// Header, Footer, Mobile nav, Theme + locale store
const { useState, useEffect, useRef } = React;

// Top header
const Header = ({ route, navigate, locale, setLocale, theme, toggleTheme }) => {
  const t = window.STRINGS[locale];
  const [open, setOpen] = useState(false); // mobile
  const [openMenu, setOpenMenu] = useState(null); // hovered dropdown
  const [scrolled, setScrolled] = useState(false);

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

  const items = [
    { id: 'pme', label: t.nav.pme, href: '/pme', children: [
      { href: '/pme/convenios', label: locale === 'pt' ? 'Antecipação de Convênios' : 'Health-plan Advances', desc: locale === 'pt' ? 'Receba hoje o repasse que o plano paga em 60 dias' : 'Get today what the plan pays in 60 days' },
      { href: '/pme/cartao', label: locale === 'pt' ? 'Antecipação de Cartão' : 'Card Advances', desc: locale === 'pt' ? 'Particular e parcelado da maquininha da clínica' : 'Out-of-pocket and installment card sales' },
      { href: '/pme/giro', label: locale === 'pt' ? 'Capital de Giro' : 'Working Capital', desc: locale === 'pt' ? 'Linha rotativa para equipar e crescer a clínica' : 'Revolving line to equip and grow the practice' },
    ]},
    { id: 'partners', label: t.nav.partners, href: '/partners' },
    { id: 'how', label: t.nav.how, href: '/how' },
    { id: 'about', label: t.nav.about, href: '/about' },
    { id: 'content', label: t.nav.content, href: '/blog' },
    { id: 'careers', label: t.nav.careers, href: '/careers' },
  ];

  return (
    <header className={cn(
      "fixed top-0 inset-x-0 z-50 transition-all duration-300 backdrop-blur-md border-b",
      scrolled ? "bg-bg/85 border-line" : "bg-bg/70 border-line/60"
    )}>
      <div className="mx-auto max-w-7xl px-6 md:px-10 h-16 flex items-center gap-4">
        <a href="#/" onClick={(e) => { e.preventDefault(); navigate('/'); }} className="flex items-center gap-2 shrink-0 py-2 -my-2">
          <FluiMark className="w-7 h-7" />
          <span className="font-display text-[17px] tracking-tight whitespace-nowrap">flui.cash</span>
        </a>

        <nav className="hidden lg:flex items-center gap-0.5 ml-2 text-sm shrink-0" onMouseLeave={() => setOpenMenu(null)}>
          {items.map(it => (
            <div key={it.id} className="relative shrink-0" onMouseEnter={() => setOpenMenu(it.children ? it.id : null)}>
              <a href={'#'+it.href} onClick={(e) => { e.preventDefault(); navigate(it.href); }}
                className={cn("px-2.5 h-9 inline-flex items-center whitespace-nowrap rounded-full transition-colors",
                  route.startsWith(it.href) && it.href !== '/' ? "text-fg bg-subtle" : "text-muted hover:text-fg")}>
                {it.label}
                {it.children && <Icon name="chevron-down" className="w-3.5 h-3.5 ml-1 opacity-60 shrink-0" />}
              </a>
              {it.children && openMenu === it.id && (
                <div className="absolute top-full left-0 pt-2 w-[420px]">
                  <div className="bg-card border border-line rounded-2xl shadow-xl p-2">
                    {it.children.map(c => (
                      <a key={c.href} href={'#'+c.href} onClick={(e) => { e.preventDefault(); navigate(c.href); setOpenMenu(null); }}
                        className="block p-3 rounded-xl hover:bg-subtle transition-colors">
                        <div className="text-sm font-medium text-fg">{c.label}</div>
                        <div className="text-xs text-muted mt-0.5">{c.desc}</div>
                      </a>
                    ))}
                  </div>
                </div>
              )}
            </div>
          ))}
        </nav>

        <div className="ml-auto flex items-center gap-2 shrink-0">
          <button onClick={() => setLocale(locale === 'pt' ? 'en' : 'pt')}
            className="hidden md:inline-flex items-center gap-1.5 h-9 px-3 rounded-full border border-line text-xs font-mono uppercase tracking-wider hover:bg-subtle transition-colors shrink-0">
            <Icon name="globe" className="w-3.5 h-3.5" /> {locale.toUpperCase()}
          </button>
          <button onClick={toggleTheme} aria-label="Toggle theme"
            className="hidden md:inline-flex items-center justify-center w-9 h-9 rounded-full border border-line hover:bg-subtle transition-colors shrink-0">
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} className="w-4 h-4" />
          </button>
          <Button variant="accent" size="sm" onClick={() => navigate('/pme#sim')} className="hidden md:inline-flex whitespace-nowrap shrink-0">
            {t.nav.cta}
          </Button>
          <button onClick={() => setOpen(true)} className="lg:hidden w-9 h-9 grid place-items-center rounded-full border border-line">
            <Icon name="menu" />
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      {open && (
        <div className="fixed inset-0 z-50 bg-bg lg:hidden">
          <div className="flex items-center justify-between p-6 border-b border-line">
            <div className="flex items-center gap-2"><FluiMark className="w-7 h-7" /><span className="font-display text-[17px]">flui.cash</span></div>
            <button onClick={() => setOpen(false)} className="w-9 h-9 grid place-items-center rounded-full border border-line"><Icon name="x" /></button>
          </div>
          <div className="p-6 space-y-1 overflow-y-auto h-[calc(100vh-80px)]">
            {items.map(it => (
              <div key={it.id}>
                <a href={'#'+it.href} onClick={(e) => { e.preventDefault(); navigate(it.href); setOpen(false); }}
                  className="block py-3 font-display text-2xl">{it.label}</a>
                {it.children && (
                  <div className="ml-1 mb-3 space-y-1">
                    {it.children.map(c => (
                      <a key={c.href} href={'#'+c.href} onClick={(e) => { e.preventDefault(); navigate(c.href); setOpen(false); }}
                        className="block py-3 text-muted">{c.label}</a>
                    ))}
                  </div>
                )}
              </div>
            ))}
            <div className="pt-6 flex items-center gap-3">
              <button onClick={() => setLocale(locale === 'pt' ? 'en' : 'pt')}
                className="inline-flex items-center gap-1.5 h-10 px-4 rounded-full border border-line text-xs font-mono uppercase tracking-wider">
                <Icon name="globe" className="w-3.5 h-3.5" /> {locale.toUpperCase()}
              </button>
              <button onClick={toggleTheme} className="inline-flex items-center justify-center w-10 h-10 rounded-full border border-line">
                <Icon name={theme === 'dark' ? 'sun' : 'moon'} className="w-4 h-4" />
              </button>
              <Button variant="accent" size="sm" onClick={() => { navigate('/pme#sim'); setOpen(false); }}>{t.nav.cta}</Button>
            </div>
          </div>
        </div>
      )}
    </header>
  );
};

