/* global React */
/* =============================================================================
   Flavio Seguros, Shell compartilhado (Header, Footer, helpers, mount).
   Exposto como window.FCS. Depende de window.FCS_DATA e do bundle do DS.
   ============================================================================= */
const S = window.FlavioCorretoraDesignSystem_9d5869;
const D = window.FCS_DATA;
const { Logo, Button, Icon, WhatsAppButton, Breadcrumb, Tag, Card } = S;

/* ---- layout helpers reutilizados pelas páginas ------------------------- */
const wrap = { maxWidth: 'var(--content-max)', margin: '0 auto', padding: '0 var(--gutter)' };
const sectionPad = { paddingTop: 'var(--section-pad-y)', paddingBottom: 'var(--section-pad-y)' };
const glassStyle = {
  background: 'rgba(255,255,255,0.55)',
  backdropFilter: 'saturate(1.4) blur(26px)',
  WebkitBackdropFilter: 'saturate(1.4) blur(26px)',
  border: '1px solid rgba(255,255,255,0.7)',
  borderRadius: 'var(--radius-xl)',
  boxShadow: 'var(--shadow-md)',
};

/* ---- Blobs orgânicos (atmosfera) --------------------------------------- */
function Blobs({ tone = 'light' }) {
  const base = { position: 'absolute', borderRadius: '50%', filter: 'blur(70px)', pointerEvents: 'none' };
  const set = tone === 'dark'
    ? [['rgba(198,154,91,0.22)', 520, -180, -140, 'fcs-blob-a'], ['rgba(30,95,158,0.5)', 460, 'auto', -160, 'fcs-blob-b'], ['rgba(143,182,218,0.22)', 380, '40%', '55%', 'fcs-blob-c']]
    : [['rgba(30,95,158,0.14)', 520, -200, -160, 'fcs-blob-a'], ['rgba(198,154,91,0.13)', 420, 'auto', -140, 'fcs-blob-b'], ['rgba(143,182,218,0.16)', 360, '55%', '60%', 'fcs-blob-c']];
  return (
    <div aria-hidden="true" style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      {set.map(([bg, size, top, left, cls], i) => {
        const st = { ...base, background: bg, width: size, height: size };
        if (top === 'auto') { st.bottom = -140; } else { st.top = top; }
        if (left === 'auto') { st.right = -160; } else { st.left = left; }
        return <div key={i} className={cls} style={st} />;
      })}
    </div>
  );
}

/* ---- Eyebrow com régua dourada ----------------------------------------- */
function Eyebrow({ children, tone = 'light' }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-eyebrow)', fontWeight: 600, letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: tone === 'dark' ? 'var(--gold-300)' : 'var(--gold-600)' }}>
      {children}
    </span>
  );
}

/* ---- Cabeçalho de seção ------------------------------------------------ */
function SectionHead({ eyebrow, title, intro, align = 'left', tone = 'light', max = '42ch', accent }) {
  const dark = tone === 'dark';
  const parts = accent && title.includes(accent)
    ? title.split(accent) : null;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, alignItems: align === 'center' ? 'center' : 'flex-start', textAlign: align, marginBottom: 48, maxWidth: align === 'center' ? '52ch' : 'none', marginLeft: align === 'center' ? 'auto' : 0, marginRight: align === 'center' ? 'auto' : 0 }}>
      {eyebrow && <Eyebrow tone={tone}>{eyebrow}</Eyebrow>}
      <h2 style={{ margin: 0, fontSize: 'var(--fs-h1)', maxWidth: '20ch', fontWeight: 400, color: dark ? 'var(--neutral-0)' : 'var(--text-strong)' }}>
        {parts ? <>{parts[0]}<em style={{ fontStyle: 'normal', color: 'var(--gold-500)' }}>{accent}</em>{parts[1]}</> : title}
      </h2>
      {intro && <p style={{ margin: 0, fontSize: 'var(--fs-lead)', color: dark ? 'var(--blue-200)' : 'var(--text-muted)', maxWidth: max, lineHeight: 'var(--lh-relaxed)' }}>{intro}</p>}
    </div>
  );
}

/* ---- Placeholder de fotografia (duotone azul) -------------------------- */
function Photo({ src, alt, icon = 'image', caption, ratio = '4 / 3', radius = 'var(--radius-lg)', style, className }) {
  if (src) {
    return (
      <div className={className} style={{ position: 'relative', aspectRatio: ratio, width: '100%', borderRadius: radius, overflow: 'hidden', background: 'var(--blue-950)', ...style }}>
        <img src={src} alt={alt || caption || ''} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      </div>
    );
  }
  return (
    <div className={className} style={{ position: 'relative', aspectRatio: ratio, width: '100%', borderRadius: radius, overflow: 'hidden', background: 'linear-gradient(135deg, var(--blue-800), var(--blue-950))', display: 'flex', alignItems: 'center', justifyContent: 'center', ...style }}>
      <div style={{ position: 'absolute', inset: 0, opacity: 0.14, backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,0.5) 0 1px, transparent 1px 22px)' }} />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, color: 'var(--blue-200)' }}>
        <Icon name={icon} size={34} strokeWidth={1.4} color="var(--blue-200)" />
        {caption && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--fs-xs)', letterSpacing: '0.06em', textTransform: 'uppercase', opacity: 0.85 }}>{caption}</span>}
      </div>
    </div>
  );
}

