"use client";

import { FormEvent, MouseEvent, useEffect, useState } from "react";
import SiteHeader from "../components/SiteHeader";
import HeroSection from "../components/HeroSection";
import ProblemSection from "../components/ProblemSection";
import ProcessSection from "../components/ProcessSection";
import DeliverabilitySection from "../components/DeliverabilitySection";
import ContinuitySection, { type ContinuityFeature, type FeatureKey } from "../components/ContinuitySection";
import MigrationProcessSection from "../components/MigrationProcessSection";
import PricingSection, { type Plan } from "../components/PricingSection";
import FaqSection from "../components/FaqSection";
import AssessmentSection from "../components/AssessmentSection";
import SiteFooter from "../components/SiteFooter";


type Theme = "dark" | "light";
const pricingSummaries: Record<Plan, string> = {
  hosting:
    "Core business email hosting with 25 GB mailboxes, custom domain email, and AWS-backed infrastructure.",
  managed:
    "Managed setup adds rollout planning, DNS validation, migration coordination, and device handoff checks during the assessment.",
};

const continuityFeatures: Record<FeatureKey, ContinuityFeature> = {
  buffering: {
    title: "Inbound buffering",
    copy: "Incoming mail can be buffered before mailbox delivery during maintenance or provider-side disruption.",
    proof: [
      "Supports planned maintenance windows",
      "Keeps delivery flow observable",
      "Feeds mailbox delivery after processing",
    ],
  },
  sending: {
    title: "Outbound sending",
    copy: "Amazon SES gives outbound email an authenticated sending path with reputation tooling and clearer operational visibility.",
    proof: [
      "Separates outbound sending from old shared hosting mail",
      "Uses domain authentication as part of setup",
      "Makes sending behavior easier to troubleshoot",
    ],
  },
  standby: {
    title: "Standby failover",
    copy: "A standby environment is part of the continuity plan when primary systems need intervention or provider-side work.",
    proof: [
      "Keeps the fallback path visible",
      "Reduces guesswork during incidents",
      "Pairs with status checks and local support",
    ],
  },
  local: {
    title: "Local management",
    copy: "Domain records, migration, mailbox changes, device setup, and troubleshooting stay with a local Corpus Christi team.",
    proof: [
      "One support path for DNS and devices",
      "Migration scope is reviewed before work starts",
      "Mailbox changes stay tied to the business context",
    ],
  },
};

export default function Page() {
  const [menuOpen, setMenuOpen] = useState(false);
  const [theme, setTheme] = useState<Theme>("dark");
  const [activeFeature, setActiveFeature] = useState<FeatureKey>("buffering");
  const [activePlan, setActivePlan] = useState<Plan>("hosting");
  const [mailboxes, setMailboxes] = useState(25);
  const [formErrors, setFormErrors] = useState({ name: "", email: "" });
  const [formStatus, setFormStatus] = useState("");
  const activeFeatureDetails = continuityFeatures[activeFeature];

  useEffect(() => {
    const storedTheme = window.localStorage.getItem("bes-theme");
    setTheme(storedTheme === "light" ? "light" : "dark");
  }, []);

  useEffect(() => {
    document.documentElement.dataset.theme = theme;
    window.localStorage.setItem("bes-theme", theme);
  }, [theme]);

  useEffect(() => {
    document.body.classList.toggle("menu-open", menuOpen);
    return () => document.body.classList.remove("menu-open");
  }, [menuOpen]);

  useEffect(() => {
    const scrollProgress = document.querySelector<HTMLElement>(".scroll-progress");
    if (!scrollProgress) {
      return;
    }

    let ticking = false;
    const updateScrollProgress = () => {
      const maxScroll = document.documentElement.scrollHeight - window.innerHeight;
      const progress = maxScroll > 0 ? window.scrollY / maxScroll : 0;
      scrollProgress.style.setProperty("--scroll-progress", Math.min(Math.max(progress, 0), 1).toFixed(4));
      ticking = false;
    };
    const onScroll = () => {
      if (ticking) {
        return;
      }
      ticking = true;
      requestAnimationFrame(updateScrollProgress);
    };

    updateScrollProgress();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const revealItems = [
      document.querySelector(".hero-copy"),
      document.querySelector(".architecture-panel"),
      ...document.querySelectorAll(".module-card"),
      document.querySelector(".local-strip"),
      ...document.querySelectorAll(".content-section > *"),
    ].filter((item): item is Element => item instanceof Element);

    revealItems.forEach((item, index) => {
      if (item instanceof HTMLElement) {
        item.classList.add("reveal-item");
        item.style.setProperty("--reveal-delay", `${Math.min(index % 4, 3) * 85}ms`);
      }
    });

    const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (prefersReducedMotion || !("IntersectionObserver" in window)) {
      revealItems.forEach((item) => item instanceof HTMLElement && item.classList.add("is-revealed"));
      return;
    }

    document.body.classList.add("motion-ready");
    const revealObserver = new IntersectionObserver(
      (entries, observer) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) {
            return;
          }
          entry.target.classList.add("is-revealed");
          observer.unobserve(entry.target);
        });
      },
      {
        threshold: 0.18,
        rootMargin: "0px 0px -8% 0px",
      },
    );

    revealItems.forEach((item) => revealObserver.observe(item));
    return () => {
      revealObserver.disconnect();
      document.body.classList.remove("motion-ready");
    };
  }, []);

  const handleNavClick = (event: MouseEvent<HTMLElement>) => {
    if (event.target instanceof HTMLAnchorElement) {
      setMenuOpen(false);
    }
  };

  const handleAssessmentSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const form = event.currentTarget;
    const formData = new FormData(form);
    const name = String(formData.get("name") || "").trim();
    const email = String(formData.get("email") || "").trim();
    const nextErrors = {
      name: name ? "" : "Please enter your name.",
      email: "",
    };

    if (!email) {
      nextErrors.email = "Please enter your business email.";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      nextErrors.email = "Email address needs to include an @ symbol.";
    }

    setFormErrors(nextErrors);
    setFormStatus("");

    if (nextErrors.name || nextErrors.email) {
      window.requestAnimationFrame(() => {
        document.getElementById(nextErrors.name ? "name" : "email")?.focus();
      });
      return;
    }

    setFormStatus("Thanks. We'll review your mailbox count and current provider before we reply.");
    form.reset();
  };

  return (
    <>
      <a className="skip-link" href="#main">Skip to content</a>
      <div className="scroll-progress" aria-hidden="true"></div>

      <SiteHeader
        menuOpen={menuOpen}
        theme={theme}
        onMenuToggle={() => setMenuOpen((isOpen) => !isOpen)}
        onThemeToggle={() => setTheme((currentTheme) => (currentTheme === "light" ? "dark" : "light"))}
        onNavClick={handleNavClick}
      />

      <main id="main">
        <HeroSection />
        <ProblemSection />
        <ProcessSection />
        <DeliverabilitySection />
        <ContinuitySection
          activeFeature={activeFeature}
          activeFeatureDetails={activeFeatureDetails}
          onFeatureChange={setActiveFeature}
        />
        <MigrationProcessSection />
        <PricingSection
          activePlan={activePlan}
          mailboxes={mailboxes}
          pricingSummaries={pricingSummaries}
          onPlanChange={setActivePlan}
          onMailboxesChange={setMailboxes}
        />
        <FaqSection />
        <AssessmentSection
          formErrors={formErrors}
          formStatus={formStatus}
          onAssessmentSubmit={handleAssessmentSubmit}
        />
      </main>

      <SiteFooter />
    </>
  );
}
