// =====================================================
// SOSSEG — App principal
//
// EDITÁVEL: configurações da marca/aparência ficam em
// CONFIG abaixo. Para mudar cor primária, modo escuro,
// densidade ou hero, edite os valores e salve. F5.
// =====================================================

const CONFIG = {
  primary:       '#0B3D6B',  // azul SOSSEG (cor primária)
  accent:        '#10B981',  // verde de destaque
  dark:          false,      // true = modo escuro
  density:       'comfortable', // 'comfortable' | 'compact'
  heroStyle:     'gradient', // 'photo' | 'gradient' | 'solid'
  showSimulator: true,       // false esconde a seção "Simulador"
};

function App() {
  const [active, setActive] = React.useState('home');
  const [quoteOpen, setQuoteOpen] = React.useState(false);
  const [presetProduct, setPresetProduct] = React.useState(null);

  // Compute relative luminance from hex to pick readable text color
  const readableInk = (hex) => {
    if (!hex || typeof hex !== 'string') return '#fff';
    const m = hex.replace('#', '');
    const full = m.length === 3 ? m.split('').map(c => c + c).join('') : m;
    if (full.length !== 6) return '#fff';
    const r = parseInt(full.slice(0, 2), 16) / 255;
    const g = parseInt(full.slice(2, 4), 16) / 255;
    const b = parseInt(full.slice(4, 6), 16) / 255;
    const lin = (c) => c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
    const L = 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
    const cWhite = 1.05 / (L + 0.05);
    const cBlack = (L + 0.05) / 0.05;
    return cBlack > cWhite ? '#0E1726' : '#ffffff';
  };

  // Apply CONFIG to CSS variables
  React.useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty('--primary', CONFIG.primary);
    root.style.setProperty('--accent', CONFIG.accent);
    root.style.setProperty('--primary-ink', readableInk(CONFIG.primary));
    root.style.setProperty('--accent-ink', readableInk(CONFIG.accent));
    const mixBase = CONFIG.dark ? 'black' : 'white';
    const p50Pct = CONFIG.dark ? 14 : 8;
    const aSoftPct = CONFIG.dark ? 18 : 16;
    root.style.setProperty('--primary-50',
      `color-mix(in oklab, ${CONFIG.primary} ${p50Pct}%, ${mixBase})`);
    root.style.setProperty('--primary-700',
      `color-mix(in oklab, ${CONFIG.primary} 78%, black)`);
    root.style.setProperty('--accent-soft',
      `color-mix(in oklab, ${CONFIG.accent} ${aSoftPct}%, ${mixBase})`);
    root.setAttribute('data-dark', CONFIG.dark ? 'true' : 'false');
    root.setAttribute('data-density', CONFIG.density);
  }, []);

  const navTo = (id) => {
    if (id === 'cotacao') {
      setPresetProduct(null);
      setQuoteOpen(true);
      return;
    }
    setActive(id);
    const el = document.getElementById(id);
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  };

  const openQuote = (productId) => {
    setPresetProduct(productId);
    setQuoteOpen(true);
  };

  React.useEffect(() => {
    const sections = ['home', 'produtos', 'sobre', 'equipe', 'confianca', 'seguradoras', 'casos', 'atuacao', 'historia', 'blog', 'contato'];
    const onScroll = () => {
      const y = window.scrollY + 120;
      for (let i = sections.length - 1; i >= 0; i--) {
        const el = document.getElementById(sections[i]);
        if (el && el.offsetTop <= y) {
          setActive(sections[i]);
          return;
        }
      }
    };
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <div>
      <a href="#main" style={{
        position: 'absolute', left: -9999, top: 0,
        background: 'var(--primary)', color: 'var(--primary-ink)',
        padding: '12px 18px', borderRadius: 0, zIndex: 999,
      }} onFocus={(e) => e.target.style.left = '0'} onBlur={(e) => e.target.style.left = '-9999px'}>
        Pular para o conteúdo
      </a>
      <Header active={active} onNav={navTo} />
      <main id="main">
        <Hero heroStyle={CONFIG.heroStyle} onNav={navTo} />
        <Products onQuote={openQuote} />
        <Credibility />
        {CONFIG.showSimulator && <Simulator onQuote={openQuote} />}
        <About />
        <Team />
        <Trust />
        <Insurers />
        <Cases />
        <Coverage />
        <Timeline />
        <Blog />
        <FAQ />
        <Contact />
      </main>
      <Footer />

      <WhatsappFAB />
      <Quote open={quoteOpen} onClose={() => setQuoteOpen(false)} presetProduct={presetProduct} />
    </div>
  );
}

// Boot: aguarda conteúdo do CMS carregar antes de renderizar
function Boot() {
  const [ready, setReady] = React.useState(!!window.SITE);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    if (window.SITE) { setReady(true); return; }
    const onReady = () => setReady(true);
    document.addEventListener('site-ready', onReady);
    if (window.__SITE_READY__) {
      window.__SITE_READY__.catch((e) => setError(e.message || String(e)));
    }
    return () => document.removeEventListener('site-ready', onReady);
  }, []);
  if (error) {
    return (
      <div style={{ padding: 40, fontFamily: 'system-ui', color: '#b91c1c' }}>
        <strong>Erro carregando conteúdo:</strong> {error}
      </div>
    );
  }
  if (!ready) {
    return (
      <div style={{
        position: 'fixed', inset: 0, display: 'flex', alignItems: 'center',
        justifyContent: 'center', background: 'var(--bg)', color: 'var(--ink)',
        fontFamily: 'system-ui',
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            width: 32, height: 32, border: '3px solid var(--line)',
            borderTopColor: 'var(--primary)', borderRadius: '50%',
            margin: '0 auto 14px', animation: 'spin 0.8s linear infinite',
          }} />
          <div style={{ fontSize: 13, color: 'var(--muted)', fontFamily: 'var(--mono)' }}>
            carregando…
          </div>
          <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
        </div>
      </div>
    );
  }
  return <App />;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Boot />);
