// Hi-Fi B — Top components (Header, Hero, Categories, Ticker)
// Reads from window.Store

const { useState, useEffect, useRef } = React;

function useReveal() {
  useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach((el) => obs.observe(el));
    return () => obs.disconnect();
  }, []);
}

function useStoreData() {
  const [data, setData] = useState({
    settings: window.Store.getSettings(),
    categories: window.Store.getCategories(),
    products: window.Store.getProducts(),
    testimonials: window.Store.getTestimonials().filter((t) => t.published),
    differentials: window.Store.getDifferentials(),
    processSteps: window.Store.getProcessSteps(),
    instagram: window.Store.getInstagram(),
  });
  useEffect(() => window.Store.subscribe(() => setData({
    settings: window.Store.getSettings(),
    categories: window.Store.getCategories(),
    products: window.Store.getProducts(),
    testimonials: window.Store.getTestimonials().filter((t) => t.published),
    differentials: window.Store.getDifferentials(),
    processSteps: window.Store.getProcessSteps(),
    instagram: window.Store.getInstagram(),
  })), []);
  return data;
}

function Header() {
  const [scrolled, setScrolled] = useState(false);
  const s = window.Store.getSettings();
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 80,
      background: scrolled ? 'rgba(245,241,232,0.96)' : 'transparent',
      backdropFilter: scrolled ? 'blur(12px)' : 'none',
      borderBottom: scrolled ? '2px solid var(--ink)' : '2px solid transparent',
      transition: 'all 0.25s ease',
    }}>
      <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px var(--section-pad-x)' }}>
        <a href="index.html#hero" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="logo.png" alt="Alcantara Studio 3D" style={{ height: 42, width: 42, objectFit: 'contain', display: 'block', borderRadius: 8 }} />
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, lineHeight: 1, letterSpacing: '-0.01em' }}>{s.brand}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.18em', color: 'var(--muted)' }}>{s.brandSub}</div>
          </div>
        </a>
        <nav style={{ display: 'flex', gap: 28, fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          <a href="index.html#catalog">Catálogo</a>
          <a href="index.html#process">Processo</a>
          <a href="index.html#diff">Diferenciais</a>
          <a href="index.html#testimonials">Clientes</a>
        </nav>
        <a href={`https://wa.me/${s.whatsapp}`} target="_blank" rel="noopener" className="btn btn-primary" style={{ padding: '12px 18px', fontSize: 12 }}>
          <Icon name="whatsapp" size={14} /> Orçar
        </a>
      </div>
    </header>
  );
}

