/* global React, FramerMotion */
/* Shared chrome: Navbar (top-center pill), Footer, CtaPill */
const { motion: M, AnimatePresence: AP } = FramerMotion;
const RH = React;

/* Filter framer-motion 11.x's internal "key prop" warning. It's emitted from
   framer-motion's own AnimatePresence internals, not from our code, and is
   harmless. We do this once per page. */
(function silenceFramerKeyWarning() {
  if (window.__captixyConsoleFiltered) return;
  window.__captixyConsoleFiltered = true;
  const _e = console.error;
  console.error = function (...args) {
    const first = typeof args[0] === "string" ? args[0] : "";
    if (first.includes('unique "key" prop')) {
      const trace = args.map(String).join(" ");
      if (trace.includes("framer-motion") || trace.includes("Navbar")) return;
    }
    _e.apply(console, args);
  };
})();

/* One unified menu used by every page. Hash anchors point at the landing
   page so the link works regardless of where the user is currently. */
const NAV_ITEMS = [
  { label: "Início",   href: "index.html" },
  { label: "Planos",   href: "pricing.html" },
  { label: "Sobre",    href: "about.html" },
  { label: "Login",    href: "https://app.captixy.com/login" },
];
// Back-compat aliases so older call sites keep working.
const NAV_ITEMS_HOME = NAV_ITEMS;
const NAV_ITEMS_PAGE = NAV_ITEMS;

/* Brand mark — logo image + wordmark.
   Use `size="sm"` for footers, default `md` for nav. */
function LogoMark({ size = "md", showWordmark = true, href = "index.html" }) {
  const dims = {
    sm: { img: "w-7 h-7", word: "text-lg", star: "text-[10px]", gap: "gap-2" },
    md: { img: "w-9 h-9 md:w-10 md:h-10", word: "text-xl md:text-2xl", star: "text-xs", gap: "gap-2.5" },
    lg: { img: "w-14 h-14", word: "text-3xl sm:text-4xl", star: "text-xl", gap: "gap-3" },
  }[size];
  const inner = (
    <span className={`inline-flex items-center ${dims.gap}`}>
      <span className="relative inline-flex">
        <img
          src="assets/captixy-icon.svg"
          alt="Captixy"
          width="512"
          height="512"
          className={`${dims.img} block select-none rounded-[22%]`}
          draggable="false"
        />
        {/* coral halo behind the mark */}
        <span
          className="absolute inset-0 -z-10 rounded-[28%] blur-md opacity-70 pointer-events-none"
          style={{ background: "radial-gradient(circle at 50% 50%, rgba(255,107,115,0.55), transparent 70%)" }}
        />
      </span>
      {showWordmark && (
        <span
          className={`${dims.word} font-medium tracking-[-0.04em] leading-none`}
          style={{ color: "#F7F8FF" }}
        >
          Captixy
          <span className={`serif italic align-baseline ml-0.5 ${dims.star}`} style={{ color: "#FF8289" }}>*</span>
        </span>
      )}
    </span>
  );
  return href ? <a href={href} className="inline-flex items-center group">{inner}</a> : inner;
}

