---
import '@styles/global.css';
import { Image } from 'astro:assets';
import OpenSourceCard from '@components/dv-OpenSourceCard.astro';
import GruntworkLogo from '@assets/gruntwork-logo.svg';
import PatternDots from '@assets/pattern-dots.png';
import IconTerratest from '@assets/icon-terratest.svg';
import IconBoilerplate from '@assets/icon-boilerplate.svg';
import IconCloudnuke from '@assets/icon-cloudnuke.svg';
import IconGitxargs from '@assets/icon-gitxargs.svg';
import Button from '@components/ui/Button.tsx';
import { ArrowRight } from 'lucide-react';

---
<footer class="flex flex-col bg-[#FAFAFA]">
    <div class="max-w-[1312px] mx-auto w-full">
        <!-- Subscribe to Newsletter Responsiveness-->
        <div class="bg-bg-dark flex flex-col md:flex-row items-center justify-between gap-4 px-6 py-6 lg:px-20">
        <p class="text-white w-full md:flex-1 select-none leading-7">
            Join the Terragrunt Newsletter!<br />
            <span class="text-gray-1"> Hear about the latest updates, features and innovations in Terragrunt.</span>
        </p>
        <div class="flex w-full md:w-[402px] items-center gap-3">
            <!-- Newsletter Form -->
            <form id="custom-subscribe-form" class="custom-form flex w-full items-center gap-3" data-form-id="437b604f-ae08-40cf-b68f-707ae19ab6e9" data-portal-id="8376079">
              <label for="email" class="sr-only">Email address</label>
              <input
                id="email"
                name="email"
                class="flex w-full p-3 bg-white/10 rounded-lg text-sm font-sans text-white placeholder-gray-300 border border-transparent focus:border-white/20 focus:outline-none transition-colors"
                type="email"
                placeholder="Your email here"
                required
                aria-describedby="email-description"
              />
              <Button id="Newsletter-Submit" type="submit" variant="primary" size="icon">
                <ArrowRight className="w-5 h-5" aria-label="External link icon" />
              </Button>
            </form>

            <!-- Success Message -->
            <div class="success-message hidden w-full items-center justify-center gap-3 py-3 px-4 bg-green-500/20 border border-green-400/30 rounded-lg">
                <div class="checkmark flex items-center justify-center w-6 h-6 bg-green-500 rounded-full text-white text-sm font-bold">✓</div>
                <p class="text-white text-sm font-medium">Thank you for subscribing!</p>
            </div>
        </div>
    </div>

    <!-- Divider -->
    <div class="relative w-full h-[13px] bg-gradient-to-l from-[#4F2FD0] to-bg-dark overflow-hidden">
        <Image
            src={PatternDots}
            alt="Pattern Dots"
            class="absolute inset-0 w-full h-full object-cover z-0 pointer-events-none select-none"
        />
    </div>

    <!-- Other Tools -->
    <div class="flex flex-col">
        <div class="flex items-center px-8 py-6">
            <p class="font-sans text-xl text-dark-blue-1">Check out our other open source tools</p>
        </div>
        <div class="flex flex-col md:flex-row w-full">
            <OpenSourceCard
                icon={IconTerratest}
                title="Terratest"
                description="Validate IaC modules"
                href="https://terratest.gruntwork.io/"
            />
            <OpenSourceCard
                icon={IconBoilerplate}
                title="Boilerplate"
                description="Automate repetitive DevOps work"
                href="https://github.com/gruntwork-io/boilerplate"
            />
            <OpenSourceCard
                icon={IconCloudnuke}
                title="CloudNuke"
                description="Save money on unused AWS resources"
                href="https://github.com/gruntwork-io/cloud-nuke"
            />
            <OpenSourceCard
                icon={IconGitxargs}
                title="GitXargs"
                description="Make changes across git repos"
                href="https://github.com/gruntwork-io/git-xargs"
            />
        </div>
    </div>

    <!-- Copyright -->
    <div class="flex flex-col md:flex-row items-start md:items-center md:justify-between py-6 px-6 bg-[#FAFAFA] mt-auto gap-3">
        <div class="flex items-center gap-2">
            <Image src={GruntworkLogo} alt="Gruntwork Logo" class="w-[30px] h-[30px]" />
            <span class="text-sm text-[#777888]">From the DevOps experts at
              <a href="https://gruntwork.io" class="text-accent-1 no-underline border-b border-gray-1 hover:cursor-pointer hover:text-accent transition duration-100 ease-in-out">
                Gruntwork
              </a>
            </span>
        </div>
        <div>
            <p class="text-center text-sm text-gray-1 select-none">
                &copy; {new Date().getFullYear()} Gruntwork, Inc. All rights reserved.
            </p>
        </div>
    </div>
    </div>
</footer>

<script src="https://js.hsforms.net/forms/v2.js"></script>

<script>
  document.addEventListener("DOMContentLoaded", function () {
    const customForm = document.getElementById("custom-subscribe-form");
    const submitButton = document.getElementById("Newsletter-Submit");
    const successMessage = document.querySelector(".success-message");
    const emailInput = document.querySelector('input[name="email"]');

    if (customForm && submitButton && successMessage && emailInput) {
      customForm.addEventListener("submit", async (e) => {
        e.preventDefault();
        console.log("start fired");

        // Disable form while submitting
        submitButton.setAttribute('disabled', 'true');
        emailInput.setAttribute('disabled', 'true');

        const email = (emailInput as HTMLInputElement).value;
        const portalId = customForm.getAttribute("data-portal-id");
        const formId = customForm.getAttribute("data-form-id");

        if (!portalId || !formId) {
          console.error("Missing portal ID or form ID");
          resetFormState();
          return;
        }

        const data = {
          submittedAt: Date.now(),
          fields: [{ name: "email", value: email }],
          context: {
            pageUri: window.location.href,
            pageName: document.title,
          },
        };

        try {
          const response = await fetch(
            `https://api.hsforms.com/submissions/v3/integration/submit/${portalId}/${formId}`,
            {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(data),
            }
          );

          if (!response.ok) throw new Error("Network response was not ok");

          console.log("Form submitted:", await response.json());

          // Animate out the form and show success message
          customForm.style.opacity = "0";
          customForm.style.transform = "translateY(-10px)";

          setTimeout(() => {
            customForm.classList.add("hidden");
            successMessage.classList.remove("hidden");
            (successMessage as HTMLElement).style.opacity = "0";
            (successMessage as HTMLElement).style.transform = "translateY(10px)";
            (successMessage as HTMLElement).offsetHeight; // trigger reflow
            (successMessage as HTMLElement).style.opacity = "1";
            (successMessage as HTMLElement).style.transform = "translateY(0)";
            (successMessage as HTMLElement).style.transition = "opacity 0.3s ease, transform 0.3s ease";
          }, 200);
        } catch (error) {
          console.error("Error:", error);
          resetFormState();
        }
      });

      function resetFormState() {
        if (submitButton) {
          submitButton.removeAttribute('disabled');
        }
        if (emailInput) {
          emailInput.removeAttribute('disabled');
        }
      }
    }
  });
</script>
