/* maximiza.AI — shared components, tokens, atoms */
const { useState, useEffect, useRef } = React;

/* ── Color tokens — now CSS variables for theming ─ */
const C = {
  bg:      'var(--bg)',
  bg2:     'var(--bg2)',
  bg3:     'var(--bg3)',
  bg4:     'var(--bg4)',
  bg5:     'var(--bg5)',
  blue:    'var(--blue)',
  blue4:   'var(--blue4)',
  blue6:   'var(--blue6)',
  teal:    'var(--teal)',
  teal4:   'var(--teal4)',
  fg:      'var(--fg)',
  fg2:     'var(--fg2)',
  fg3:     'var(--fg3)',
  fg4:     'var(--fg4)',
  border:  'var(--border)',
  borderM: 'var(--borderM)',
  borderB: 'var(--borderB)',
  borderT: 'var(--borderT)',
};

/* Plus Jakarta Sans as primary (display + body). Geologica as secondary for labels/metadata. */
const FONT_SANS    = "'Plus Jakarta Sans', system-ui, sans-serif";
const FONT_DISPLAY = "'Plus Jakarta Sans', system-ui, sans-serif";
const FONT_LABEL   = "'Geologica', 'Plus Jakarta Sans', system-ui, sans-serif";
const FONT_MONO    = "'Geologica', 'DM Mono', 'Fira Mono', ui-monospace, monospace";

/* ── Tone helper — since CSS vars break equality checks,
   carry semantic tone strings in data and resolve colors + rgb through this map. */
const TONE = {
  blue:      { color: 'var(--blue)',  rgb: '91,156,255',  border: 'var(--borderB)' },
  blueLight: { color: 'var(--blue4)', rgb: '123,178,255', border: 'var(--borderB)' },
  teal:      { color: 'var(--teal)',  rgb: '102,205,204', border: 'var(--borderT)' },
  tealLight: { color: 'var(--teal4)', rgb: '133,218,218', border: 'var(--borderT)' },
};
function tone(t) { return TONE[t] || TONE.blue; }

/* ── Theme context ─────────────────────────────── */
const ThemeCtx = React.createContext({ theme:'dark', setTheme:() => {} });
function useTheme() { return React.useContext(ThemeCtx); }

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => {
    try { return localStorage.getItem('mxai-theme') || 'dark'; }
    catch (e) { return 'dark'; }
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    try { localStorage.setItem('mxai-theme', theme); } catch (e) {}
  }, [theme]);
  return <ThemeCtx.Provider value={{theme, setTheme}}>{children}</ThemeCtx.Provider>;
}

function ThemeToggle() {
  const { theme, setTheme } = useTheme();
  const isDark = theme === 'dark';
  return (
    <button
      onClick={() => setTheme(isDark ? 'light' : 'dark')}
      aria-label={isDark ? 'Ativar modo claro' : 'Ativar modo escuro'}
      style={{
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        width:34, height:34, borderRadius:9999,
        background:'transparent', border:`1px solid ${C.border}`,
        cursor:'pointer', color:C.fg2, transition:'all .15s',
      }}
      onMouseEnter={e => { e.currentTarget.style.color = C.fg; e.currentTarget.style.borderColor = C.borderM; }}
      onMouseLeave={e => { e.currentTarget.style.color = C.fg2; e.currentTarget.style.borderColor = C.border; }}
    >
      {isDark ? (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
      ) : (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
      )}
    </button>
  );
}