// Logo mark — flui.cash (coração · saúde)
const FluiMark = ({ className = "w-6 h-6" }) => (
  <svg viewBox="0 0 32 32" className={className} fill="none" aria-hidden>
    <rect x="1" y="1" width="30" height="30" rx="9" fill="rgb(var(--fg))" />
    <path
      d="M16 25C16 25 7.5 19.6 7.5 14C7.5 11.5 9.4 9.8 11.6 9.8C13.4 9.8 15.1 10.9 16 12.4C16.9 10.9 18.6 9.8 20.4 9.8C22.6 9.8 24.5 11.5 24.5 14C24.5 19.6 16 25 16 25Z"
      fill="rgb(var(--primary))"
    />
    <path
      d="M9.6 15.6H13L14.6 12.6L17.4 18.4L19 15.6H22.4"
      stroke="rgb(var(--fg))"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      fill="none"
    />
  </svg>
);

// Footer
const Footer = ({ locale, setLocale, theme, toggleTheme, navigate }) => {
  const L = locale === 'pt';
  const cols = [
    {
      title: L ? 'Para Sua Clínica' : 'For Your Practice',
      links: [
        [L ? 'Antecipação de Convênios' : 'Health-plan Advances', '/pme/convenios'],
        [L ? 'Antecipação de Cartão' : 'Card Advances', '/pme/cartao'],
        [L ? 'Capital de Giro' : 'Working Capital', '/pme/giro'],
        [L ? 'Simular antecipação' : 'Run a simulation', '/pme#sim'],
      ],
    },
    {
      title: L ? 'Para Parceiros' : 'For Partners',
      links: [
        [L ? 'Para softwares de saúde' : 'For healthcare software', '/partners'],
        [L ? 'Como integrar' : 'How to integrate', '/partners#integrate'],
        [L ? 'Modelos de parceria' : 'Partnership models', '/partners#models'],
        [L ? 'Falar com o time' : 'Talk to us', '/partners#contact'],
      ],
    },
    {
      title: L ? 'Companhia' : 'Company',
      links: [
        [L ? 'Sobre' : 'About', '/about'],
        [L ? 'Como funciona' : 'How it works', '/how'],
        [L ? 'Carreiras' : 'Careers', '/careers'],
        [L ? 'Conteúdo' : 'Content', '/blog'],
        [L ? 'Contato' : 'Contact', '/contact'],
      ],
    },
    {
      title: L ? 'Legal & Privacidade' : 'Legal & Privacy',
      links: [
        [L ? 'Privacidade' : 'Privacy', '/legal/privacy'],
        [L ? 'Termos de uso' : 'Terms', '/legal/terms'],
        [L ? 'Cookies' : 'Cookies', '/legal/cookies'],
        ['LGPD / DPO', '/legal/dpo'],
        ['Ouvidoria', '/legal/ouvidoria'],
      ],
    },
  ];

  return (
    <footer className="border-t border-line bg-bg pt-20 pb-10">
      <div className="mx-auto max-w-7xl px-6 md:px-10">
        <div className="grid lg:grid-cols-[1.4fr_2.6fr] gap-12 mb-16">
          <div>
            <div className="flex items-center gap-2 mb-5">
              <FluiMark className="w-8 h-8" />
              <span className="font-display text-xl tracking-tight">flui.cash</span>
            </div>
            <p className="text-muted max-w-sm">
              {L
                ? 'Fintech AI Native para a saúde. Antecipação de repasses de convênios e de cartão para profissionais e clínicas.'
                : 'AI Native fintech for healthcare. Health-plan and card receivable advances for practitioners and clinics.'}
            </p>
            <div className="flex items-center gap-2 mt-6">
              <button onClick={() => setLocale(L ? 'en' : 'pt')}
                className="inline-flex items-center gap-1.5 h-9 px-3 rounded-full border border-line text-xs font-mono uppercase tracking-wider hover:bg-subtle">
                <Icon name="globe" className="w-3.5 h-3.5" /> {locale.toUpperCase()}
              </button>
              <button onClick={toggleTheme} className="inline-flex items-center justify-center w-9 h-9 rounded-full border border-line hover:bg-subtle">
                <Icon name={theme === 'dark' ? 'sun' : 'moon'} className="w-4 h-4" />
              </button>
            </div>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
            {cols.map(col => (
              <div key={col.title}>
                <h4 className="font-mono text-xs uppercase tracking-[0.18em] text-muted mb-4">{col.title}</h4>
                <ul className="space-y-0.5 md:space-y-2.5">
                  {col.links.map(([label, href]) => (
                    <li key={href}>
                      <a href={'#'+href} onClick={(e) => { e.preventDefault(); navigate(href); }}
                        className="block py-2.5 md:py-0 text-sm text-fg/80 hover:text-fg transition-colors">{label}</a>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* Partners + Privacy row */}
        <div className="border-t border-line pt-8 grid lg:grid-cols-[2fr_1fr] gap-8">
          <div className="flex flex-wrap items-center gap-3">
            <ComplianceSeal title={L ? 'BaaS Parceiro' : 'BaaS Partner'} sub={L ? 'Regulado pelo BACEN' : 'BACEN-regulated'} />
            <ComplianceSeal title={L ? 'Gestora FIDC' : 'FIDC Manager'} sub={L ? 'Autorizada pela CVM' : 'CVM-authorized'} />
            <ComplianceSeal title="LGPD" sub={L ? 'Conforme Lei 13.709' : 'Law 13.709 compliant'} />
            <ComplianceSeal title="ISO 27001" sub={L ? 'Em implementação' : 'In progress'} />
            <ComplianceSeal title={L ? 'Sigilo em Saúde' : 'Health Data'} sub={L ? 'Dados clínicos não trafegam' : 'No clinical data processed'} />
          </div>
          <div className="text-xs text-muted lg:text-right space-y-1 font-mono">
            <div>FLUI.CASH S.A.</div>
            <div>CNPJ 00.000.000/0001-00</div>
            <div>Av. Brigadeiro Faria Lima, 0000 — São Paulo / SP</div>
            <div>Contato dpo@flui.cash</div>
          </div>
        </div>

        <div className="border-t border-line mt-8 pt-6 flex flex-wrap items-center justify-between gap-4 text-xs text-muted">
          <div>© 2026 flui.cash. {L ? 'Todos os direitos reservados.' : 'All rights reserved.'}</div>
          <div className="flex items-center gap-4 font-mono uppercase tracking-wider">
            <span>v 1.0 — health</span>
            <span>São Paulo · BR</span>
          </div>
        </div>
      </div>
    </footer>
  );
};

const ComplianceSeal = ({ title, sub }) => (
  <div className="inline-flex items-center gap-2.5 px-3 py-2 rounded-xl border border-line bg-card">
    <div className="w-7 h-7 rounded-md bg-subtle grid place-items-center">
      <Icon name="shield" className="w-4 h-4 text-fg" />
    </div>
    <div className="leading-tight">
      <div className="font-mono text-[11px] uppercase tracking-[0.16em] font-semibold">{title}</div>
      <div className="text-[10.5px] text-muted">{sub}</div>
    </div>
  </div>
);

Object.assign(window, { Header, Footer, FluiMark, ComplianceSeal });
