// FRZN — sections (i18n aware)
const { useState, useEffect, useRef } = React;

// Scroll reveal hook
const useReveal = (stagger = false) => {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { el.classList.add('in'); io.unobserve(el); }
    }, { threshold: 0.15 });
    el.classList.add(stagger ? 'reveal-stagger' : 'reveal');
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
};

const Reveal = ({ children, stagger, as: As = 'div', ...rest }) => {
  const ref = useReveal(stagger);
  return <As ref={ref} {...rest}>{children}</As>;
};

// render array headline with italic accent words
const renderTitle = (arr, accentIdx = [1]) => arr.map((w, i) =>
  accentIdx.includes(i)
    ? <em key={i}>{w}{' '}</em>
    : <span key={i}>{w}{' '}</span>
);

// ------------ HERO ------------
const Hero = ({ t, copyKey, onWaitlist }) => {
  const [waterTemp, setWaterTemp] = useState(4);
  useEffect(() => {
    const id = setInterval(() => {
      setWaterTemp(x => Math.max(1.5, Math.min(6.5, x + (Math.random() - 0.5) * 0.4)));
    }, 1600);
    return () => clearInterval(id);
  }, []);
  const h = t.hero.headline[copyKey];
  const eyebrow = t.hero.eyebrow[copyKey];
  const sub = t.hero.sub[copyKey];
  const markerPos = `${Math.min(100, Math.max(0, (waterTemp / 30) * 100))}%`;
  const accentIdx = copyKey === 'thermal' ? 1 : copyKey === 'vitality' ? 5 : 1;

  return (
    <section className="hero" id="top" data-screen-label="01 Hero">
      <div className="hero-meta">
        <div><span className="label">{t.hero.metaSpec}</span><span className="value">{t.hero.metaSpecV}</span></div>
        <div><span className="label">{t.hero.metaCond}</span><span className="value">{t.hero.metaCondV}</span></div>
        <div><span className="label">{t.hero.metaTarget}</span><span className="value">{t.hero.metaTargetV}</span></div>
        <div><span className="label">{t.hero.metaRelease}</span><span className="value">{t.hero.metaReleaseV}</span></div>
      </div>

      <div className="hero-body">
        <div className="hero-left">
          <Reveal>
            <div className="mono" style={{ color: 'var(--ink-3)', marginBottom: 24 }}>{eyebrow}</div>
            <h1 className="hero-headline">
              {h.map((w, i) => {
                if (i === accentIdx) return <span key={i} className="accent">{w} </span>;
                if (i === 4 && copyKey === 'thermal') return <em key={i}>{w} </em>;
                return <span key={i}>{w} </span>;
              })}
            </h1>
            <p className="hero-sub">{sub}</p>
            <div className="hero-cta-row">
              <button className="btn btn-primary" onClick={onWaitlist}><span>{t.hero.reserve}</span><span>→</span></button>
              <button className="btn btn-ghost" onClick={() => document.getElementById('products')?.scrollIntoView({ behavior: 'smooth' })}><span>{t.hero.see}</span></button>
            </div>
          </Reveal>

          <Reveal stagger as="div" className="hero-bottom">
            <div className="hero-bottom-col">
              <div className="mono" style={{ color: 'var(--ink-3)', marginBottom: 8 }}>{t.hero.prop1Title}</div>
              <p>{t.hero.prop1}</p>
            </div>
            <div className="hero-bottom-col">
              <div className="mono" style={{ color: 'var(--ink-3)', marginBottom: 8 }}>{t.hero.prop2Title}</div>
              <p>{t.hero.prop2}</p>
            </div>
          </Reveal>
        </div>

        <div className="hero-right">
          <div className="thermal-stage">
            <div className="thermal-card-meta">
              <div className="crosshair tl" /><div className="crosshair tr" />
              <div className="crosshair bl" /><div className="crosshair br" />
              <div><div>FR-001 / SHORTS</div><div style={{ marginTop: 4, color: 'rgba(255,255,255,0.4)' }}>THERMAL CAPTURE · 3.2 μm</div></div>
              <div style={{ textAlign: 'right' }}><div>REV 04</div><div style={{ marginTop: 4, color: 'rgba(255,255,255,0.4)' }}>{waterTemp.toFixed(1)}°C AMB</div></div>
            </div>
            <div className="thermal-svg-wrap"><ShortsThermal /></div>
          </div>
          <div className="thermal-gauge">
            <div className="thermal-gauge-row"><span>{t.liveLabel} · THERMAL READ</span><strong>{waterTemp.toFixed(1)}°C · CLASS III</strong></div>
            <div className="thermal-spectrum"><div className="thermal-marker" style={{ left: markerPos }} /></div>
            <div className="thermal-gauge-row" style={{ fontSize: 9 }}><span>0°C</span><span>10°C</span><span>20°C</span><span>30°C</span></div>
          </div>
        </div>
      </div>

      <div className="marquee" aria-hidden="true">
        <div className="marquee-track">
          {Array.from({ length: 2 }).map((_, r) => (
            <React.Fragment key={r}>{t.marquee.map((m, i) => <span key={i}>{m}</span>)}</React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
};

// ------------ SECTION HEAD ------------
const SectionHead = ({ num, label, title, accentIdx = [1] }) => (
  <Reveal className="section-head">
    <div className="label"><span className="num">§ {num}</span><span>{label}</span></div>
    <h2>{renderTitle(title, accentIdx)}</h2>
  </Reveal>
);

// ------------ SCIENCE ------------
const Science = ({ t }) => (
  <section className="section" id="science" data-screen-label="02 Science">
    <div className="container">
      <SectionHead num="01" label={t.sectionLabels.physio} title={t.science.title} accentIdx={[1]} />
    </div>
    <div className="container">
      <Reveal stagger as="div" className="science-grid">
        {t.science.cards.map((c, i) => (
          <div key={i} className="science-cell">
            <div>
              <div className="stat"><span className="sign">{c.stat[0]}</span>{c.stat.slice(1)}</div>
              <div className="mono" style={{ color: 'var(--ink-2)', marginTop: 12 }}>{c.title}</div>
            </div>
            <div>
              <p className="copy">{c.copy}</p>
              <div className="cite">{c.cite}</div>
            </div>
          </div>
        ))}
      </Reveal>
    </div>
  </section>
);

// ------------ MECHANISM ------------
const Mechanism = ({ t }) => {
  const [active, setActive] = useState(3);
  return (
    <section className="mechanism" id="how" data-screen-label="03 Mechanism">
      <div className="container">
        <SectionHead num="02" label={t.sectionLabels.mech} title={t.mech.title} accentIdx={[1]} />
      </div>
      <div className="container">
        <Reveal className="mech-stage">
          <div className="mech-visual"><div className="mech-visual-grid" /><MechanismDiagram /></div>
          <div className="mech-layers">
            {t.mech.layers.map((l, i) => (
              <div key={i} className={`mech-layer ${active === i ? 'active' : ''}`} onMouseEnter={() => setActive(i)}>
                <span className="num">{l[0]}</span>
                <div><div className="name">{l[1]}</div><div className="desc">{l[2]}</div></div>
                <span className="num">→</span>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
};

// ------------ PRODUCT CARD ------------
const ProductCard = ({ product, onAdd, lang, t }) => {
  const [size, setSize] = useState(product.sizes.find(s => !product.unavailable.includes(s)));
  const [added, setAdded] = useState(false);
  const Thermal = window[product.visual];
  const handleAdd = () => {
    onAdd({ ...product, size });
    setAdded(true); setTimeout(() => setAdded(false), 1200);
  };
  const title = product.name;
  const tagline = product.tagline[lang] || product.tagline.en;
  const desc = product.desc[lang] || product.desc.en;

  return (
    <div className={`product-card ${product.featured ? 'featured' : ''}`}>
      <div className="product-visual">
        <div className="crosshair tl" /><div className="crosshair tr" />
        <div className="crosshair bl" /><div className="crosshair br" />
        <div className="product-spec-badge">{product.id} · REV 04</div>
        <Thermal />
        <div className="product-thermal-pill"><span className="dot" />{product.thermal} · {product.gsm}</div>
      </div>
      <div className="product-info">
        <div className="id-row"><span>{tagline}</span><span>{product.lat}</span></div>
        <h3>{title}</h3>
        <p className="desc">{desc}</p>
        <div className="size-picker">
          {product.sizes.map(s => (
            <button key={s}
              className={`size-btn ${size === s ? 'active' : ''}`}
              onClick={() => setSize(s)}
              disabled={product.unavailable.includes(s)}>{s}</button>
          ))}
        </div>
        <div className="price-row">
          <div className="price">{product.was && <span className="was">€{product.was}</span>}€{product.price}</div>
          <span className="mono" style={{ color: 'var(--ink-3)' }}>{t.products.stock}</span>
        </div>
        <button className={`add-btn ${added ? 'added' : ''}`} onClick={handleAdd}>
          <span>{added ? t.products.added : t.products.add}</span>
          <span>{added ? '' : '+'}</span>
        </button>
      </div>
    </div>
  );
};

// ------------ PRODUCTS ------------
const Products = ({ t, lang, onAdd }) => {
  const top3 = CATALOG.slice(0, 3);
  return (
    <section className="section" id="products" data-screen-label="04 Products">
      <div className="container">
        <SectionHead num="03" label={t.sectionLabels.system} title={t.products.title} accentIdx={[1]} />
      </div>
      <div className="container">
        <Reveal stagger as="div" className="product-grid">
          {top3.map(p => <ProductCard key={p.id} product={p} onAdd={onAdd} lang={lang} t={t} />)}
        </Reveal>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 0, marginTop: -1, border: '1px solid var(--line)', background: 'var(--line)' }}>
          <ProductCard product={CATALOG[3]} onAdd={onAdd} lang={lang} t={t} />
          <div style={{ background: 'var(--bg)', padding: 32, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div className="mono" style={{ color: 'var(--ink-3)', marginBottom: 12 }}>{t.products.refillTitle}</div>
            <p style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 22, lineHeight: 1.3 }}>{t.products.refill}</p>
          </div>
          <div style={{ background: 'var(--bg)', padding: 32, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start' }}>
            <div className="mono" style={{ color: 'var(--ink-3)', marginBottom: 12 }}>{t.products.provTitle}</div>
            <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 16 }}>{t.products.prov}</p>
            <a href="./shop.html" className="mono" style={{ color: 'var(--accent)' }}>{t.products.supplyMap}</a>
          </div>
        </div>
      </div>
    </section>
  );
};

// ------------ RITUAL ------------
const Ritual = ({ t }) => (
  <section className="section" id="ritual" data-screen-label="05 Ritual" style={{ background: 'var(--bg-2)' }}>
    <div className="container">
      <SectionHead num="04" label={t.sectionLabels.ritual} title={t.ritual.title} accentIdx={[1]} />
    </div>
    <div className="container">
      <Reveal stagger as="div" className="ritual">
        {t.ritual.phases.map((p, i) => (
          <div key={i} className="ritual-step">
            <div className="phase">{t.ritual.phase} {p[0]}</div>
            <div>
              <div className="temp">{p[2]}<span className="unit">C</span></div>
              <div className="name" style={{ marginTop: 8 }}>{p[1]}</div>
            </div>
            <div className="duration">{p[4]}</div>
            <p className="desc">{p[3]}</p>
          </div>
        ))}
      </Reveal>
    </div>
  </section>
);

// ------------ AMBASSADORS ------------
const Ambassadors = ({ t }) => (
  <section className="section" id="field" data-screen-label="06 Field">
    <div className="container">
      <SectionHead num="05" label={t.sectionLabels.field} title={t.field.title} accentIdx={[1]} />
    </div>
    <div className="container">
      <Reveal stagger as="div" className="quotes">
        {t.field.quotes.map((q, i) => (
          <div key={i} className="quote">
            <p className="text">{q[0]}</p>
            <div className="attr"><span className="name">{q[1]}</span><span className="role">{q[2]}</span></div>
          </div>
        ))}
      </Reveal>
      <Reveal className="press-strip" style={{ marginTop: 64 }}>
        {['Men\u2019s Health','GQ','Monocle','WIRED','Kinfolk','Hypebeast'].map(n => (<span key={n} className="press-logo">{n}</span>))}
      </Reveal>
    </div>
  </section>
);

// ------------ GUARANTEE ------------
const Guarantee = ({ t }) => (
  <section className="section" id="guarantee" data-screen-label="07 Guarantee" style={{ paddingTop: 0 }}>
    <div className="container">
      <Reveal className="section-head">
        <div className="label"><span className="num">§ 06</span><span>{t.guarantee.title.toUpperCase()}</span></div>
        <h2>{t.guarantee.title}</h2>
      </Reveal>
      <Reveal stagger as="div" className="guarantee">
        {t.guarantee.items.map((g, i) => (
          <div key={i} className="guarantee-cell">
            <div className="icon">{['60','∞','↻','−CO₂'][i]}</div>
            <div>
              <div className="head" style={{ marginBottom: 8 }}>{g[0]}</div>
              <p>{g[1]}</p>
            </div>
          </div>
        ))}
      </Reveal>
    </div>
  </section>
);

// ------------ SPECS ------------
const Specs = ({ t }) => (
  <section className="section" id="specs" data-screen-label="08 Specs" style={{ background: 'var(--bg-2)' }}>
    <div className="container">
      <SectionHead num="07" label={t.sectionLabels.materials} title={t.specs.title} accentIdx={[1]} />
    </div>
    <div className="container">
      <Reveal className="specs-table">
        {t.specs.rows.map((r, i) => (
          <div key={i} className="specs-row">
            <div className="label">{r[0]}</div>
            <div className="value">{r[1]}</div>
            <div className="value"><span className="sub">{r[2]}</span></div>
            <div className="value"><span className="sub">{r[3]}</span></div>
          </div>
        ))}
      </Reveal>
    </div>
  </section>
);

// ------------ FAQ ------------
const FAQ = ({ t }) => {
  const [open, setOpen] = useState(0);
  return (
    <section className="section" id="faq" data-screen-label="09 FAQ">
      <div className="container">
        <SectionHead num="08" label={t.sectionLabels.queries} title={t.faq.title} accentIdx={[1]} />
      </div>
      <div className="container">
        <div className="faq-list">
          {t.faq.items.map((it, i) => (
            <div key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="idx">0{i + 1}</span>
                <span>{it[0]}</span>
                <span className="plus">+</span>
              </button>
              <div className="faq-a">{it[1]}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ------------ WAITLIST ------------
const Waitlist = ({ t, onSubmit }) => {
  const [email, setEmail] = useState('');
  return (
    <section className="section" id="waitlist" data-screen-label="10 Waitlist">
      <Reveal className="waitlist-block">
        <div>
          <h2>{renderTitle(t.waitlist.title, [1])}</h2>
          <p>{t.waitlist.sub}</p>
        </div>
        <div>
          <form className="waitlist-form" onSubmit={(e) => { e.preventDefault(); onSubmit(email); setEmail(''); }}>
            <input type="email" required placeholder={t.waitlist.placeholder} value={email} onChange={e => setEmail(e.target.value)} />
            <button type="submit">{t.waitlist.submit}</button>
          </form>
          <div className="waitlist-meta"><span>{t.waitlist.reserved}</span><span>{t.waitlist.left}</span></div>
        </div>
      </Reveal>
    </section>
  );
};

// ------------ FOOTER ------------
const Footer = ({ t }) => (
  <footer className="footer">
    <div className="footer-top">
      <div>
        <p className="footer-copy">{t.footer.copy[0]} <em>{t.footer.copy[1]}</em> {t.footer.copy[2]}</p>
      </div>
      <div className="footer-col"><h4>{t.footer.shop}</h4>{t.footer.links.shop.map(l => <a key={l} href="./shop.html">{l}</a>)}</div>
      <div className="footer-col"><h4>{t.footer.read}</h4>{t.footer.links.read.map(l => <a key={l}>{l}</a>)}</div>
      <div className="footer-col"><h4>{t.footer.about}</h4>{t.footer.links.about.map(l => <a key={l}>{l}</a>)}</div>
    </div>
    <div className="footer-wordmark" aria-hidden="true">FRZN</div>
    <div className="footer-bottom">
      <span>{t.footer.legal}</span>
      <span>{t.footer.location}</span>
      <span>{t.footer.policies}</span>
    </div>
  </footer>
);

Object.assign(window, { Hero, Science, Mechanism, Products, Ritual, Ambassadors, Guarantee, Specs, FAQ, Waitlist, Footer, ProductCard, useReveal, Reveal, renderTitle, SectionHead });