/* ── Logo mark SVG ──────────────────────────────── */
function LogoMark({ size = 32 }) {
  const id = `lm${size}`;
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" fill="none">
      <defs>
        <radialGradient id={`${id}t`} cx="38%" cy="32%" r="62%"><stop offset="0%" stopColor="#8EEAE0"/><stop offset="100%" stopColor="#28B8B0"/></radialGradient>
        <radialGradient id={`${id}r`} cx="38%" cy="32%" r="62%"><stop offset="0%" stopColor="#7ACEF8"/><stop offset="100%" stopColor="#3278E0"/></radialGradient>
        <radialGradient id={`${id}l`} cx="38%" cy="32%" r="62%"><stop offset="0%" stopColor="#3A8AC8"/><stop offset="100%" stopColor="#082050"/></radialGradient>
      </defs>
      <circle cx="50" cy="33" r="26" fill={`url(#${id}t)`} stroke={C.bg} strokeWidth="2.5"/>
      <circle cx="28" cy="68" r="26" fill={`url(#${id}l)`} stroke={C.bg} strokeWidth="2.5"/>
      <circle cx="70" cy="68" r="26" fill={`url(#${id}r)`} stroke={C.bg} strokeWidth="2.5"/>
    </svg>
  );
}

/* ── Animated Logo — "breathing" version for hero/feature spots ── */
function LogoMarkAnimated({ size = 140 }) {
  const id = `lma${size}`;
  return (
    <div style={{
      width:size, height:size, position:'relative', display:'inline-block',
    }}>
      <svg width={size} height={size} viewBox="0 0 140 140" fill="none" style={{overflow:'visible'}}>
        <defs>
          <radialGradient id={`${id}t`} cx="38%" cy="32%" r="62%"><stop offset="0%" stopColor="#8EEAE0"/><stop offset="100%" stopColor="#28B8B0"/></radialGradient>
          <radialGradient id={`${id}r`} cx="38%" cy="32%" r="62%"><stop offset="0%" stopColor="#7ACEF8"/><stop offset="100%" stopColor="#3278E0"/></radialGradient>
          <radialGradient id={`${id}l`} cx="38%" cy="32%" r="62%"><stop offset="0%" stopColor="#3A8AC8"/><stop offset="100%" stopColor="#082050"/></radialGradient>
          <filter id={`${id}glow`} x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="4" result="blur"/>
            <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>

        {/* Soft halo behind */}
        <circle cx="70" cy="70" r="60" fill={`url(#${id}t)`} opacity=".08">
          <animate attributeName="r" values="58;66;58" dur="4s" repeatCount="indefinite"/>
          <animate attributeName="opacity" values=".06;.14;.06" dur="4s" repeatCount="indefinite"/>
        </circle>

        {/* Top/teal circle */}
        <g style={{transformOrigin:'70px 48px'}}>
          <circle cx="70" cy="48" r="30" fill={`url(#${id}t)`} filter={`url(#${id}glow)`}>
            <animate attributeName="r" values="28;32;28" dur="3.2s" repeatCount="indefinite"/>
            <animate attributeName="cy" values="48;45;48" dur="3.2s" repeatCount="indefinite"/>
          </circle>
        </g>

        {/* Left/navy circle */}
        <g>
          <circle cx="42" cy="90" r="30" fill={`url(#${id}l)`} filter={`url(#${id}glow)`}>
            <animate attributeName="r" values="28;32;28" dur="3.2s" begin=".5s" repeatCount="indefinite"/>
            <animate attributeName="cx" values="42;39;42" dur="3.2s" begin=".5s" repeatCount="indefinite"/>
          </circle>
        </g>

        {/* Right/blue circle */}
        <g>
          <circle cx="98" cy="90" r="30" fill={`url(#${id}r)`} filter={`url(#${id}glow)`}>
            <animate attributeName="r" values="28;32;28" dur="3.2s" begin="1s" repeatCount="indefinite"/>
            <animate attributeName="cx" values="98;101;98" dur="3.2s" begin="1s" repeatCount="indefinite"/>
          </circle>
        </g>
      </svg>
    </div>
  );
}


/* ── Icon (Lucide paths) ───────────────────────── */
function Icon({ d, color = C.blue, size = 20, sw = 1.5 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke={color} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      {(Array.isArray(d) ? d : [d]).map((p, i) => <path key={i} d={p}/>)}
    </svg>
  );
}

