"use client";

import { AnimatePresence, motion } from "framer-motion";
import { X } from "lucide-react";
import { ReactNode, useCallback, useEffect, useState } from "react";

import { ContactForm, LeadIntent, LeadType, trackLeadEvent } from "@/components/contact-form";

type LeadModalProviderProps = {
  children: ReactNode;
};

const pathLeadTypes: Array<[string, LeadType]> = [
  ["bs-reporter", "bs_reporter"],
  ["beds24", "beds24"],
  ["hotelska", "beds24"],
  ["pda", "pda_wms"],
  ["wms", "pda_wms"],
  ["vps", "vps"],
  ["tracking", "tracking"],
  ["analytics", "tracking"],
  ["seo", "seo_aeo_geo"],
  ["aeo", "seo_aeo_geo"],
  ["geo", "seo_aeo_geo"],
  ["biznisoft", "biznisoft"],
  ["erp", "biznisoft"],
  ["ecommerce", "ecommerce"],
  ["kurirske", "ecommerce"],
  ["feedovi", "ecommerce"],
  ["marketplace", "ecommerce"],
];

function inferLeadType(pathname: string): LeadType {
  const normalized = pathname.toLowerCase();
  return pathLeadTypes.find(([needle]) => normalized.includes(needle))?.[1] ?? "general";
}

function pageSubjectFallback() {
  if (typeof document === "undefined") {
    return "Upit: konsultacije";
  }

  const title = document.title.split("|")[0]?.trim();
  return title ? `Upit: ${title}` : "Upit: konsultacije";
}

function normalizeIntent(intent: LeadIntent): Required<LeadIntent> {
  const pathname = typeof window !== "undefined" ? `${window.location.pathname}${window.location.search}` : "/";
  const leadType = intent.leadType ?? inferLeadType(pathname);

  return {
    leadType,
    subject: intent.subject ?? pageSubjectFallback(),
    sourcePage: intent.sourcePage ?? pathname,
    sourceSection: intent.sourceSection ?? "CTA",
  };
}

export function LeadModalProvider({ children }: LeadModalProviderProps) {
  const [intent, setIntent] = useState<Required<LeadIntent> | null>(null);

  const openModal = useCallback((nextIntent: LeadIntent) => {
    const normalized = normalizeIntent(nextIntent);
    setIntent(normalized);
    trackLeadEvent("lead_modal_open", {
      lead_type: normalized.leadType,
      subject: normalized.subject,
      source_page: normalized.sourcePage,
      source_section: normalized.sourceSection,
      service: normalized.leadType,
    });
  }, []);

  const closeModal = useCallback(() => {
    setIntent(null);
  }, []);

  useEffect(() => {
    function handleClick(event: MouseEvent) {
      const target = event.target;
      const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
      const anchor = element?.closest<HTMLAnchorElement>('a[data-contact-cta="true"]');
      const contactLink = element?.closest<HTMLAnchorElement>('a[href^="tel:"], a[href^="mailto:"]');
      const trackedElement = element?.closest<HTMLElement>("[data-track-event]");

      if (trackedElement && !anchor) {
        trackLeadEvent(trackedElement.dataset.trackEvent ?? "site_interaction", {
          cta_label: trackedElement.dataset.trackLabel ?? trackedElement.textContent?.trim(),
          href: trackedElement instanceof HTMLAnchorElement ? trackedElement.href : undefined,
          source_page: `${window.location.pathname}${window.location.search}`,
          source_section: trackedElement.dataset.sourceSection ?? "Tracked interaction",
        });
      }

      if (contactLink && !anchor) {
        trackLeadEvent(contactLink.href.startsWith("tel:") ? "phone_click" : "email_click", {
          href: contactLink.href,
          cta_label: contactLink.textContent?.trim(),
          source_page: `${window.location.pathname}${window.location.search}`,
          source_section: contactLink.dataset.sourceSection ?? "Contact link",
        });
      }

      if (!anchor) return;
      if (anchor.target === "_blank" || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;

      event.preventDefault();

      const nextIntent = normalizeIntent({
        leadType: (anchor.dataset.leadType as LeadType | undefined) ?? undefined,
        subject: anchor.dataset.leadSubject,
        sourcePage: anchor.dataset.sourcePage ?? `${window.location.pathname}${window.location.search}`,
        sourceSection: anchor.dataset.sourceSection ?? anchor.textContent?.trim() ?? "CTA",
      });

      const sourceSection = nextIntent.sourceSection;
      const eventName = /case|reference/i.test(sourceSection) ? "case_study_cta_click" : "cta_click";

      trackLeadEvent(eventName, {
        lead_type: nextIntent.leadType,
        subject: nextIntent.subject,
        cta_label: anchor.textContent?.trim(),
        source_page: nextIntent.sourcePage,
        source_section: sourceSection,
        service: nextIntent.leadType,
      });

      openModal(nextIntent);
    }

    document.addEventListener("click", handleClick, true);
    return () => document.removeEventListener("click", handleClick, true);
  }, [openModal]);

  useEffect(() => {
    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") closeModal();
    }

    document.addEventListener("keydown", handleEscape);
    return () => document.removeEventListener("keydown", handleEscape);
  }, [closeModal]);

  return (
    <>
      {children}
      <AnimatePresence>
        {intent ? (
          <motion.div
            className="fixed inset-0 z-[100] flex items-end justify-center bg-slate-950/55 px-3 py-4 backdrop-blur-sm sm:items-center sm:p-6"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.16 }}
            role="dialog"
            aria-modal="true"
            aria-label="Kontakt forma"
          >
            <motion.div
              className="relative max-h-[calc(100dvh-1.5rem)] w-full max-w-3xl overflow-y-auto overscroll-contain rounded-2xl border border-slate-200 bg-white shadow-[0_30px_100px_rgb(15_23_42_/_0.28)] sm:max-h-[92vh]"
              initial={{ opacity: 0, y: 18, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 18, scale: 0.98 }}
              transition={{ duration: 0.18, ease: "easeOut" }}
            >
              <div className="sticky top-0 z-10 flex items-start justify-between gap-4 border-b border-slate-200 bg-white/95 px-5 py-4 backdrop-blur sm:px-6">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.16em] text-primary">ECOM01 upit</p>
                  <h2 className="mt-1 text-xl font-semibold text-slate-950">{intent.subject}</h2>
                  <p className="mt-1 text-sm text-slate-500">Forma pamti izvor CTA dugmeta i tip zahteva.</p>
                </div>
                <button
                  type="button"
                  aria-label="Zatvori kontakt formu"
                  onClick={closeModal}
                  className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-700 transition hover:border-slate-300 hover:bg-slate-50"
                >
                  <X className="h-5 w-5" strokeWidth={1.8} />
                </button>
              </div>
              <div className="p-4 sm:p-6">
                <ContactForm
                  key={`${intent.leadType}-${intent.subject}-${intent.sourceSection}`}
                  leadType={intent.leadType}
                  subject={intent.subject}
                  sourcePage={intent.sourcePage}
                  sourceSection={intent.sourceSection}
                  inModal
                  onCancel={closeModal}
                  onSuccess={() => undefined}
                />
              </div>
            </motion.div>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </>
  );
}