function PartnerChip({ name }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 64, border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', background: 'var(--surface-card)', color: 'var(--neutral-500)', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, letterSpacing: '0.01em', textAlign: 'center', padding: '0 8px' }}>{name}</div>
  );
}

/* ---- Reveal ao rolar (transform + opacity) ----------------------------- */
function Reveal({ children, delay = 0, style, as = 'div' }) {
  const El = as;
  return <El className="reveal" style={{ transitionDelay: delay + 'ms', ...style }}>{children}</El>;
}

/* ---- Logo do site (imagem oficial: navy em fundo claro, branco em escuro) */
function SiteLogo({ tone = 'primary', height = 34, style }) {
  const inv = tone === 'inverse';
  const imgBase = { height, width: 'auto', display: 'block', transition: 'opacity 0.45s var(--ease-standard)' };
  return (
    <span style={{ position: 'relative', display: 'inline-block', height, lineHeight: 0, ...style }}>
      <img src="assets/logo-flavio.png" alt="Flavio Seguros" style={{ ...imgBase, opacity: inv ? 0 : 1 }} />
      <img src="assets/logo-flavio-inverse.png" alt="" aria-hidden="true" style={{ ...imgBase, position: 'absolute', top: 0, left: 0, opacity: inv ? 1 : 0 }} />
    </span>
  );
}