function Ticker() {
  const items = ['EDIÇÃO LIMITADA', 'ENTREGA NACIONAL', 'ORÇAMENTO GRÁTIS', 'IMPRESSÃO 3D PERSONALIZADA', 'RESPOSTA EM 2H'];
  const repeated = [...items, ...items, ...items, ...items];
  return (
    <div style={{ background: 'var(--ink)', color: 'var(--accent)', padding: '10px 0', overflow: 'hidden', borderTop: '2px solid var(--ink)', borderBottom: '2px solid var(--ink)' }}>
      <div className="ticker-track" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600, letterSpacing: '0.2em' }}>
        {repeated.map((it, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 40 }}><Icon name="sparkle" size={11} /> {it}</span>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  const s = window.Store.getSettings();
  const heroCopy = s.heroCopy || 'PEÇAS<br/><em>únicas</em><br/>EM 3D.';
  const badgeText = s.heroBadge ? s.heroBadge.split('\n') : null;
  return (
    <section id="hero" style={{ position: 'relative', minHeight: '92vh', paddingTop: 110, paddingBottom: 50, overflow: 'hidden' }}>
      <div className="glow-ring" style={{ width: 800, height: 800, top: -200, right: -200 }} />
      <div className="glow-ring" style={{ width: 500, height: 500, bottom: -100, left: -100, opacity: 0.6 }} />
      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 60, alignItems: 'center' }}>
          <div className="reveal in">
            <div className="font-mono" style={{ fontSize: 12, letterSpacing: '0.25em', color: 'var(--primary)', fontWeight: 700, marginBottom: 24, display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 30, height: 2, background: 'var(--primary)' }}></span>
              {s.heroEdition}
            </div>
            <h1 className="h-display" dangerouslySetInnerHTML={{ __html: heroCopy }} />
            <p style={{ fontSize: 16, lineHeight: 1.55, color: 'var(--ink-2)', marginTop: 26, maxWidth: 460, fontWeight: 500 }}>
              {s.heroBody}
            </p>
            <div style={{ display: 'flex', gap: 16, marginTop: 40, flexWrap: 'wrap' }}>
              <a href={`https://wa.me/${s.whatsapp}`} target="_blank" rel="noopener" className="btn btn-primary btn-lg">
                <Icon name="whatsapp" size={18} /> Orçar no WhatsApp
              </a>
              <a href="#catalog" className="btn">Ver catálogo <Icon name="arrow-down" size={16} /></a>
            </div>
            <div style={{ display: 'flex', gap: 32, marginTop: 56 }}>
              {[
                { n: s.stat1Number, l: s.stat1Label },
                { n: s.stat2Number, l: s.stat2Label },
                { n: s.stat3Number, l: s.stat3Label },
              ].map((st, i) => (
                <div key={i}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, color: 'var(--primary)', lineHeight: 1 }}>{st.n}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 4 }}>{st.l}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ position: 'relative' }} className="reveal in">
            <div style={{
              aspectRatio: '4/5',
              background: `linear-gradient(135deg, var(--primary) 0%, var(--secondary) 60%, var(--accent) 100%)`,
              border: '3px solid var(--ink)', boxShadow: '12px 12px 0 var(--ink)',
              position: 'relative', overflow: 'hidden',
            }}>
              <div className="halftone" style={{ position: 'absolute', inset: 0, opacity: 0.2 }}></div>
              {s.heroImage && <img src={s.heroImage} alt="hero" style={{ width: '100%', height: '100%', objectFit: 'cover', mixBlendMode: 'luminosity', opacity: 0.92 }} />}
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(0deg, var(--primary) 0%, transparent 50%)', mixBlendMode: 'multiply' }}></div>
              <div style={{ position: 'absolute', bottom: 24, left: 24, right: 24 }}>
                <div className="font-mono" style={{ fontSize: 10, color: 'var(--accent)', letterSpacing: '0.2em', marginBottom: 6 }}>FIG. 01</div>
                <div className="font-display" style={{ fontSize: 22, color: 'white', lineHeight: 0.9 }}>BUSTO<br/>CUSTOM</div>
              </div>
            </div>
            {badgeText && <div className="star-badge" style={{ top: -30, right: -30 }}>
              <span>{badgeText[0]}<br/><span style={{ fontSize: 24 }}>{badgeText[1]}</span></span>
            </div>}
            <div style={{ position: 'absolute', bottom: -30, left: -30, background: 'var(--ink)', color: 'var(--accent)', padding: '10px 18px', fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700, letterSpacing: '0.15em', transform: 'rotate(-2deg)', border: '2px solid var(--ink)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="sparkle" size={11} /> EDIÇÃO DE 1 <Icon name="sparkle" size={11} />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Categories() {
  const cats = window.Store.getCategories().filter((c) => c.featured);
  const n = cats.length || 1;
  // Longest single word (words separated by spaces can wrap — only the longest matters)
  const longestWord = Math.max(...cats.map(c =>
    Math.max(...c.label.split(' ').map(w => w.length))
  ));
  // Scale inversely with word length and column count so every card lands on the same size
  const labelFontSize = `clamp(12px, ${(63 / n / longestWord).toFixed(1)}vw, 48px)`;
  return (
    <section style={{ background: 'var(--ink)', color: 'var(--paper)', padding: 'var(--section-pad-y) 0' }}>
      <div className="container">
        <div className="section-tag reveal" style={{ color: 'var(--accent)' }}>02 / Categorias em destaque</div>
        <h2 className="h-section reveal" style={{ marginBottom: 48, color: 'var(--paper)' }}>ESCOLHA<br/>SEU <em>TIPO</em>.</h2>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.max(cats.length, 1)}, 1fr)`, gap: 24 }}>
          {cats.map((c, i) => (
            <a key={c.id} href="#catalog" className="lift reveal" style={{
              position: 'relative', minHeight: 360,
              border: `3px solid ${c.tone === 'accent' ? 'var(--accent)' : 'var(--paper)'}`,
              background: c.tone === 'primary' ? 'var(--primary)' : c.tone === 'accent' ? 'var(--accent)' : 'var(--secondary)',
              color: c.tone === 'accent' ? 'var(--primary)' : 'var(--paper)',
              padding: 24, display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
              transitionDelay: `${i * 80}ms`,
            }}>
              <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
                <div className="halftone" style={{ position: 'absolute', inset: 0, opacity: 0.15, color: c.tone === 'accent' ? 'var(--primary)' : 'var(--paper)' }}></div>
                {c.heroImg && <img src={c.heroImg} alt={c.label} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', mixBlendMode: 'multiply', opacity: 0.5 }} />}
              </div>
              <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between' }}>
                <span className="font-mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.15em' }}>0{i + 1}</span>
                <span className="font-mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em' }}>
                  {window.Store.getProducts().filter((p) => p.category === c.id).length} peças
                </span>
              </div>
              <div style={{ position: 'relative' }}>
                <div className="font-display" style={{ fontSize: labelFontSize, lineHeight: 1.1, hyphens: 'none' }}>{c.label}</div>
                <div className="font-mono" style={{ fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', marginTop: 8, opacity: 0.85 }}>{c.sub}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16, fontWeight: 700, fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                  Ver peças <Icon name="arrow-right" size={16} />
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

window.Header = Header;
window.Ticker = Ticker;
window.Hero = Hero;
window.Categories = Categories;
window.useReveal = useReveal;
window.useStoreData = useStoreData;