/* ── Btn ───────────────────────────────────────── */
function Btn({ children, variant = 'primary', onClick, sm, href, full }) {
  const [h, setH] = useState(false);
  const s = {
    primary: { bg: h ? C.blue4 : C.blue, color:'#fff', shadow: h ? '0 10px 32px rgba(91,156,255,.45), 0 0 0 1px rgba(255,255,255,.12) inset' : '0 4px 14px rgba(91,156,255,.22), 0 0 0 1px rgba(255,255,255,.08) inset', border:'none' },
    teal:    { bg: h ? C.teal4 : C.teal, color:'#001A1A', shadow: h ? '0 10px 28px rgba(102,205,204,.45), 0 0 0 1px rgba(255,255,255,.15) inset' : '0 4px 12px rgba(102,205,204,.18), 0 0 0 1px rgba(255,255,255,.1) inset', border:'none' },
    outline: { bg: h ? 'var(--bg3)' : 'transparent', color: h ? C.fg : C.fg2, border:`1.5px solid ${h ? C.borderM : C.border}`, shadow: h ? '0 6px 20px rgba(0,0,0,.08)' : 'none' },
    ghost:   { bg:'transparent', color: h ? C.blue4 : C.fg3, border:'none', shadow:'none' },
  }[variant] || {};

  const hasShimmer = variant === 'primary' || variant === 'teal';

  const common = {
    position:'relative', overflow:'hidden',
    fontFamily: FONT_SANS, fontWeight:600, cursor:'pointer',
    borderRadius: sm ? 7 : 9, fontSize: sm ? 13 : 15,
    padding: sm ? '8px 16px' : '13px 26px',
    display:'inline-flex', alignItems:'center', gap:6,
    transition:'transform .2s cubic-bezier(.22,1,.36,1), box-shadow .25s, background .2s, color .2s, border-color .2s',
    transform: h ? 'translateY(-1px)' : 'translateY(0)',
    background: s.bg, color: s.color, boxShadow: s.shadow,
    border: s.border || 'none',
    width: full ? '100%' : 'auto', justifyContent: full ? 'center' : 'flex-start',
    textDecoration:'none',
  };

  // Children with animated arrow: detect trailing '→' and wrap so it slides
  const kids = renderBtnKids(children, h);

  const shine = hasShimmer ? (
    <span aria-hidden style={{
      position:'absolute', inset:0, borderRadius:'inherit', pointerEvents:'none',
      overflow:'hidden',
    }}>
      <span style={{
        position:'absolute', top:0, bottom:0, width:'40%',
        left: h ? '110%' : '-50%',
        background:'linear-gradient(100deg, transparent 0%, rgba(255,255,255,.28) 50%, transparent 100%)',
        transition: h ? 'left .7s cubic-bezier(.22,1,.36,1)' : 'left 0s',
        transform:'skewX(-15deg)',
      }}/>
    </span>
  ) : null;

  if (href) return <a href={href} target="_blank" rel="noopener" style={common} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}>{shine}<span style={{position:'relative',display:'inline-flex',alignItems:'center',gap:6}}>{kids}</span></a>;
  return <button onClick={onClick} style={common} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}>{shine}<span style={{position:'relative',display:'inline-flex',alignItems:'center',gap:6}}>{kids}</span></button>;
}

/* Split children so trailing arrow (→) animates on hover */
function renderBtnKids(children, h) {
  if (typeof children !== 'string') return children;
  const m = children.match(/^(.*?)(\s*→)\s*$/);
  if (!m) return children;
  return (
    <>
      {m[1]}
      <span style={{
        display:'inline-block',
        transform: h ? 'translateX(4px)' : 'translateX(0)',
        transition:'transform .25s cubic-bezier(.22,1,.36,1)',
      }}>{m[2].trim()}</span>
    </>
  );
}

/* ── Label pill — tone:'blue' | 'teal' ─────── */
function Pill({ children, tone = 'blue', color }) {
  const isTeal = tone === 'teal';
  const txt = color || (isTeal ? C.teal : C.blue);
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:5,
      fontSize:10, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase',
      fontFamily: FONT_LABEL, color: txt,
      background: isTeal ? 'rgba(102,205,204,.08)' : 'rgba(91,156,255,.08)',
      border:`1px solid ${isTeal ? C.borderT : C.borderB}`,
      borderRadius:9999, padding:'3px 9px',
    }}>{children}</span>
  );
}