/* ---- HEADER (pílula flutuante em vidro + dropdown Seguros) -------------- */
function Header() {
  const [scrolled, setScrolled] = React.useState(false);
  const [openMenu, setOpenMenu] = React.useState(false);
  const [openDrop, setOpenDrop] = React.useState(false);
  const [mobSeg, setMobSeg] = React.useState(false);
  const [onDark, setOnDark] = React.useState(true);
  const glassRef = React.useRef(null);
  const headerRef = React.useRef(null);
  React.useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const lumOf = (c) => { const m = c.match(/\d+(\.\d+)?/g); if (!m) return 1; return (0.2126 * (+m[0]) + 0.7152 * (+m[1]) + 0.0722 * (+m[2])) / 255; };
    const detect = () => {
      const el = glassRef.current, hd = headerRef.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const x = Math.round(r.left + 46), y = Math.round(r.top + r.height / 2);
      const stack = document.elementsFromPoint(x, y);
      let node = null;
      for (let k = 0; k < stack.length; k++) { const n = stack[k]; if (!hd || (!hd.contains(n) && n !== hd)) { node = n; break; } }
      let bg = null;
      while (node) { const c = getComputedStyle(node).backgroundColor; if (c && c !== 'transparent' && !/rgba\([^)]*,\s*0\)/.test(c)) { bg = c; break; } node = node.parentElement; }
      setOnDark(bg ? lumOf(bg) < 0.55 : true);
    };
    let ticking = false;
    const apply = () => {
      const y = window.scrollY;
      setScrolled(y > 8);
      if (!reduce && glassRef.current) {
        const p = Math.max(0, Math.min(1, y / 700));
        glassRef.current.style.setProperty('--spec-x', (24 + p * 34) + '%');
      }
      detect();
      ticking = false;
    };
    const onScroll = () => { if (!ticking) { ticking = true; requestAnimationFrame(apply); } };
    apply();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', apply, { passive: true });
    const t = setTimeout(detect, 400);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', apply); clearTimeout(t); };
  }, []);
  const dropTimer = React.useRef(null);
  const segRef = React.useRef(null);
  const [dropPos, setDropPos] = React.useState({ left: 0, top: 0 });
  const enter = () => {
    clearTimeout(dropTimer.current);
    if (segRef.current) { const r = segRef.current.getBoundingClientRect(); const left = Math.min(r.left, window.innerWidth - 560 - 16); setDropPos({ left: Math.max(16, left), top: r.bottom + 22 }); }
    setOpenDrop(true);
  };
  const leave = () => { dropTimer.current = setTimeout(() => setOpenDrop(false), 140); };

  const pf = D.pf(); const pj = D.pj();
  const dark = onDark;
  const linkColor = dark ? 'rgba(255,255,255,0.88)' : 'var(--text-body)';
  const linkHoverColor = dark ? 'var(--neutral-0)' : 'var(--blue-800)';
  const linkHoverBg = dark ? 'rgba(255,255,255,0.12)' : 'var(--surface-subtle)';
  const linkStyle = { fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 500, color: linkColor, textDecoration: 'none', padding: '8px 14px', borderRadius: 'var(--radius-pill)', display: 'inline-flex', alignItems: 'center', gap: 6, transition: 'background var(--dur-fast) var(--ease-standard), color var(--dur-fast) var(--ease-standard)' };

  return (
    <header ref={headerRef} style={{ position: 'sticky', top: 0, zIndex: 60, padding: '14px var(--gutter) 0' }}>
      <svg width="0" height="0" aria-hidden="true" style={{ position: 'absolute' }}>
        <filter id="fcs-glass-distort" x="-20%" y="-20%" width="140%" height="140%">
          <feTurbulence type="fractalNoise" baseFrequency="0.011 0.013" numOctaves="2" seed="12" result="t" />
          <feGaussianBlur in="t" stdDeviation="1.4" result="tb" />
          <feDisplacementMap in="SourceGraphic" in2="tb" scale="11" xChannelSelector="R" yChannelSelector="G" />
        </filter>
      </svg>
      <div ref={glassRef} className={'fcs-glass is-light' + (scrolled ? '' : ' is-top')} style={{ maxWidth: 'var(--content-max)', margin: '0 auto', borderRadius: 'var(--radius-pill)', background: openMenu ? 'rgba(255,255,255,0.96)' : undefined }}>
        <span className="glassL fcs-glass-refract" aria-hidden="true" />
        <span className="glassL fcs-glass-tint" aria-hidden="true" />
        <span className="glassL fcs-glass-edge" aria-hidden="true" />
        <span className="glassL fcs-glass-spec" aria-hidden="true" />
        <span className="glassL fcs-glass-noise" aria-hidden="true" />
        <div style={{ position: 'relative', zIndex: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, padding: '10px 12px 10px 20px' }}>
        <a href="index.html" style={{ textDecoration: 'none', flex: '0 0 auto', display: 'inline-flex' }}><SiteLogo tone={(dark && !openMenu) ? 'inverse' : 'primary'} height={34} /></a>

        <nav className="fcs-desknav" style={{ display: 'flex', gap: 2, alignItems: 'center' }}>
          <div className="fcs-segmenu" ref={segRef} style={{ position: 'relative' }} onMouseEnter={enter} onMouseLeave={leave}>
            <a href="seguros.html" style={{ ...linkStyle, background: openDrop ? linkHoverBg : 'transparent', color: openDrop ? linkHoverColor : linkColor }}
              aria-expanded={openDrop} onFocus={enter} onBlur={leave}>
              Seguros <Icon name="chevron-down" size={15} strokeWidth={2} style={{ transform: openDrop ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-fast)' }} />
            </a>
            {openDrop && (
              <div onMouseEnter={enter} onMouseLeave={leave} style={{ position: 'fixed', top: dropPos.top, left: dropPos.left, width: 560, zIndex: 70, ...glassStyle, background: 'rgba(255,255,255,0.75)', padding: 24 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 22 }}>
                  {[['Para você', pf], ['Para sua empresa', pj]].map(([h, list]) => (
                    <div key={h} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                      <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-xs)', fontWeight: 700, letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: 'var(--gold-600)', marginBottom: 8 }}>{h}</span>
                      {list.map((p) => (
                        <a key={p.slug} href={'produto.html?p=' + p.slug} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 10px', borderRadius: 'var(--radius-md)', textDecoration: 'none', color: 'var(--text-body)' }}
                          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--surface-subtle)'; }}
                          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
                          <span style={{ width: 32, height: 32, flex: '0 0 auto', borderRadius: 'var(--radius-sm)', background: 'var(--blue-50)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={p.icon} size={17} color="var(--blue-700)" strokeWidth={1.75} /></span>
                          <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 500 }}>{p.title}</span>
                        </a>
                      ))}
                    </div>
                  ))}
                </div>
                <a href="seguros.html" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--border-subtle)', width: '100%', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 600, color: 'var(--blue-700)', textDecoration: 'none' }}>
                  Ver todos os seguros <Icon name="arrow-right" size={16} strokeWidth={2} />
                </a>
              </div>
            )}
          </div>
          {D.NAV.filter((n) => !n.dropdown).map((n) => (
            <a key={n.label} href={n.href} style={linkStyle}
              onMouseEnter={(e) => { e.currentTarget.style.background = linkHoverBg; e.currentTarget.style.color = linkHoverColor; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = linkColor; }}>{n.label}</a>
          ))}
        </nav>

        <div className="fcs-deskcta" style={{ display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto' }}>
          <a href={D.CONTACT.phoneHref} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 600, color: dark ? 'var(--neutral-0)' : 'var(--blue-800)', textDecoration: 'none', transition: 'color var(--dur-normal)' }}>
            <Icon name="phone" size={16} strokeWidth={2} /> {D.CONTACT.phone}
          </a>
          <Button size="sm" variant={dark ? 'inverse' : 'primary'} href="orcamento.html" iconTrailing="arrow-right">Solicite uma cotação</Button>
        </div>

        <button className="fcs-burger" onClick={() => setOpenMenu(!openMenu)} aria-label="Menu" style={{ display: 'none', background: 'none', border: 'none', cursor: 'pointer', color: (dark && !openMenu) ? 'var(--neutral-0)' : 'var(--blue-800)', padding: 6, transition: 'color var(--dur-normal) var(--ease-standard)' }}>
          <Icon name={openMenu ? 'x' : 'menu'} size={26} strokeWidth={2} />
        </button>
        </div>
      </div>

      {openMenu && (
        <div style={{ position: 'absolute', left: 'var(--gutter)', right: 'var(--gutter)', top: 'calc(100% + 8px)', ...glassStyle, background: 'rgba(255,255,255,0.97)', padding: '10px 16px 18px', maxHeight: 'calc(100svh - 120px)', overflowY: 'auto' }} className="fcs-mobmenu">
          <button onClick={() => setMobSeg(!mobSeg)} style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '13px 4px', background: 'none', border: 'none', borderBottom: '1px solid var(--border-subtle)', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-body)', fontWeight: 500, color: 'var(--text-body)', cursor: 'pointer' }}>
            Seguros <Icon name={mobSeg ? 'chevron-up' : 'chevron-down'} size={18} />
          </button>
          {mobSeg && (
            <div style={{ padding: '6px 4px 10px', borderBottom: '1px solid var(--border-subtle)' }}>
              {D.PRODUCTS.map((p) => (
                <a key={p.slug} href={'produto.html?p=' + p.slug} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 4px', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', color: 'var(--text-body)', textDecoration: 'none' }}>
                  <Icon name={p.icon} size={16} color="var(--blue-700)" /> {p.title}
                </a>
              ))}
              <a href="seguros.html" style={{ display: 'block', padding: '9px 4px', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 600, color: 'var(--blue-700)', textDecoration: 'none' }}>Ver todos os seguros →</a>
            </div>
          )}
          {D.NAV.filter((n) => !n.dropdown).map((n) => (
            <a key={n.label} href={n.href} style={{ display: 'block', padding: '13px 4px', fontFamily: 'var(--font-sans)', fontWeight: 500, color: 'var(--text-body)', textDecoration: 'none', borderBottom: '1px solid var(--border-subtle)' }}>{n.label}</a>
          ))}
          <div style={{ marginTop: 14 }}><Button fullWidth href="orcamento.html" iconTrailing="arrow-right">Solicite uma cotação</Button></div>
        </div>
      )}
    </header>
  );
}