function Navbar({ items /* ignored — kept for back-compat */, cta = true }) {
  const [open, setOpen] = RH.useState(false);
  const [scrolled, setScrolled] = RH.useState(false);

  RH.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  RH.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const pillBg = scrolled
    ? "bg-[#070B1F]/85 backdrop-blur-md hairline-strong"
    : "bg-[#070B1F]/55 backdrop-blur hairline";

  return (
    <>
      {/* LOGO — fixed top-left of viewport */}
      <M.div
        initial={{ x: -24, opacity: 0 }}
        animate={{ x: 0, opacity: 1 }}
        transition={{ duration: 0.9, ease: window.EASE_EXPO, delay: 0.15 }}
        className="fixed top-3 left-3 sm:top-4 sm:left-5 md:top-5 md:left-7 z-50"
      >
        <LogoMark size="md" />
      </M.div>

      {/* NAV PILL — fixed bar that fills viewport width and centers the pill
         via flex. The M.nav animates only y/opacity so framer-motion's
         transform never fights with Tailwind's -translate-x-1/2. */}
      <div className="hidden md:flex fixed top-4 lg:top-5 inset-x-0 z-50 justify-center pointer-events-none">
        <M.nav
          initial={{ y: -28, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ duration: 0.9, ease: window.EASE_EXPO, delay: 0.2 }}
          className="pointer-events-auto"
        >
          <div className={`rounded-full px-6 lg:px-7 py-2.5 transition-all duration-300 ${pillBg}`}>
            <ul className="flex items-center gap-7 lg:gap-9 whitespace-nowrap">
              {NAV_ITEMS.map((it) => (
                <li key={it.label}>
                  <a
                    href={it.href}
                    className="text-[12px] lg:text-[13px] tracking-wide transition-colors link-underline"
                    style={{ color: "rgba(225,224,204,0.82)" }}
                    onMouseEnter={(e) => (e.currentTarget.style.color = "#F7F8FF")}
                    onMouseLeave={(e) => (e.currentTarget.style.color = "rgba(225,224,204,0.82)")}
                  >
                    {it.label}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </M.nav>
      </div>

      {/* CTA — fixed top-right of viewport */}
      {cta && (
        <M.div
          initial={{ x: 24, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          transition={{ duration: 0.9, ease: window.EASE_EXPO, delay: 0.25 }}
          className="hidden md:block fixed top-4 lg:top-5 right-4 lg:right-7 z-50"
        >
          <a
            href="index.html#cta"
            className="group inline-flex items-center gap-2 hover:gap-3 transition-all btn-coral rounded-full pl-4 lg:pl-5 pr-1 py-1 text-xs lg:text-sm font-medium"
          >
            Pedir acesso
            <span className="inline-flex items-center justify-center bg-[#070B1F]/30 text-white rounded-full w-7 h-7 lg:w-8 lg:h-8 transition-transform group-hover:scale-110">
              <window.IconArrowRight className="w-3.5 h-3.5" />
            </span>
          </a>
        </M.div>
      )}

      {/* HAMBURGER — fixed top-right, mobile only */}
      <M.button
        initial={{ x: 24, opacity: 0 }}
        animate={{ x: 0, opacity: 1 }}
        transition={{ duration: 0.9, ease: window.EASE_EXPO, delay: 0.2 }}
        onClick={() => setOpen(true)}
        className={`md:hidden fixed top-3 right-3 z-50 w-11 h-11 rounded-full ${pillBg} flex items-center justify-center text-primary transition-colors duration-300`}
        aria-label="Abrir menu"
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="w-5 h-5">
          <path d="M4 8h16M4 14h16" strokeLinecap="round" />
        </svg>
      </M.button>

      {/* MOBILE DRAWER */}
      <AP>
        {open && <MobileDrawer key="drawer" onClose={() => setOpen(false)} />}
      </AP>
    </>
  );
}

function MobileDrawer({ onClose }) {
  return (
    <>
      {/* scrim */}
      <M.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.3 }}
        onClick={onClose}
        className="md:hidden fixed inset-0 bg-black/65 backdrop-blur-sm z-[60]"
      />
      {/* panel */}
      <M.div
        initial={{ x: "100%" }}
        animate={{ x: 0 }}
        exit={{ x: "100%" }}
        transition={{ duration: 0.55, ease: window.EASE_EXPO }}
        className="md:hidden fixed top-0 right-0 bottom-0 w-[86vw] max-w-[380px] z-[70] flex flex-col overflow-hidden"
        style={{ background: "#111530" }}
      >
        <div className="absolute inset-0 aurora opacity-70 pointer-events-none" />
        <div className="absolute inset-0 noise-overlay opacity-30 mix-blend-overlay pointer-events-none" />
        <div className="absolute inset-0 bg-gradient-to-b from-transparent via-transparent to-black/40 pointer-events-none" />

        {/* drawer header */}
        <div className="relative flex items-center justify-between px-5 py-4 border-b border-white/10">
          <LogoMark size="sm" />
          <button
            onClick={onClose}
            className="w-10 h-10 rounded-full hairline-strong flex items-center justify-center text-primary/85 hover:text-primary transition-colors"
            aria-label="Fechar menu"
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="w-4 h-4">
              <path d="M6 6l12 12M6 18L18 6" strokeLinecap="round" />
            </svg>
          </button>
        </div>

        {/* nav list */}
        <nav className="relative flex-1 overflow-y-auto px-5 py-7">
          <div className="eyebrow-orange mb-5">Menu</div>
          <ul>
            {NAV_ITEMS.map((it, i) => (
              <M.li
                key={it.label}
                initial={{ x: 24, opacity: 0 }}
                animate={{ x: 0, opacity: 1 }}
                transition={{ duration: 0.5, delay: 0.18 + i * 0.06, ease: window.EASE_EXPO }}
              >
                <a
                  href={it.href}
                  onClick={onClose}
                  className="group flex items-center justify-between py-3.5 border-b border-white/5 text-primary text-xl tracking-tight"
                >
                  <span className="flex items-center gap-3">
                    <span className="text-[10px] text-primary/30 tracking-[0.18em]">
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    {it.label}
                  </span>
                  <span className="inline-flex w-7 h-7 rounded-full bg-[#1A1E3A] hairline items-center justify-center text-primary/45 group-hover:text-orange group-hover:translate-x-1 transition-all">
                    <window.IconArrowRight className="w-3.5 h-3.5" />
                  </span>
                </a>
              </M.li>
            ))}
          </ul>

          <M.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.55, ease: window.EASE_EXPO }}
            className="mt-9 grid grid-cols-2 gap-2 text-[11px] text-primary/40"
          >
            <a href="privacy.html" onClick={onClose} className="link-underline">Privacidade</a>
            <a href="terms.html" onClick={onClose} className="link-underline text-right">Termos</a>
            <a href="mailto:contact@captixy.com" onClick={onClose} className="link-underline col-span-2 pt-3 border-t border-white/5 text-primary/55">
              contact@captixy.com
            </a>
          </M.div>
        </nav>

        {/* drawer footer CTA */}
        <M.div
          initial={{ y: 24, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ duration: 0.6, delay: 0.6, ease: window.EASE_EXPO }}
          className="relative px-5 py-5 border-t border-white/10"
        >
          <a
            href="index.html#cta"
            onClick={onClose}
            className="group flex items-center justify-between gap-2 btn-coral rounded-full pl-5 pr-1.5 py-1.5 text-sm font-medium"
          >
            Pedir acesso antecipado
            <span className="inline-flex items-center justify-center bg-[#070B1F]/30 text-white rounded-full w-9 h-9 transition-transform group-hover:scale-110">
              <window.IconArrowRight className="w-4 h-4" />
            </span>
          </a>
          <div className="mt-3 text-[10px] text-primary/35 text-center tracking-wide">
            © 2026 Captixy · Feito em Portugal
          </div>
        </M.div>
      </M.div>
    </>
  );
}

/* Pill CTA — primary orange with black circle + arrow.
   variant: "orange" (default) | "cream" | "ghost" | "ghost-cream" | "ink" */
function CtaPill({ children, href = "#cta", variant = "orange", size = "md", onClick }) {
  const sizes = {
    sm: { pad: "pl-4 pr-1.5 py-1.5", text: "text-xs sm:text-sm", circle: "w-7 h-7" },
    md: { pad: "pl-5 pr-1.5 py-1.5", text: "text-sm sm:text-base", circle: "w-9 h-9 sm:w-10 sm:h-10" },
    lg: { pad: "pl-7 pr-2 py-2",     text: "text-base sm:text-lg", circle: "w-11 h-11 sm:w-12 sm:h-12" },
  }[size];

  const variantClasses = {
    orange: "btn-coral",
    cream:  "bg-primary text-black",
    ghost:  "btn-ghost-dark",
    "ghost-cream": "btn-ghost-dark",
    ink:    "bg-ink text-cream",
  }[variant];

  const circleClasses = {
    orange: "bg-[#070B1F]/30 text-white",
    cream:  "bg-black text-primary",
    ghost:  "bg-orange text-white",
    "ghost-cream": "bg-orange text-white",
    ink:    "bg-cream text-ink",
  }[variant];

  return (
    <a
      href={href}
      onClick={onClick}
      className={`group inline-flex items-center gap-2 hover:gap-3 transition-all duration-300 rounded-full font-medium ${sizes.pad} ${sizes.text} ${variantClasses}`}
    >
      <span>{children}</span>
      <span className={`inline-flex items-center justify-center rounded-full transition-transform duration-300 group-hover:scale-110 ${sizes.circle} ${circleClasses}`}>
        <window.IconArrowRight className="w-4 h-4" />
      </span>
    </a>
  );
}

/* Footer */
function Footer() {
  return (
    <footer className="bg-[#070B1F] border-t border-white/5">
      <div className="max-w-7xl mx-auto px-6 md:px-8 py-14 md:py-20">
        <div className="grid grid-cols-2 md:grid-cols-12 gap-10">
          <div className="col-span-2 md:col-span-5">
            <LogoMark size="lg" />
            <p className="mt-5 max-w-sm text-sm text-primary/60 leading-relaxed">
              Uma assistente virtual AI que capta, responde e qualifica leads.
              Partilhável por link, QR code ou embed no website.
            </p>
            <div className="mt-7 flex items-center gap-3">
              <CtaPill href="index.html#cta" size="sm">Pedir acesso</CtaPill>
            </div>
          </div>

          <div className="md:col-span-2">
            <div className="eyebrow mb-4">Produto</div>
            <ul className="space-y-2.5 text-sm text-primary/75">
              <li><a className="link-underline" href="index.html#demo">Demonstração</a></li>
              <li><a className="link-underline" href="index.html#features">Funcionalidades</a></li>
              <li><a className="link-underline" href="pricing.html">Planos</a></li>
              <li><a className="link-underline" href="index.html#how">Como funciona</a></li>
            </ul>
          </div>

          <div className="md:col-span-2">
            <div className="eyebrow mb-4">Empresa</div>
            <ul className="space-y-2.5 text-sm text-primary/75">
              <li><a className="link-underline" href="about.html">Sobre</a></li>
              <li><a className="link-underline" href="mailto:contact@captixy.com">Contacto</a></li>
              <li><a className="link-underline" href="index.html#cta">Acesso antecipado</a></li>
            </ul>
          </div>

          <div className="md:col-span-3">
            <div className="eyebrow mb-4">Legal</div>
            <ul className="space-y-2.5 text-sm text-primary/75">
              <li><a className="link-underline" href="privacy.html">Privacidade</a></li>
              <li><a className="link-underline" href="terms.html">Termos</a></li>
            </ul>
          </div>
        </div>

        <div className="mt-14 pt-7 border-t border-white/5 flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between text-xs text-primary/40">
          <div>© 2026 Captixy. Feito em Portugal.</div>
          <div className="flex items-center gap-4">
            <span>Early access</span>
            <span className="w-1 h-1 rounded-full bg-primary/30" />
            <span>v0.9</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Navbar, CtaPill, Footer, LogoMark, NAV_ITEMS_HOME, NAV_ITEMS_PAGE });