/* ── Section label (small caps above heading) ── */
function SectionLabel({ children, color = C.blue }) {
  return (
    <div style={{fontSize:11, fontWeight:700, letterSpacing:'.10em', textTransform:'uppercase',
      color, fontFamily: FONT_SANS, marginBottom:12}}>
      {children}
    </div>
  );
}

/* ── Divider ────────────────────────────────────── */
function Divider() {
  return <div style={{height:1, background:C.border, margin:'0 48px'}}/>;
}

/* ── Scroll reveal hook ─────────────────────────── */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const obs = new IntersectionObserver(
      entries => entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('visible'); }),
      { threshold: 0.1 }
    );
    els.forEach(el => obs.observe(el));
    return () => obs.disconnect();
  });
}

/* ── Nav ───────────────────────────────────────── */
function Nav({ page, setPage }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const el = document.getElementById('scroll-root');
    if (!el) return;
    const h = () => setScrolled(el.scrollTop > 20);
    el.addEventListener('scroll', h);
    return () => el.removeEventListener('scroll', h);
  }, []);

  const links = [
    { label:'Problemas', id:'problemas' },
    { label:'Ofertas', id:'ofertas' },
    { label:'Como funciona', id:'metodo' },
    { label:'Demos', id:'demos' },
  ];

  const scrollTo = (id) => {
    setPage('home');
    setMobileOpen(false);
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) {
        const root = document.getElementById('scroll-root');
        root.scrollTop = el.offsetTop - 70;
      }
    }, 50);
  };

  return (
    <nav style={{
      position:'sticky', top:0, zIndex:200,
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding:'0 clamp(20px,4vw,48px)', height:62,
      background: scrolled ? 'var(--nav-bg-scroll)' : 'var(--nav-bg-rest)',
      backdropFilter:'blur(18px)', WebkitBackdropFilter:'blur(18px)',
      borderBottom:`1px solid ${scrolled ? C.borderM : 'transparent'}`,
      transition:'border-color .25s ease',
    }}>
      <button onClick={() => setPage('home')} style={{display:'flex',alignItems:'center',gap:9,background:'none',border:'none',cursor:'pointer'}}>
        <LogoMark size={26}/>
        <span style={{fontSize:15,fontWeight:700,color:C.fg,letterSpacing:'-0.01em',fontFamily: FONT_SANS}}>
          maximiza<span style={{color:C.blue}}>.AI</span>
        </span>
      </button>

      <div style={{display:'flex', gap:12, alignItems:'center'}}>
        {links.map(l => (
          <button key={l.id} onClick={() => scrollTo(l.id)} style={{
            display: 'none',
            background:'none',border:'none',cursor:'pointer',fontFamily: FONT_SANS,
            fontSize:13,fontWeight:500,color:C.fg3,transition:'color .15s',
          }}
          className="nav-link"
          onMouseEnter={e => e.target.style.color = C.fg}
          onMouseLeave={e => e.target.style.color = C.fg3}>{l.label}</button>
        ))}
        <ThemeToggle/>
        <Btn sm onClick={() => setPage('contato')}>Conversa inicial →</Btn>
      </div>
    </nav>
  );
}

/* ── Ticker ─────────────────────────────────────── */
function Ticker() {
  const items = ['Diagnóstico de operação','Visibilidade de dados','Dashboard executivo','Automação de backoffice','IA aplicada a PMEs','Escopo fechado','Entrada leve','Relatório automático','Site Institucional','Clareza operacional'];
  const all = [...items,...items];
  return (
    <div style={{overflow:'hidden',borderTop:`1px solid ${C.border}`,borderBottom:`1px solid ${C.border}`,padding:'11px 0',background:C.bg}}>
      <div style={{display:'flex',gap:48,animation:'ticker 22s linear infinite',width:'max-content'}}>
        {all.map((item,i) => (
          <span key={i} style={{fontSize:11,fontWeight:500,color:C.fg3,display:'flex',alignItems:'center',gap:10,whiteSpace:'nowrap',fontFamily:FONT_SANS}}>
            <span style={{width:4,height:4,borderRadius:'50%',background:i%2===0?C.blue:C.teal,display:'inline-block',flexShrink:0}}/>
            {item}
          </span>
        ))}
      </div>
    </div>
  );
}