/* ---- Breadcrumb claro dentro do hero escuro --------------------------- */
function HeroCrumbs({ items, center, style }) {
  return (
    <nav className="fcs-hin" aria-label="Trilha" style={{ animationDelay: '0.02s', display: 'flex', gap: 9, alignItems: 'center', flexWrap: 'wrap', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-xs)', letterSpacing: '0.02em', justifyContent: center ? 'center' : 'flex-start', ...style }}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span style={{ color: 'var(--blue-300)', opacity: 0.55 }}>/</span>}
          {it.href ? <a href={it.href} style={{ color: 'var(--blue-200)', textDecoration: 'none' }}>{it.label}</a> : <span style={{ color: 'var(--blue-300)' }}>{it.label}</span>}
        </React.Fragment>
      ))}
    </nav>
  );
}

/* ---- Hero compacto para páginas internas (headline em máscara) --------- */
function PageHero({ eyebrow, title, accent, intro, cta, align = 'left', crumbs, lead }) {
  const parts = accent && title.includes(accent) ? title.split(accent) : null;
  const center = align === 'center';
  const heading = parts ? <>{parts[0]}<em style={{ fontStyle: 'normal', color: 'var(--gold-300)', fontWeight: 400 }}>{accent}</em>{parts[1]}</> : title;
  return (
    <section style={{ background: 'var(--surface-inverse)', position: 'relative', overflow: 'hidden', marginTop: 'calc(-1 * var(--header-h))' }}>
      <Blobs tone="dark" />
      <div style={{ ...wrap, position: 'relative', paddingTop: 'calc(var(--header-h) + clamp(1rem, 0.5rem + 2vw, 2.5rem))', paddingBottom: 'clamp(3.25rem, 2rem + 4.5vw, 5.5rem)', display: 'flex', flexDirection: 'column', gap: 18, alignItems: center ? 'center' : 'flex-start', textAlign: center ? 'center' : 'left', maxWidth: center ? '62ch' : 'var(--content-max)', marginLeft: 'auto', marginRight: 'auto' }}>
        {crumbs && <HeroCrumbs items={crumbs} center={center} style={{ marginBottom: 6 }} />}
        {eyebrow && <div className="fcs-hin" style={{ animationDelay: '0.05s' }}><Eyebrow tone="dark">{eyebrow}</Eyebrow></div>}
        <h1 data-mask style={{ margin: 0, fontSize: 'var(--fs-display-2)', fontWeight: 300, color: 'var(--neutral-0)', lineHeight: 1.06, letterSpacing: 'var(--ls-tight)', maxWidth: '20ch' }}>
          <span className="ml"><span>{heading}</span></span>
        </h1>
        {lead && <p className="fcs-hin" style={{ animationDelay: '0.4s', margin: 0, fontFamily: 'var(--font-serif)', fontWeight: 300, fontSize: 'var(--fs-h3)', color: 'var(--gold-300)', letterSpacing: '-0.01em', maxWidth: '26ch' }}>{lead}</p>}
        {intro && <p className="fcs-hin" style={{ animationDelay: '0.52s', margin: 0, fontSize: 'var(--fs-lead)', color: 'var(--blue-200)', maxWidth: '54ch', lineHeight: 'var(--lh-relaxed)' }}>{intro}</p>}
        {cta && <div className="fcs-hin" style={{ animationDelay: '0.58s' }}>{cta}</div>}
      </div>
    </section>
  );
}

