// Header + Hero — repositioned for sitters & pet hotels.
const { motion: m1, AnimatePresence: AP1 } = window;
const { t: t1, languageUrl } = window.SW_I18N || { t: (value) => value, languageUrl: () => "#" };

const NAV_BY_AUDIENCE = {
  pets: [
    { label: "How it works", href: "#how" },
    { label: "Preview", href: "#pets-preview" },
    { label: "Contact", href: "#contact" },
  ],
  sitters: [
    { label: "Features", href: "#features" },
    { label: "Platform preview", href: "#platform-preview" },
    { label: "Contact", href: "#contact" },
  ],
};

const LanguageSwitcher = ({ mobile = false }) => {
  const lang = window.SW_I18N?.lang || "en";
  const [open, setOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  const languages = [
    { code: "en", label: "EN", aria: "Switch language to English" },
    { code: "hu", label: "HU", aria: "Switch language to Hungarian" },
    { code: "pt-br", label: "PT", aria: "Switch language to Brazilian Portuguese" },
  ];
  const current = languages.find((item) => item.code === lang) || languages[0];

  React.useEffect(() => {
    if (!open) return;
    const onPointerDown = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) setOpen(false);
    };
    const onKeyDown = (event) => {
      if (event.key === "Escape") setOpen(false);
    };
    document.addEventListener("pointerdown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("pointerdown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  if (mobile) {
    return (
      <div className="mt-3 flex gap-2">
        {languages.map((item) => (
          <a
            key={item.code}
            href={languageUrl(item.code)}
            aria-label={t1(item.aria)}
            onClick={() => window.SW_I18N?.setLangPref?.(item.code)}
            className={`inline-flex items-center justify-center rounded-full border px-3 py-1.5 text-[11.5px] font-semibold transition-colors ${
              lang === item.code
                ? "bg-forest text-cream border-forest"
                : "bg-white text-inkSoft border-line hover:border-forest/30 hover:text-forest"
            }`}
          >
            {item.label}
          </a>
        ))}
      </div>
    );
  }

  return (
    <div ref={menuRef} className="relative inline-flex">
      <button
        type="button"
        onClick={() => setOpen((value) => !value)}
        className="inline-flex min-w-[52px] items-center justify-center rounded-full border border-line bg-white px-3 py-2 text-[11.5px] font-semibold text-forest shadow-soft transition-colors hover:border-forest/30"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={t1("Select language")}
      >
        {current.label}
      </button>
      <div
        role="menu"
        aria-hidden={!open}
        className={`absolute right-0 top-full z-50 mt-2 min-w-[78px] overflow-hidden rounded-xl border border-line bg-white p-1 shadow-lift transition-all ${
          open ? "pointer-events-auto translate-y-0 opacity-100" : "pointer-events-none -translate-y-1 opacity-0"
        }`}
      >
        {languages.map((item) => (
          <a
            key={item.code}
            href={languageUrl(item.code)}
            role="menuitem"
            aria-label={t1(item.aria)}
            tabIndex={open ? 0 : -1}
            onClick={() => window.SW_I18N?.setLangPref?.(item.code)}
            className={`block rounded-lg px-3 py-2 text-center text-[12px] font-semibold transition-colors ${
              lang === item.code ? "bg-forest text-cream" : "text-inkSoft hover:bg-mint/60 hover:text-forest"
            }`}
          >
            {item.label}
          </a>
        ))}
      </div>
    </div>
  );
};

const Header = ({ audience = "pets" }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const nav = NAV_BY_AUDIENCE[audience] || NAV_BY_AUDIENCE.pets;
  React.useEffect(() => {
    const onS = () => setScrolled(window.scrollY > 8);
    onS();
    window.addEventListener("scroll", onS, { passive: true });
    return () => window.removeEventListener("scroll", onS);
  }, []);
  return (
    <header
      className={`sticky top-0 z-40 transition-all ${
        scrolled
          ? "bg-cream/85 backdrop-blur-md border-b border-line/80"
          : "bg-transparent border-b border-transparent"
      }`}
    >
      <div className="max-w-7xl mx-auto px-5 sm:px-8 lg:px-12 h-[88px] flex items-center justify-between gap-6 relative">
        <Logo height={56} />
        <nav className="hidden md:flex items-center gap-1 absolute left-1/2 -translate-x-1/2">
          {nav.map((n) => (
            <a
              key={n.label}
              href={n.href}
              className="px-3 py-2 rounded-full text-[14px] text-ink/80 hover:text-forest hover:bg-mint/60 transition-colors whitespace-nowrap"
            >
              {t1(n.label)}
            </a>
          ))}
        </nav>
        <div className="hidden md:flex">
          <LanguageSwitcher />
        </div>
        <button
          className="md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full border border-line bg-cream"
          onClick={() => setOpen((v) => !v)}
          aria-label="Menu"
        >
          {open ? <IconClose /> : <IconFilter />}
        </button>
      </div>
      <AP1>
        {open && (
          <m1.div
            key="mobile-nav"
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="md:hidden overflow-hidden border-t border-line bg-cream"
          >
            <div className="px-5 py-3 flex flex-col gap-1">
              {nav.map((n) => (
                <a key={n.label} href={n.href} onClick={() => setOpen(false)} className="py-2 text-ink">
                  {t1(n.label)}
                </a>
              ))}
              <LanguageSwitcher mobile />
            </div>
          </m1.div>
        )}
      </AP1>
    </header>
  );
};

// ----- Hero dashboard mock — admin app preview -----
const HeroMock = () => (
  <m1.div
    initial={{ opacity: 0, y: 30 }}
    animate={{ opacity: 1, y: 0 }}
    transition={{ delay: 0.45, duration: 0.8, ease: [0.2, 0.7, 0.2, 1] }}
    className="relative bg-white rounded-[26px] border border-line shadow-ring overflow-hidden"
  >
    {/* window chrome */}
    <div className="flex items-center justify-between px-4 py-3 border-b border-line bg-creamSoft/50">
      <div className="flex items-center gap-1.5">
        <span className="w-2.5 h-2.5 rounded-full bg-coral/60" />
        <span className="w-2.5 h-2.5 rounded-full bg-butter" />
        <span className="w-2.5 h-2.5 rounded-full bg-mintDeep" />
      </div>
      <div className="flex-1" />
      <div className="w-10" />
    </div>

    <div className="grid grid-cols-12 gap-0">
      {/* Sidebar */}
      <div className="hidden md:flex col-span-2 flex-col gap-1 p-3 bg-forest text-cream/85 border-r border-line min-h-[420px]">
        {[
          { i: <IconHome size={14} />, t: "Dashboard", a: true },
          { i: <IconCal size={14} />, t: "Bookings" },
          { i: <IconPaw size={14} />, t: "Pets" },
          { i: <IconUser size={14} />, t: "Clients" },
          { i: <IconCamera size={14} />, t: "Check-ins" },
          { i: <IconChart size={14} />, t: "Reports" },
        ].map((it) => (
          <div
            key={it.t}
            className={`flex items-center gap-2 px-2.5 py-2 rounded-lg text-[12.5px] ${
              it.a ? "bg-cream/15 text-cream" : "text-cream/70"
            }`}
          >
            {it.i}
            <span className="truncate">{it.t}</span>
          </div>
        ))}
      </div>

      {/* Dashboard body */}
      <div className="col-span-12 md:col-span-10 p-4 sm:p-5 bg-cream space-y-4">
        <div className="flex items-baseline justify-between">
          <div>
            <div className="font-display text-[20px] sm:text-[22px] text-forestDeep leading-none">Good morning, Sarah</div>
            <div className="text-[12.5px] text-inkSoft mt-1">Thursday · 12 June · Bristol</div>
          </div>
          <Badge tone="mint" icon={<IconBolt size={12} />}>Live</Badge>
        </div>

        {/* KPI strip */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
          {[
            { k: "Occupancy", v: "82%", s: "+6% vs last wk" },
            { k: "Today arrivals", v: "4", s: "2 confirmed" },
            { k: "Departures", v: "3", s: "1 photo pending" },
            { k: "Outstanding", v: "€480", s: "2 quotes open" },
          ].map((s) => (
            <div key={s.k} className="bg-white border border-line rounded-xl p-3">
              <div className="text-[10.5px] uppercase tracking-[0.12em] text-inkSoft">{s.k}</div>
              <div className="text-[20px] font-display text-forestDeep mt-1 leading-none">{s.v}</div>
              <div className="text-[11px] text-inkSoft mt-1">{s.s}</div>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-5 gap-3">
          {/* Bookings */}
          <div className="lg:col-span-3 bg-white border border-line rounded-xl p-3">
            <div className="flex items-center justify-between mb-2">
              <div className="text-[12px] uppercase tracking-[0.12em] text-inkSoft">Today's bookings</div>
              <span className="text-[11px] text-inkSoft">7 today</span>
            </div>
            <div className="space-y-2">
              {[
                { pet: "Luna", breed: "Beagle · M", room: "Suite 2", status: "Checked-in", tone: "mint" },
                { pet: "Pixel", breed: "Tabby · cat", room: "Cat lounge", status: "Arriving 14:00", tone: "butter" },
                { pet: "Otis", breed: "Labrador · L", room: "Suite 4", status: "Photo due", tone: "coral" },
              ].map((b, i) => (
                <m1.div
                  key={b.pet}
                  initial={{ opacity: 0, x: -8 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.7 + i * 0.1 }}
                  className="flex items-center gap-3 p-2 bg-cream border border-line rounded-lg"
                >
                  <Photo ratio="1/1" className="w-9 flex-none" rounded="rounded-lg" cat={i === 1 ? "cat" : "dog"} idx={i} w={120} alt={b.pet} />
                  <div className="flex-1 min-w-0">
                    <div className="text-[13px] font-semibold text-forestDeep truncate">{b.pet}</div>
                    <div className="text-[11px] text-inkSoft truncate">{b.breed} · {b.room}</div>
                  </div>
                  <Badge tone={b.tone}>{b.status}</Badge>
                </m1.div>
              ))}
            </div>
          </div>

          {/* Capacity bar */}
          <div className="lg:col-span-2 bg-white border border-line rounded-xl p-3">
            <div className="text-[12px] uppercase tracking-[0.12em] text-inkSoft mb-2">Capacity this week</div>
            <div className="flex items-end gap-1.5 h-[100px]">
              {[55, 70, 88, 82, 95, 78, 60].map((v, i) => (
                <m1.div
                  key={i}
                  initial={{ height: 0 }}
                  animate={{ height: `${v}%` }}
                  transition={{ delay: 0.8 + i * 0.06, duration: 0.6, ease: "easeOut" }}
                  className={`flex-1 rounded-md ${i === 4 ? "bg-coral" : "bg-forest/85"}`}
                />
              ))}
            </div>
            <div className="flex justify-between text-[10px] text-inkSoft mt-2 font-mono">
              <span>M</span><span>T</span><span>W</span><span>T</span><span>F</span><span>S</span><span>S</span>
            </div>
            <div className="mt-3 pt-3 border-t border-line flex items-center justify-between text-[12px]">
              <span className="text-inkSoft">Peak Friday</span>
              <span className="font-semibold text-forestDeep">12 / 13 rooms</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </m1.div>
);

const HERO_BY_AUDIENCE = {
  pets: {
    eyebrow: "For pet owners",
    h1a: "Find pet care",
    h1b: "you can trust",
    sub:
      "Find verified pet sitters and pet hotels with clear profiles, real photos, care details, reviews, and a simple way to ask questions before you book.",
    primary: null,
    secondary: "See how it works",
    secondaryHref: "#how",
  },
  sitters: {
    eyebrow: "For sitters &amp; pet hotels",
    h1a: "Run your pet care business",
    h1b: "like a pro",
    sub:
      "StayWise helps pet sitters and pet hotels present a trusted profile, receive clearer requests, and manage bookings, pets, check-ins, and payments with less admin stress.",
    primary: "Talk to the team",
    primaryHref: "#contact",
    secondary: "See how it works",
    secondaryHref: "#features",
  },
};

const Hero = ({ audience = "pets" }) => {
  const h = HERO_BY_AUDIENCE[audience] || HERO_BY_AUDIENCE.pets;
  return (
    <section id="top" className="relative pt-8 sm:pt-12 pb-12 sm:pb-20">
      <div className="absolute inset-0 grain pointer-events-none" />

      <div className="relative max-w-7xl mx-auto px-5 sm:px-8 lg:px-12 text-center">
        <m1.div
          key={audience + "-eyebrow"}
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="inline-flex items-center gap-2 mb-6 px-3 py-1.5 rounded-full bg-white border border-line text-forest text-[12.5px] whitespace-nowrap"
        >
          <span className="inline-flex w-1.5 h-1.5 rounded-full bg-coral" />
          <span dangerouslySetInnerHTML={{ __html: h.eyebrow }} />
        </m1.div>

        <m1.div
          key={audience + "-h1"}
          initial={{ opacity: 0, y: 18 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, ease: [0.2, 0.7, 0.2, 1] }}
        >
          <h1 className="font-display text-[44px] sm:text-[64px] lg:text-[80px] leading-[0.98] text-forestDeep max-w-4xl mx-auto tracking-tight">
            {h.h1a}{" "}
            <span className="relative inline-block">
              {h.h1b}
              <svg viewBox="0 0 300 14" className="absolute left-0 right-0 -bottom-2 w-full" preserveAspectRatio="none" aria-hidden="true">
                <path d="M2 9 C 60 1, 140 13, 298 5" stroke="#B45309" strokeWidth="3" fill="none" strokeLinecap="round" />
              </svg>
            </span>
            .
          </h1>
        </m1.div>

        <m1.p
          key={audience + "-sub"}
          initial={{ opacity: 0, y: 14 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15, duration: 0.6 }}
          className="mt-6 text-[17px] sm:text-[19px] text-inkSoft max-w-2xl mx-auto text-pretty"
        >
          {h.sub}
        </m1.p>

        <m1.div
          initial={{ opacity: 0, y: 14 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.25, duration: 0.5 }}
          className="mt-8 flex flex-wrap items-center justify-center gap-3"
        >
          {h.primary && (
            <a href={h.primaryHref}>
              <Button variant="coral" size="lg">
                {t1(h.primary)} <IconArrow size={14} />
              </Button>
            </a>
          )}
          <a href={h.secondaryHref}>
            <Button variant="outline" size="lg">{t1(h.secondary)}</Button>
          </a>
        </m1.div>

        {audience === "sitters" && (
          <div className="mt-12 sm:mt-16 relative">
            <HeroMock />
          </div>
        )}
      </div>
    </section>
  );
};

Object.assign(window, { Header, Hero });