/* ── Footer ─────────────────────────────────────── */
function Footer({ setPage }) {
  const cols = [
    { title:'Ofertas', links:[
      { l:'Diagnóstico', fn:() => setPage('home') },
      { l:'Dashboard executivo', fn:() => setPage('home') },
      { l:'Relatório automático', fn:() => setPage('home') },
      { l:'Site Institucional', fn:() => setPage('home') },
      { l:'Site Express', fn:() => setPage('home') },
    ]},
    { title:'Como funciona', links:[
      { l:'Conversa inicial gratuita', fn:() => setPage('contato') },
      { l:'Método de entrega', fn:() => setPage('home') },
      { l:'Demos e samples', fn:() => setPage('home') },
    ]},
    { title:'Contato', links:[
      { l:'contato@maximiza.ai', fn:() => {} },
      { l:'Conversa inicial', fn:() => setPage('contato') },
    ]},
  ];
  return (
    <footer style={{borderTop:`1px solid ${C.border}`,background:C.bg,padding:'48px clamp(20px,4vw,48px) 28px'}}>
      <div style={{maxWidth:1100,margin:'0 auto'}}>
        <SpotlightWordmark/>
        <div style={{display:'grid',gridTemplateColumns:'2fr 1fr 1fr 1fr',gap:40,margin:'48px 0',flexWrap:'wrap'}}>
          <div>
            <div style={{display:'flex',alignItems:'center',gap:9,marginBottom:16}}>
              <LogoMark size={28}/>
              <span style={{fontSize:16,fontWeight:700,color:C.fg,fontFamily:FONT_SANS}}>maximiza<span style={{color:C.blue}}>.AI</span></span>
            </div>
            <p style={{fontSize:13,color:C.fg3,lineHeight:1.7,maxWidth:260,marginBottom:16}}>
              Da confusão à clareza. Do achismo à decisão.
            </p>
            <a href="mailto:contato@maximiza.ai" style={{fontSize:12,color:C.fg3,fontFamily:FONT_MONO,textDecoration:'none'}}>contato@maximiza.ai</a>
          </div>
          {cols.map(col => (
            <div key={col.title}>
              <div style={{fontSize:11,fontWeight:700,letterSpacing:'.08em',textTransform:'uppercase',color:C.fg4,fontFamily:FONT_SANS,marginBottom:14}}>{col.title}</div>
              <div style={{display:'flex',flexDirection:'column',gap:9}}>
                {col.links.map(lk => (
                  <button key={lk.l} onClick={lk.fn} style={{background:'none',border:'none',cursor:'pointer',textAlign:'left',fontSize:13,color:C.fg3,fontFamily:FONT_SANS,padding:0,transition:'color .15s'}}
                    onMouseEnter={e => e.currentTarget.style.color = C.fg}
                    onMouseLeave={e => e.currentTarget.style.color = C.fg3}>
                    {lk.l}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{borderTop:`1px solid ${C.border}`,paddingTop:20,display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:10}}>
          <span style={{fontSize:11,color:C.fg4,fontFamily:FONT_SANS}}>© 2026 maximiza.AI · Todos os direitos reservados</span>
          <div style={{display:'flex',gap:16}}>
            <button style={{background:'none',border:'none',cursor:'pointer',fontSize:11,color:C.fg4,fontFamily:FONT_SANS}}>Política de privacidade</button>
            <button style={{background:'none',border:'none',cursor:'pointer',fontSize:11,color:C.fg4,fontFamily:FONT_SANS}}>LGPD</button>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ── Spotlight Wordmark (Resend-style mouse-tracked reveal) ── */
function SpotlightWordmark() {
  const ref = useRef(null);
  const [hover, setHover] = useState(false);

  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    el.style.setProperty('--mx', `${e.clientX - r.left - 200}px`);
    el.style.setProperty('--my', `${e.clientY - r.top - 200}px`);
  };

  return (
    <div
      ref={ref}
      onMouseMove={onMove}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position:'relative',
        margin:'0 auto',
        width:'100%', maxWidth:1100,
        overflow:'hidden',
        borderRadius:20,
        padding:'clamp(24px,6vw,72px) 0',
        cursor:'default',
        userSelect:'none',
      }}
    >
      {/* Dim base wordmark */}
      <div style={{
        fontFamily: FONT_DISPLAY, fontWeight:800, letterSpacing:'-0.03em',
        fontSize:'clamp(64px,16vw,220px)', lineHeight:.85, textAlign:'center',
        color:'var(--fg)', opacity:.07,
        pointerEvents:'none', textWrap:'nowrap', whiteSpace:'nowrap',
      }}>
        MAXIMIZA
      </div>

      {/* Highlighted wordmark, masked to pointer spotlight */}
      <div style={{
        position:'absolute', inset:0,
        display:'flex', alignItems:'center', justifyContent:'center',
        pointerEvents:'none',
        opacity: hover ? 1 : 0,
        transition:'opacity .5s ease-out',
        maskImage: 'radial-gradient(250px at calc(var(--mx, 50%) + 200px) calc(var(--my, 50%) + 200px), black 0%, black 30%, transparent 75%)',
        WebkitMaskImage: 'radial-gradient(250px at calc(var(--mx, 50%) + 200px) calc(var(--my, 50%) + 200px), black 0%, black 30%, transparent 75%)',
      }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontWeight:800, letterSpacing:'-0.03em',
          fontSize:'clamp(64px,16vw,220px)', lineHeight:.85, textAlign:'center',
          background:`linear-gradient(120deg, ${C.blue} 0%, ${C.teal} 100%)`,
          WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent',
          textWrap:'nowrap', whiteSpace:'nowrap',
        }}>
          MAXIMIZA
        </div>
      </div>

      {/* Soft radial glow that follows cursor (even stronger under spotlight) */}
      <div aria-hidden style={{
        position:'absolute', inset:0, pointerEvents:'none',
        opacity: hover ? 1 : 0,
        transition:'opacity .4s ease-out',
        background: `radial-gradient(400px at calc(var(--mx, 50%) + 200px) calc(var(--my, 50%) + 200px), rgba(91,156,255,.16), transparent 70%)`,
      }}/>
    </div>
  );
}

Object.assign(window, { C, FONT_DISPLAY, FONT_SANS, FONT_LABEL, FONT_MONO, TONE, tone, LogoMark, LogoMarkAnimated, Icon, Btn, Pill, SectionLabel, Divider, Ticker, Nav, Footer, useReveal, ThemeProvider, ThemeToggle, useTheme, SpotlightWordmark });

/* ── Glass surface helper ── */
const GLASS = (opts = {}) => ({
  background: opts.strong ? 'color-mix(in oklab, var(--bg3) 70%, transparent)' : 'color-mix(in oklab, var(--bg3) 55%, transparent)',
  backdropFilter: 'blur(18px) saturate(140%)',
  WebkitBackdropFilter: 'blur(18px) saturate(140%)',
  border: `1px solid color-mix(in oklab, var(--fg) 8%, transparent)`,
  boxShadow: opts.strong
    ? '0 20px 60px rgba(0,0,0,.18), inset 0 1px 0 color-mix(in oklab, var(--fg) 6%, transparent)'
    : '0 10px 32px rgba(0,0,0,.12), inset 0 1px 0 color-mix(in oklab, var(--fg) 4%, transparent)',
});

/* ── Tilt card (subtle 3D on hover, follows cursor) ── */
function TiltCard({ children, strength = 6, style, ...rest }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width;
    const y = (e.clientY - r.top) / r.height;
    const rx = ((0.5 - y) * strength).toFixed(2);
    const ry = ((x - 0.5) * strength).toFixed(2);
    el.style.transform = `perspective(900px) rotateX(${rx}deg) rotateY(${ry}deg) translateZ(0)`;
    el.style.setProperty('--sx', `${x * 100}%`);
    el.style.setProperty('--sy', `${y * 100}%`);
  };
  const reset = () => {
    const el = ref.current; if (!el) return;
    el.style.transform = 'perspective(900px) rotateX(0) rotateY(0) translateZ(0)';
  };
  return (
    <div
      ref={ref}
      onMouseMove={onMove}
      onMouseLeave={reset}
      style={{
        transition:'transform .25s cubic-bezier(.22,1,.36,1)',
        transformStyle:'preserve-3d', willChange:'transform',
        position:'relative',
        ...style,
      }}
      {...rest}
    >
      {children}
      {/* Shine overlay that follows cursor */}
      <div aria-hidden style={{
        position:'absolute', inset:0, borderRadius:'inherit', pointerEvents:'none',
        background:'radial-gradient(240px at var(--sx,50%) var(--sy,50%), color-mix(in oklab, var(--fg) 8%, transparent), transparent 60%)',
        opacity:0, transition:'opacity .25s ease',
      }} className="tilt-shine"/>
    </div>
  );
}

/* ── Number count-up (animates when element enters viewport) ── */
function CountUp({ to, from = 0, duration = 1400, prefix = '', suffix = '', decimals = 0, format }) {
  const ref = useRef(null);
  const [val, setVal] = useState(from);
  const done = useRef(false);

  useEffect(() => {
    const el = ref.current; if (!el) return;
    const runAnim = () => {
      if (done.current) return;
      done.current = true;
      const t0 = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(from + (to - from) * eased);
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };
    const check = () => {
      const rect = el.getBoundingClientRect();
      return rect.top < window.innerHeight + 100 && rect.bottom > -100;
    };
    const raf1 = requestAnimationFrame(() => {
      if (check()) { runAnim(); return; }
      const root = document.getElementById('scroll-root') || null;
      const io = new IntersectionObserver((entries) => {
        for (const en of entries) if (en.isIntersecting) { runAnim(); io.disconnect(); }
      }, { threshold: 0.3, root });
      io.observe(el);
    });
    const safety = setTimeout(() => runAnim(), 2500);
    return () => { cancelAnimationFrame(raf1); clearTimeout(safety); };
  }, [to, from, duration]);

  const display = format
    ? format(val)
    : prefix + val.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, '.') + suffix;
  return <span ref={ref}>{display}</span>;
}

/* ── Word-by-word reveal (stagger fade+rise) ── */
function WordReveal({ children, delayBase = 0, stagger = 60, className = '', style }) {
  // Accept string or array of segments ({t, gradient?, className?})
  const segs = Array.isArray(children) ? children : [{t: String(children)}];
  let idx = 0;
  return (
    <span className={className} style={style}>
      {segs.map((seg, si) => {
        const words = seg.t.split(/(\s+)/);
        return words.map((w, wi) => {
          if (/^\s+$/.test(w)) return <span key={`${si}-${wi}`}>{w}</span>;
          const d = delayBase + idx * stagger;
          idx++;
          const inner = (
            <span className="wr-in" style={{
              display:'inline-block',
              animationDelay: `${d}ms`,
              transformOrigin:'50% 100%',
              ...(seg.gradient ? {
                background: seg.gradient,
                WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent', backgroundClip:'text',
              } : {}),
            }}>{w}</span>
          );
          return <span key={`${si}-${wi}`} style={{display:'inline-block'}}>{inner}</span>;
        });
      })}
    </span>
  );
}

Object.assign(window, { TiltCard, CountUp, WordReveal, GLASS });