/* ---- Linha editorial de seguro (reutilizável) -------------------------- */
function SegRow({ p }) {
  return (
    <a href={'produto.html?p=' + p.slug} className="fcs-segrow" style={{ display: 'grid', gridTemplateColumns: '46px 1fr auto', alignItems: 'center', gap: 20, padding: '20px 12px', borderTop: '1px solid var(--border-subtle)', textDecoration: 'none' }}>
      <span className="fcs-segrow-ic" style={{ width: 46, height: 46, borderRadius: 'var(--radius-md)', border: '1px solid var(--border-subtle)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--blue-700)' }}><Icon name={p.icon} size={20} strokeWidth={1.6} color="currentColor" /></span>
      <span>
        <span className="fcs-segrow-title" style={{ display: 'block', fontFamily: 'var(--font-serif)', fontSize: 'var(--fs-h4)', fontWeight: 500, color: 'var(--text-strong)', transition: 'color var(--dur-normal)' }}>{p.title}</span>
        <span style={{ display: 'block', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', color: 'var(--text-muted)', marginTop: 3 }}>{p.one}</span>
      </span>
      <span className="fcs-segrow-arw" style={{ display: 'inline-flex' }}><Icon name="arrow-right" size={20} color="var(--blue-600)" /></span>
    </a>
  );
}

function FeaturedSeguro({ p, badge }) {
  return (
    <a href={'produto.html?p=' + p.slug} className="fcs-feat rise" style={{ display: 'flex', flexDirection: 'column', textDecoration: 'none' }}>
      <div style={{ position: 'relative', borderRadius: 'var(--radius-lg)', overflow: 'hidden' }}>
        <Photo className="fcs-feat-img" src={p.photo} icon={p.icon} caption={p.title} ratio="16 / 11" />
        {badge && <span style={{ position: 'absolute', top: 16, left: 16, display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 13px', borderRadius: 'var(--radius-pill)', background: 'rgba(198,154,91,0.92)', color: 'var(--blue-950)', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-xs)', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{badge}</span>}
      </div>
      <div style={{ padding: '24px 4px 4px' }}>
        <h3 style={{ margin: '0 0 8px', fontSize: 'var(--fs-h3)', fontWeight: 400, color: 'var(--text-strong)' }}>{p.title}</h3>
        <p style={{ margin: '0 0 16px', fontSize: 'var(--fs-body)', color: 'var(--text-body)', lineHeight: 'var(--lh-relaxed)', maxWidth: '46ch' }}>{p.tagline}</p>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', fontWeight: 600, color: 'var(--blue-700)' }}>Ver cobertura <span className="fcs-feat-arw" style={{ display: 'inline-flex' }}><Icon name="arrow-right" size={16} strokeWidth={2} /></span></span>
      </div>
    </a>
  );
}

function Marquee({ items }) {
  const row = items.concat(items);
  return (
    <div className="fcs-marquee">
      <div className="fcs-marquee-track">{row.map((n, i) => <span key={i} className="fcs-mchip">{n}</span>)}</div>
    </div>
  );
}

/* ---- Faixa de breadcrumb ----------------------------------------------- */
function Crumbs({ items }) {
  return (
    <div style={{ borderBottom: '1px solid var(--border-subtle)', background: 'var(--surface-card)' }}>
      <div style={{ ...wrap, padding: '14px var(--gutter)' }}><Breadcrumb items={items} /></div>
    </div>
  );
}

/* ---- Bloco final de CTA (reutilizável) --------------------------------- */
function FinalCTA() {
  return (
    <section style={{ ...sectionPad, background: 'var(--surface-inverse)', position: 'relative', overflow: 'hidden' }}>
      <Blobs tone="dark" />
      <div aria-hidden="true" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 220, background: 'linear-gradient(to bottom, transparent, var(--surface-inverse))', pointerEvents: 'none', zIndex: 0 }} />
      <div aria-hidden="true" style={{ position: 'absolute', left: '50%', bottom: -320, transform: 'translateX(-50%)', width: 900, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,154,91,0.26), rgba(198,154,91,0) 66%)', filter: 'blur(50px)', pointerEvents: 'none', zIndex: 0 }} />
      <div style={{ ...wrap, position: 'relative', zIndex: 1, textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22 }}>
        <Eyebrow tone="dark">Vamos começar</Eyebrow>
        <h2 style={{ margin: 0, fontSize: 'var(--fs-display-2)', fontWeight: 300, color: 'var(--neutral-0)', maxWidth: '18ch' }}>Pronto para proteger o que <em style={{ fontStyle: 'normal', color: 'var(--gold-300)' }}>importa</em>?</h2>
        <p style={{ margin: 0, fontSize: 'var(--fs-lead)', color: 'var(--blue-200)', maxWidth: '48ch', lineHeight: 'var(--lh-relaxed)' }}>Conte o que você precisa proteger. Um consultor retorna em até 1 dia útil com as melhores opções, sem compromisso.</p>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
          <Button size="lg" href="orcamento.html" iconTrailing="arrow-right">Solicite uma cotação</Button>
          <Button size="lg" variant="inverse" href="#" onClick={(e) => { e.preventDefault(); openWhats(e); }}><WhatsIcon size={20} color="#1EA952" />Falar no WhatsApp</Button>
        </div>
      </div>
    </section>
  );
}

/* ---- FOOTER ------------------------------------------------------------ */
function Footer() {
  const cols = [
    { h: 'Para você', links: D.pf().map((p) => [p.title, 'produto.html?p=' + p.slug]) },
    { h: 'Para sua empresa', links: D.pj().map((p) => [p.title, 'produto.html?p=' + p.slug]) },
    { h: 'Institucional', links: [['A Corretora', 'a-corretora.html'], ['Blog', 'blog.html'], ['Suporte', 'suporte.html'], ['Solicite uma cotação', 'orcamento.html']] },
    { h: 'Links úteis', links: D.LINKS_UTEIS.map((u) => [u.label, u.url]) },
  ];
  return (
    <footer style={{ background: 'var(--surface-inverse)', color: 'var(--blue-200)', position: 'relative', overflow: 'hidden' }}>
      <Blobs tone="dark" />
      <div aria-hidden="true" style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 220, background: 'linear-gradient(to top, transparent, var(--surface-inverse))', pointerEvents: 'none', zIndex: 0 }} />
      <div aria-hidden="true" style={{ position: 'absolute', left: '50%', top: -320, transform: 'translateX(-50%)', width: 900, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,154,91,0.24), rgba(198,154,91,0) 66%)', filter: 'blur(50px)', pointerEvents: 'none', zIndex: 0 }} />
      <div style={{ ...wrap, position: 'relative', zIndex: 1, padding: '64px var(--gutter) 40px', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr', gap: 40 }} className="fcs-footer-grid">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 320 }}>
          <SiteLogo tone="inverse" height={34} style={{ objectFit: 'contain', alignSelf: 'flex-start' }} />
          <p style={{ margin: 0, fontSize: 'var(--fs-sm)', lineHeight: 'var(--lh-relaxed)', color: 'var(--blue-200)' }}>Consultoria de seguros em Belo Horizonte desde 1987. Tradição que protege. Precisão técnica, atenção humana.</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)' }}>
            <a href={D.CONTACT.phoneHref} className="fcs-flink" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, textDecoration: 'none' }}><Icon name="phone" size={15} color="var(--gold-300)" /> {D.CONTACT.phone}</a>
            <a href={'mailto:' + D.CONTACT.email} className="fcs-flink" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, textDecoration: 'none' }}><Icon name="mail" size={15} color="var(--gold-300)" /> {D.CONTACT.email}</a>
            <span style={{ display: 'inline-flex', alignItems: 'flex-start', gap: 8, lineHeight: 'var(--lh-snug)' }}><Icon name="map-pin" size={15} color="var(--gold-300)" style={{ flex: '0 0 auto', marginTop: 3 }} /><span>Rua Gonçalves Dias, 142 · Sl 601 · Funcionários · Belo Horizonte/MG</span></span>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
            {[['Instagram', 'Ig'], ['Facebook', 'Fb'], ['LinkedIn', 'In']].map(([label, ab]) => (
              <a key={label} href="#" aria-label={label} style={{ width: 38, height: 38, borderRadius: '50%', border: '1px solid rgba(255,255,255,0.14)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600, color: 'var(--blue-200)', textDecoration: 'none' }}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--gold-500)'; e.currentTarget.style.color = 'var(--gold-300)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.14)'; e.currentTarget.style.color = 'var(--blue-200)'; }}>{ab}</a>
            ))}
          </div>
        </div>
        {cols.map((c) => (
          <div key={c.h} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <span style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-eyebrow)', fontWeight: 700, letterSpacing: 'var(--ls-eyebrow)', textTransform: 'uppercase', color: 'var(--gold-300)' }}>{c.h}</span>
            {c.links.map(([l, href]) => { const ext = /^https?:/.test(href); return <a key={l} href={href} target={ext ? '_blank' : undefined} rel={ext ? 'noopener noreferrer' : undefined} className="fcs-flink" style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-sm)', textDecoration: 'none' }}>{l}</a>; })}
          </div>
        ))}
      </div>
      <div style={{ borderTop: '1px solid rgba(255,255,255,0.08)', position: 'relative', zIndex: 1 }}>
        <div style={{ ...wrap, padding: '20px var(--gutter)', display: 'flex', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-xs)', color: 'var(--neutral-400)' }}>
          <span>© 2026 Flavio Corretora de Seguros LTDA · Belo Horizonte/MG · Desde 1987 · CNPJ: 22.589.618/0001-71</span>
          <span style={{ display: 'flex', gap: 18 }}><a href="politica-privacidade.html" className="fcs-flink fcs-flink--muted" style={{ textDecoration: 'none' }}>Política de Privacidade</a></span>
        </div>
      </div>
    </footer>
  );
}

/* ---- Popup de escolha de número do WhatsApp ---------------------------- */
function WhatsPicker() {
  const [open, setOpen] = React.useState(false);
  const [anchor, setAnchor] = React.useState(null);
  const [pos, setPos] = React.useState({ top: 0, left: 0, origin: 'bottom right' });
  const ref = React.useRef(null);
  React.useEffect(() => {
    const on = (e) => { setAnchor((e.detail && e.detail.rect) || null); setOpen(true); };
    window.addEventListener('fcs:openwhats', on);
    return () => window.removeEventListener('fcs:openwhats', on);
  }, []);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    const onScroll = () => setOpen(false);
    if (open) { window.addEventListener('keydown', onKey); window.addEventListener('scroll', onScroll, true); window.addEventListener('resize', onScroll); }
    return () => { window.removeEventListener('keydown', onKey); window.removeEventListener('scroll', onScroll, true); window.removeEventListener('resize', onScroll); };
  }, [open]);
  React.useLayoutEffect(() => {
    if (!open || !ref.current) return;
    const el = ref.current, w = el.offsetWidth, h = el.offsetHeight, m = 14, vw = window.innerWidth, vh = window.innerHeight;
    const a = anchor || { top: vh / 2, bottom: vh / 2, left: vw / 2, right: vw / 2, width: 0 };
    const above = a.top - m - h >= 8;
    let top = above ? a.top - m - h : Math.min(a.bottom + m, vh - h - 8);
    let left = a.left + a.width / 2 - w / 2;              // center on anchor
    left = Math.max(8, Math.min(left, vw - w - 8));
    top = Math.max(8, top);
    const originX = (a.left + a.width / 2) < vw / 2 ? 'left' : 'right';
    setPos({ top, left, origin: `${above ? 'bottom' : 'top'} ${originX}` });
  }, [open, anchor]);
  if (!open) return null;
  const nums = D.CONTACT.whatsNumbers || [];
  const msg = encodeURIComponent(D.CONTACT.whatsMsg || '');
  return (
    <React.Fragment>
      <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 119, background: 'transparent' }} />
      <div ref={ref} role="dialog" aria-modal="true" aria-label="Escolha um número de WhatsApp"
        style={{ position: 'fixed', top: pos.top, left: pos.left, zIndex: 120, width: 320, maxWidth: 'calc(100vw - 16px)',
          ...glassStyle, background: 'rgba(255,255,255,0.72)', backdropFilter: 'saturate(1.5) blur(44px)', WebkitBackdropFilter: 'saturate(1.5) blur(44px)', border: '1px solid rgba(255,255,255,0.85)', borderRadius: 'var(--radius-lg)', boxShadow: '0 24px 60px rgba(8,36,62,0.28)', padding: '18px 18px 16px',
          transformOrigin: pos.origin, animation: 'fcsWhatsPop 0.22s var(--ease-out) both' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <span style={{ width: 34, height: 34, borderRadius: '50%', background: '#1EA952', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}>
            <WhatsIcon size={19} color="#fff" />
          </span>
          <h3 style={{ margin: 0, fontFamily: 'var(--font-serif)', fontSize: 'var(--fs-h4)', fontWeight: 500, color: 'var(--text-strong)' }}>Falar no WhatsApp</h3>
          <button onClick={() => setOpen(false)} aria-label="Fechar" style={{ marginLeft: 'auto', width: 28, height: 28, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,0.5)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)' }}>
            <Icon name="x" size={16} />
          </button>
        </div>
        <p style={{ margin: '0 0 14px', fontSize: 'var(--fs-xs)', color: 'var(--text-body)', lineHeight: 'var(--lh-normal)' }}>Escolha um número e fale direto no WhatsApp.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {nums.map((n) => (
            <a key={n.phone} href={`https://wa.me/${n.phone}?text=${msg}`} target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)}
              className="fcs-whats-row"
              style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 'var(--radius-md)', border: '1px solid rgba(255,255,255,0.8)', textDecoration: 'none', background: 'rgba(255,255,255,0.82)', transition: 'border-color var(--dur-fast), background var(--dur-fast)' }}>
              <WhatsIcon size={19} color="#1EA952" />
              <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-sm)', color: 'var(--text-strong)' }}>{n.label}</span>
              <Icon name="arrow-right" size={16} color="var(--text-muted)" style={{ marginLeft: 'auto' }} />
            </a>
          ))}
        </div>
      </div>
    </React.Fragment>
  );
}

/* Botão flutuante persistente que abre o popup de números */
function FloatingWhats({ label = 'Fale conosco' }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button type="button" className="fcs-fab" onClick={openWhats} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ position: 'fixed', right: 24, bottom: 24, zIndex: 60, display: 'inline-flex', alignItems: 'center', gap: 10, padding: '13px 20px 13px 16px', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-pill)', background: '#1EA952', color: '#fff', fontFamily: 'var(--font-sans)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-sm)', boxShadow: hover ? '0 10px 28px rgba(30,169,82,0.45)' : '0 6px 20px rgba(30,169,82,0.35)', transform: hover ? 'translateY(-2px)' : 'none', transition: 'all var(--dur-normal) var(--ease-out)' }}>
      <WhatsIcon size={22} color="#fff" />
      {label}
    </button>
  );
}

function openWhats(e) {
  const nums = (D.CONTACT.whatsNumbers || []);
  if (nums.length <= 1) {
    const phone = (nums[0] && nums[0].phone) || D.CONTACT.whats;
    const msg = encodeURIComponent(D.CONTACT.whatsMsg || '');
    window.open('https://wa.me/' + phone + '?text=' + msg, '_blank', 'noopener');
    return;
  }
  let rect = null;
  try { const el = e && (e.currentTarget || e.target); if (el && el.getBoundingClientRect) { const r = el.getBoundingClientRect(); rect = { top: r.top, bottom: r.bottom, left: r.left, right: r.right, width: r.width }; } } catch (_) {}
  window.dispatchEvent(new CustomEvent('fcs:openwhats', { detail: { rect } }));
}

/* Envio de formulários por e-mail via FormSubmit (site estático, sem backend).
   1º envio: FormSubmit manda um e-mail de ativação para o destino — basta confirmar uma vez. */
function sendQuoteEmail(subject, fields) {
  const dest = D.CONTACT.emailQuote || D.CONTACT.email;
  const body = Object.assign({ _subject: subject, _template: 'table', _captcha: 'false' }, fields);
  return fetch('https://formsubmit.co/ajax/' + dest, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
    body: JSON.stringify(body),
  }).then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); });
}

/* Ícone oficial do WhatsApp (PNG branco usado como máscara — colore-se via background) */
function WhatsIcon({ size = 20, color = '#fff', style }) {
  return (
    <span aria-hidden="true" style={{ display: 'inline-block', flex: '0 0 auto', width: size, height: size, background: color, WebkitMaskImage: 'url(assets/whatsapp.png)', maskImage: 'url(assets/whatsapp.png)', WebkitMaskRepeat: 'no-repeat', maskRepeat: 'no-repeat', WebkitMaskPosition: 'center', maskPosition: 'center', WebkitMaskSize: 'contain', maskSize: 'contain', ...style }} />
  );
}

/* ---- Mount --------------------------------------------------------------
   Uso nas páginas:  FCS.mount((ctx) => <> ...seções... </>)               */
function mount(renderPage) {
  function App() {
    return (
      <React.Fragment>
        <Header />
        <main>{renderPage({})}</main>
        <Footer />
        <FloatingWhats label="Fale conosco" />
        <WhatsPicker />
      </React.Fragment>
    );
  }
  function go() {
    if (!window.FCS || !window.FCS.Footer) { setTimeout(go, 30); return; }
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
    const tick = () => window.lucide && window.lucide.createIcons();
    [80, 300, 800, 1500].forEach((t) => setTimeout(tick, t));
    setTimeout(function () {
      if (window.FCS.motion && window.FCS.motion.init) { window.FCS.motion.init({ smoothScroll: true, cursor: true }); return; }
      // fallback: reveal via IntersectionObserver
      const els = document.querySelectorAll('.reveal, .rise');
      if (!('IntersectionObserver' in window) || window.matchMedia('(prefers-reduced-motion: reduce)').matches) { els.forEach((e) => e.classList.add('in')); return; }
      const io = new IntersectionObserver((entries) => {
        entries.forEach((en) => { if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); } });
      }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
      els.forEach((e) => io.observe(e));
    }, 150);
  }
  go();
}

window.FCS = Object.assign(window.FCS || {}, {
  wrap, sectionPad, glassStyle, Blobs, Eyebrow, SectionHead, Photo, PartnerChip, Reveal,
  Header, Footer, Crumbs, PageHero, HeroCrumbs, FinalCTA, mount, SegRow, FeaturedSeguro, Marquee, SiteLogo, openWhats, WhatsPicker, FloatingWhats, WhatsIcon, sendQuoteEmail,
});
