/* BAZ26 — Sections */

const { useState, useEffect, useRef } = React;

// Render any string with "BAZ26" replaced by the styled brand-mark
// (matches the navbar logo: Inter 800, "26" in teal, never italic).
function renderWithBrand(text) {
  if (!text || typeof text !== 'string') return text;
  const parts = text.split(/(BAZ26)/g);
  return parts.map((p, i) =>
    p === 'BAZ26'
      ? <span key={i} className="brand-mark">BAZ<span className="brand-mark__num">26</span></span>
      : p
  );
}

function NavBar({ lang, setLang, t, mode, setMode }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const time = useLiveTime();
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Close mobile menu on Escape — keyboard parity with the close button.
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMenuOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [menuOpen]);

  const links = [
    ['#about', t.nav.about],
    ['#nome', t.nav.nome],
    ['#services', t.nav.services],
    ['#approach', t.nav.approach],
    ['#contact', t.nav.contact],
  ];

  return (
    <>
      <header className={`site-header ${scrolled ? 'is-scrolled' : ''}`}>
        <nav className="nav" aria-label="Main navigation">
          <a href="#hero" className="brand magnetic" aria-label="BAZ26 — go to top">
            BAZ<span className="brand__num">26</span><span className="brand__caret" aria-hidden="true"></span>
          </a>
          <div className="nav__center">
            {links.map(([href, label]) => (
              <a key={href} href={href} className="nav__link">{label}</a>
            ))}
          </div>
          <div className="nav__right">
            <span className="live-chip" aria-hidden="true">
              <span className="live-dot"></span>
              <span>TURIN · {time}</span>
            </span>
            <div className="lang-toggle" role="group" aria-label="Language">
              <button
                type="button"
                className={lang === 'it' ? 'is-active' : ''}
                aria-pressed={lang === 'it'}
                onClick={() => setLang('it')}
              >IT</button>
              <button
                type="button"
                className={lang === 'en' ? 'is-active' : ''}
                aria-pressed={lang === 'en'}
                onClick={() => setLang('en')}
              >EN</button>
            </div>
            <button
              type="button"
              className={`saber-toggle ${mode === 'sith' ? 'is-sith' : 'is-jedi'}`}
              aria-label={mode === 'sith' ? 'Switch to light mode (Jedi)' : 'Switch to dark mode (Sith)'}
              aria-pressed={mode === 'sith'}
              title={mode === 'sith' ? 'Jedi mode (light)' : 'Sith mode (dark)'}
              onClick={() => setMode && setMode(mode === 'sith' ? 'jedi' : 'sith')}
            >
              <span className="saber-toggle__hilt" aria-hidden="true"></span>
              <span className="saber-toggle__blade" aria-hidden="true"></span>
              <span className="saber-toggle__glow" aria-hidden="true"></span>
            </button>
            <button
              type="button"
              className={`menu-btn ${menuOpen ? 'is-open' : ''}`}
              aria-label={menuOpen ? 'Close menu' : 'Open menu'}
              aria-expanded={menuOpen}
              aria-controls="mobile-menu"
              onClick={() => setMenuOpen(!menuOpen)}
            >
              <span aria-hidden="true"></span><span aria-hidden="true"></span><span aria-hidden="true"></span>
            </button>
          </div>
        </nav>
      </header>
      <div
        id="mobile-menu"
        className={`mobile-menu ${menuOpen ? 'is-open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-label="Site menu"
        aria-hidden={!menuOpen}
      >
        {links.map(([href, label]) => (
          <a
            key={href}
            href={href}
            tabIndex={menuOpen ? 0 : -1}
            onClick={() => setMenuOpen(false)}
          >{label}</a>
        ))}
      </div>
    </>
  );
}

// ===== HERO =====
function Hero({ t, variant }) {
  const titleRef = useRef(null);
  const sideRef = useRef(null);
  const [titleVisible, setTitleVisible] = useState(false);
  const [cycleIdx, setCycleIdx] = useState(0);

  useEffect(() => {
    const id = setTimeout(() => setTitleVisible(true), 200);
    return () => clearTimeout(id);
  }, []);

  // Rotate the placeholder word
  useEffect(() => {
    const id = setInterval(() => setCycleIdx((i) => (i + 1) % t.hero.cycle.length), 2400);
    return () => clearInterval(id);
  }, [t.hero.cycle.length]);

  const cta1Ref = useMagnetic(0.25);
  const cta2Ref = useMagnetic(0.25);

  // Card mouse-track gradient
  useEffect(() => {
    const el = sideRef.current?.querySelector('.hero__placeholder');
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      el.style.setProperty('--mx', `${e.clientX - r.left}px`);
      el.style.setProperty('--my', `${e.clientY - r.top}px`);
    };
    el.addEventListener('mousemove', onMove);
    return () => el.removeEventListener('mousemove', onMove);
  }, []);

  // Parallax on scroll
  useEffect(() => {
    const onScroll = () => {
      const y = Math.min(window.scrollY, 800);
      if (sideRef.current) sideRef.current.style.transform = `translateY(${y * -0.08}px)`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const cls = `lines hero__title ${titleVisible ? 'is-visible' : ''}`;

  return (
    <section className="hero" id="hero" data-variant={variant}>
      <div className="container hero__grid">
        <div>
          <div className="hero__pre">
            {t.hero.pre.map((p, i) => <span key={i} className="hero__pre-line">{p}</span>)}
          </div>

          {variant === 'cursor' && (
            <h1 ref={titleRef} className={cls}>
              <span className="line"><span>{t.hero.title_pre}<em>{t.hero.title_em1}</em></span></span>
              <span className="line"><span>{t.hero.title_mid}<em>{t.hero.title_em2}</em></span></span>
              <span className="line"><span>{t.hero.title_end}</span></span>
            </h1>
          )}

          {variant === 'scramble' && (
            <h1 className={cls}>
              <span className="line"><span>{t.hero.title_pre}<em>{t.hero.title_em1}</em>,</span></span>
              <span className="line"><span><CycleWord words={t.hero.cycle} idx={cycleIdx} />,</span></span>
              <span className="line"><span><em>{t.hero.title_em2}</em>.</span></span>
            </h1>
          )}

          {variant === 'split' && (
            <h1 className={cls}>
              <span className="line"><span>{t.hero.title_pre}<em>{t.hero.title_em1}</em></span></span>
              <span className="line"><span>{t.hero.title_mid}<em>{t.hero.title_em2}</em>.</span></span>
            </h1>
          )}

          <p className="hero__sub">{t.hero.sub}</p>

          <div className="hero__actions">
            <a ref={cta1Ref} href="#services" className="btn btn--primary magnetic">
              {t.hero.cta1}<span className="arrow">→</span>
            </a>
            <a ref={cta2Ref} href="#contact" className="btn btn--ghost magnetic">
              {t.hero.cta2}<span className="arrow">↗</span>
            </a>
          </div>
        </div>

        <div ref={sideRef} className="hero__side">
          {variant === 'cursor' && <PlaceholderCard t={t} cycleIdx={cycleIdx} />}
          {variant === 'scramble' && <PlaceholderCard t={t} cycleIdx={cycleIdx} variant="scramble" />}
          {variant === 'split' && (
            <div className="hero__split">
              <div className="hero__split-card hero__split-card--marco">
                <div className="role">Heritage / Brand</div>
                <h4>Marco</h4>
                <div>30 yrs · Advertising</div>
                <div style={{opacity: 0.6, marginTop: '0.5rem'}}>Hub09 · AICopy</div>
              </div>
              <div className="hero__split-card hero__split-card--daniele">
                <div className="role" style={{color: 'oklch(0.78 0.10 180)'}}>Future / AI</div>
                <h4>Daniele</h4>
                <div>AI · Innovation</div>
                <div style={{opacity: 0.55, marginTop: '0.5rem'}}>Systems · Strategy</div>
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="hero__scroll container">
        <div className="hero__scroll-line"></div>
        <span>{t.hero.scroll}</span>
      </div>
    </section>
  );
}

function CycleWord({ words, idx }) {
  const target = words[idx];
  const out = useScramble(target, true, { duration: 800 });
  return <em style={{display: 'inline-block', minWidth: '5ch'}}>{out}</em>;
}

function PlaceholderCard({ t, cycleIdx, variant }) {
  const word = t.hero.cycle[cycleIdx];
  return (
    <div className="hero__placeholder">
      <div className="hero__placeholder-bar">
        <span></span><span></span><span></span>
      </div>
      <pre>
        <span className="ph-comment">{`// baz26.config`}</span>{'\n'}
        <span className="ph-key">brand</span>: <span className="ph-teal">"baz_"</span>,{'\n'}
        <span className="ph-key">strategy</span>: <span className="ph-teal">"<CycleWord words={t.hero.cycle} idx={cycleIdx} />"</span>,{'\n'}
        <span className="ph-key">team</span>: <span className="ph-val">{`["marco", "daniele", ...]`}</span>,{'\n'}
        <span className="ph-key">output</span>: <span className="ph-teal">"autonomy"</span>,{'\n'}
        <span className="ph-key">status</span>: <span className="ph-val">running</span><span className="ph-cursor"></span>
      </pre>
    </div>
  );
}

// ===== Marquee =====
function Marquee({ items, dark }) {
  // Pause the CSS animation while the marquee is off-screen — saves ~60fps
  // worth of compositor work (and battery on mobile) when the user is reading
  // any other section. IO disconnects on unmount.
  const wrapRef = useRef(null);
  useEffect(() => {
    const el = wrapRef.current;
    if (!el || typeof IntersectionObserver === 'undefined') return;
    const io = new IntersectionObserver(
      ([entry]) => el.classList.toggle('is-paused', !entry.isIntersecting),
      { rootMargin: '120px 0px' }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const row = (
    <span>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i % 2 ? <em>{it}</em> : it}
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div ref={wrapRef} className={`marquee ${dark ? 'marquee--dark' : ''}`}>
      <div className="marquee__track">
        {row}{row}{row}{row}
      </div>
    </div>
  );
}

// ===== About =====
function About({ t }) {
  const [openIdx, setOpenIdx] = useState(0);
  const [introRef, introVisible] = useReveal();
  const [bodyRef, bodyVisible] = useReveal();

  return (
    <section className="section about" id="about">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num">{t.about.label}</span>
            <span className="eyebrow">A holding · Turin · 2026</span>
          </div>
          <h2 ref={introRef} className={`h-section lines ${introVisible ? 'is-visible' : ''}`}>
            <span className="line"><span>{t.about.title_a}</span></span>
            <span className="line"><span><em>{t.about.title_em}</em>{t.about.title_b}</span></span>
          </h2>
        </div>

        <div className="about__grid">
          <div ref={bodyRef} className={`reveal ${bodyVisible ? 'is-visible' : ''}`}>
            <p className="about__lead">{t.about.lead}</p>
            <div className="about__body">
              <p>{t.about.p1_a}<strong>{t.about.p1_b}</strong>{t.about.p1_c}</p>
              <p>{t.about.p2}</p>
            </div>
          </div>

          <ul className="values">
            {t.about.values.map((v, i) => (
              <li
                key={i}
                className={`value-row ${openIdx === i ? 'is-open' : ''}`}
                onClick={() => setOpenIdx(openIdx === i ? -1 : i)}
              >
                <span className="value-row__num mono">{v.num}</span>
                <h3 className="value-row__title">{v.title}</h3>
                <span className="value-row__expand">+</span>
                <p className="value-row__desc">{v.desc}</p>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ===== Founders =====
function Founders({ t }) {
  const [introRef, introVisible] = useReveal();
  const [marcoRef, marcoVisible] = useReveal();
  const [danRef, danVisible] = useReveal();
  const [creativeReveal, setCreativeReveal] = useState(false);
  const swapWatchRef = useRef(null);

  // Watch Marco's card with a fresh IO that re-fires on enter/leave so the
  // DIREZIONE → PASSIONE swap resets and re-runs each time the section is
  // back in view.
  useEffect(() => {
    const el = swapWatchRef.current;
    if (!el) return;
    let timer = null;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          if (timer) clearTimeout(timer);
          setCreativeReveal(false);
          timer = setTimeout(() => setCreativeReveal(true), 3500);
        } else {
          if (timer) clearTimeout(timer);
          timer = null;
          setCreativeReveal(false);
        }
      });
    }, { threshold: 0.35 });
    io.observe(el);
    return () => {
      io.disconnect();
      if (timer) clearTimeout(timer);
    };
  }, []);

  return (
    <section className="section founders" id="founders">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num" style={{color: 'rgba(255,255,255,0.5)'}}>{t.founders.label}</span>
            <span className="eyebrow">Marco × Daniele</span>
          </div>
          <h2 ref={introRef} className={`h-section lines ${introVisible ? 'is-visible' : ''}`}>
            <span className="line"><span>{t.founders.title_a}<em>{t.founders.title_em}</em>{t.founders.title_b}</span></span>
          </h2>
        </div>

        <p className="body-lg" style={{maxWidth: 720}}>{t.founders.lead}</p>

        <div className="founders__grid">
          <div ref={marcoRef} className={`founder-card reveal ${marcoVisible ? 'is-visible' : ''}`}>
            <div ref={swapWatchRef} className="founder-card__portrait">
              <span className="founder-card__noise-tag">{t.founders.marco.tag}</span>
              <span className="founder-card__monogram">M</span>
              <span className="founder-card__noise-tag founder-card__noise-tag--right" style={{top: 'auto', bottom: '1rem'}}>est. 1995</span>
            </div>
            <h3 className="founder-card__name">{t.founders.marco.name_a}<em>{t.founders.marco.name_em}</em></h3>
            {(() => {
              const isIT = /Direzione/i.test(t.founders.marco.role);
              const prefix = isIT ? "Co-fondatore · " : "Co-founder · Creative ";
              const fromW = isIT ? "Direzione" : "Direction";
              const toW = isIT ? "Passione" : "Passion";
              const suffix = isIT ? " Creativa" : "";
              return (
                <span className={`founder-card__role role-swap ${creativeReveal ? 'is-swapped' : ''}`}>
                  {prefix}
                  <span className="role-swap__words">
                    <span className="role-swap__from">{fromW}</span>
                    <span className="role-swap__to">{toW}</span>
                  </span>
                  {suffix}
                </span>
              );
            })()}
            <p className="founder-card__bio">{t.founders.marco.bio}</p>
          </div>

          <div ref={danRef} className={`founder-card reveal ${danVisible ? 'is-visible' : ''}`} style={{transitionDelay: '120ms'}}>
            <div className="founder-card__portrait">
              <span className="founder-card__noise-tag">{t.founders.daniele.tag}</span>
              <span className="founder-card__monogram">D</span>
              <span className="founder-card__noise-tag founder-card__noise-tag--right" style={{top: 'auto', bottom: '1rem'}}>est. 2026</span>
            </div>
            <h3 className="founder-card__name">{t.founders.daniele.name_a}<em>{t.founders.daniele.name_em}</em></h3>
            <span className="founder-card__role">{t.founders.daniele.role}</span>
            <p className="founder-card__bio">{t.founders.daniele.bio}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== Il Nome =====
function Nome({ t }) {
  const [heroRef, heroVisible] = useReveal({ threshold: 0.3 });
  const [bodyRef, bodyVisible] = useReveal();
  const tokenRef = useRef(null);

  // Cycle the demo rows
  const [stage, setStage] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setStage((s) => (s + 1) % 3), 4000);
    return () => clearInterval(id);
  }, []);

  // Scroll-linked highlight on the BAZ26 token: progress runs from 0 to 1 as
  // the token travels from 80% down the viewport up to 30% from the top.
  useEffect(() => {
    const el = tokenRef.current;
    if (!el) return;
    let ticking = false;
    const update = () => {
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight || 1;
      const start = vh * 0.8;
      const end = vh * 0.3;
      const center = rect.top + rect.height / 2;
      let p = (start - center) / (start - end);
      p = Math.max(0, Math.min(1, p));
      el.style.setProperty('--hl', p.toFixed(3));
      ticking = false;
    };
    const onScroll = () => {
      if (!ticking) {
        ticking = true;
        requestAnimationFrame(update);
      }
    };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <section className="section nome" id="nome">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num">{t.nome.label}</span>
            <span className="eyebrow">Metasyntactic origin</span>
          </div>
        </div>

        <h2 ref={heroRef} className={`nome__hero-line lines ${heroVisible ? 'is-visible' : ''}`}>
          <span className="line"><span>{t.nome.hero_a}<span ref={tokenRef} className="placeholder-token brand-mark">BAZ<span className="brand-mark__num">26</span></span>{t.nome.hero_b}</span></span>
        </h2>

        <div className="nome__layout">
          <div ref={bodyRef} className={`nome__text reveal ${bodyVisible ? 'is-visible' : ''}`}>
            <p>{t.nome.p1_a}<em style={{fontStyle: 'italic', color: 'var(--teal)'}}>{t.nome.p1_em}</em>{t.nome.p1_b}</p>
            <p>{t.nome.p2}</p>
            <p className="pull">{renderWithBrand(t.nome.pull)}</p>
            <p>{t.nome.p3}</p>
          </div>

          <div className="nome__demo">
            <div className="nome__demo-title">{t.nome.demo.title}</div>
            {t.nome.demo.rows.map((r, i) => (
              <div
                key={i}
                className="nome__demo-row"
                style={{
                  opacity: i === stage ? 1 : 0.35,
                  transition: 'opacity 0.6s ease-out',
                }}
              >
                <span className="nome__demo-stage">{r.stage}</span>
                <div>
                  <div className="nome__demo-text" dangerouslySetInnerHTML={{
                    __html: r.text.replace('baz_', '<em>baz<span style="display:inline-block;width:0.5em;height:1em;background:var(--teal);vertical-align:-0.15em;animation:caret 1.1s steps(2) infinite;"></span></em>')
                  }}></div>
                  {i === stage && <div className="nome__demo-progress"></div>}
                </div>
              </div>
            ))}
            <div className="nome__demo-replace">{t.nome.demo.replace}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== Services =====
function Services({ t }) {
  const [openIdxs, setOpenIdxs] = useState([]);
  const [introRef, introVisible] = useReveal();

  const toggle = (i) => {
    setOpenIdxs((prev) =>
      prev.includes(i) ? prev.filter((x) => x !== i) : [...prev, i]
    );
  };

  return (
    <section className="section services" id="services">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num">{t.services.label}</span>
            <span className="eyebrow">Three pillars · One vision</span>
          </div>
          <h2 ref={introRef} className={`h-section lines ${introVisible ? 'is-visible' : ''}`}>
            <span className="line"><span>{t.services.title_a}</span></span>
            <span className="line"><span><em>{t.services.title_em}</em>{t.services.title_b}</span></span>
          </h2>
        </div>

        <ul className="services__list">
          {t.services.list.map((s, i) => {
            const isOpen = openIdxs.includes(i);
            return (
            <li
              key={i}
              className={`service-row ${isOpen ? 'is-open' : ''}`}
              onClick={() => toggle(i)}
            >
              <span className="service-row__num">{s.num}</span>
              <h3 className="service-row__title">
                {s.title_a}<em>{s.title_em}</em>
              </h3>
              <span className="service-row__cta">
                <span>{isOpen ? 'close' : 'view'}</span>
                <span className="service-row__cta-arrow">→</span>
              </span>

              <div className="service-row__detail">
                <div className="service-row__detail-grid">
                  <p className="service-row__desc">{s.desc}</p>
                  <ul className="service-row__items">
                    {s.items.map((it, j) => <li key={j}>{it}</li>)}
                  </ul>
                </div>
              </div>
            </li>
            );
          })}
        </ul>
      </div>
    </section>
  );
}

// ===== Approach =====
function Approach({ t }) {
  const [introRef, introVisible] = useReveal();
  const [statsRef, statsVisible] = useReveal({ threshold: 0.4 });

  return (
    <section className="section approach" id="approach">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num" style={{color: 'rgba(255,255,255,0.5)'}}>{t.approach.label}</span>
            <span className="eyebrow">Step in · Define · Step out</span>
          </div>
          <h2 ref={introRef} className={`h-section lines ${introVisible ? 'is-visible' : ''}`}>
            <span className="line"><span>{t.approach.title_a}</span></span>
            <span className="line"><span><em>{t.approach.title_em}</em>{t.approach.title_b}</span></span>
          </h2>
        </div>

        <div className="approach__grid">
          <div className="approach__left">
            <p className="body-lg" style={{maxWidth: 380}}>{t.approach.lead}</p>
            <div ref={statsRef} className="stats">
              {t.approach.stats.map((s, i) => (
                <Stat key={i} target={s.num} suffix={s.suffix} label={s.label} trigger={statsVisible} />
              ))}
            </div>
          </div>

          <div className="steps">
            {t.approach.steps.map((s, i) => <Step key={i} step={s} idx={i} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

function Stat({ target, suffix, label, trigger }) {
  const val = useCounter(target, trigger);
  return (
    <div>
      <span className="stat__num">
        {val}<span className="stat__suffix">{suffix}</span>
      </span>
      <div className="stat__label">{label}</div>
    </div>
  );
}

function Step({ step, idx }) {
  const [ref, visible] = useReveal();
  return (
    <div ref={ref} className={`step reveal ${visible ? 'is-visible' : ''}`} style={{transitionDelay: `${idx * 100}ms`}}>
      <div className="step__num">0{idx + 1}</div>
      <div>
        <div className="step__verb">{step.verb}</div>
        <h3 className="step__title">
          {step.title_a}<em>{step.title_em}</em>{step.title_b}
        </h3>
        <p className="step__desc">{step.desc}</p>
      </div>
    </div>
  );
}

// ===== DotNav (sticky side dot navigation) =====
// Appears only while scrolling (or on hover) and fades out after a short
// idle period. Visually minimal: no pill background, just discreet dots.
function DotNav() {
  const sections = [
    { id: 'hero', label: 'Inizio' },
    { id: 'about', label: 'Chi Siamo' },
    { id: 'founders', label: 'Fondatori', dark: true },
    { id: 'nome', label: 'Il Nome' },
    { id: 'services', label: 'Servizi' },
    { id: 'approach', label: 'Metodo', dark: true },
    { id: 'ventures', label: 'Ventures' },
    { id: 'contact', label: 'Contatti' },
    { id: 'footer', label: 'Footer', dark: true, virtual: true },
  ];
  const DARK_IDS = new Set(sections.filter((s) => s.dark).map((s) => s.id));
  const visibleSections = sections.filter((s) => !s.virtual);

  const [active, setActive] = useState('hero');
  const [visible, setVisible] = useState(false);
  const [hovering, setHovering] = useState(false);
  // Per-dot dark flags, indexed against `visibleSections`.
  const [darkFlags, setDarkFlags] = useState(() => visibleSections.map(() => false));
  const idleTimer = useRef(null);
  const dotRefs = useRef([]);

  // Get the viewport-space rects of each dark section.
  const getDarkRects = () => {
    const rects = [];
    for (const id of DARK_IDS) {
      const el = document.getElementById(id);
      if (!el) continue;
      const r = el.getBoundingClientRect();
      rects.push({ top: r.top, bottom: r.bottom });
    }
    return rects;
  };

  const recomputeDark = () => {
    const darkRects = getDarkRects();
    const next = dotRefs.current.map((node) => {
      if (!node) return false;
      const r = node.getBoundingClientRect();
      const cy = r.top + r.height / 2;
      // Is the centre of this dash inside any dark section's vertical band?
      return darkRects.some((dr) => cy >= dr.top && cy <= dr.bottom);
    });
    setDarkFlags((prev) => {
      if (prev.length === next.length && prev.every((v, i) => v === next[i])) return prev;
      return next;
    });
  };

  useEffect(() => {
    let rafId = null;
    const tick = () => {
      // Update active section.
      const y = window.scrollY + window.innerHeight * 0.35;
      let current = visibleSections[0].id;
      for (const s of visibleSections) {
        const el = document.getElementById(s.id);
        if (el && el.offsetTop <= y) current = s.id;
      }
      setActive(current);
      recomputeDark();
      rafId = null;
    };
    const schedule = () => {
      if (rafId == null) rafId = requestAnimationFrame(tick);
    };
    const onScroll = () => {
      schedule();
      // Show on any scroll, hide after idle.
      setVisible(true);
      if (idleTimer.current) clearTimeout(idleTimer.current);
      idleTimer.current = setTimeout(() => setVisible(false), 1100);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', schedule);
    schedule();
    idleTimer.current = setTimeout(() => setVisible(false), 1100);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', schedule);
      if (rafId != null) cancelAnimationFrame(rafId);
      if (idleTimer.current) clearTimeout(idleTimer.current);
    };
  }, []);

  const shown = visible || hovering;

  return (
    <React.Fragment>
      {/* Invisible hot-zone along the right edge: hovering it summons the nav. */}
      <div
        className="dot-nav__hover-zone"
        aria-hidden="true"
        onMouseEnter={() => setHovering(true)}
        onMouseLeave={() => setHovering(false)}
      ></div>
      <nav
        className={`dot-nav ${shown ? 'is-shown' : ''}`}
        aria-label="Section navigation"
        onMouseEnter={() => setHovering(true)}
        onMouseLeave={() => setHovering(false)}
      >
        {visibleSections.map((s, i) => (
          <a
            key={s.id}
            href={`#${s.id}`}
            className={`dot-nav__item ${active === s.id ? 'is-active' : ''} ${darkFlags[i] ? 'is-on-dark' : ''}`}
            aria-label={s.label}
          >
            <span
              className="dot-nav__dot"
              ref={(el) => { dotRefs.current[i] = el; }}
            ></span>
            <span className="dot-nav__label">{s.label}</span>
          </a>
        ))}
      </nav>
    </React.Fragment>
  );
}

// ===== Ventures =====
function Ventures({ t }) {
  const [introRef, introVisible] = useReveal();
  // Real URLs for the operating ventures (others stay placeholder).
  const URLS = {
    "Bellairon": "https://www.bellaironllc.com",
    "Sukai": "https://sukai.it/",
    "La Mezza": "https://birralamezza.it/",
  };
  // Static screenshots used as hover previews (X-Frame-Options blocks live iframes).
  // WebP — q=80 @ 1600px wide, ~95%+ browser support (Safari 14+).
  const PREVIEWS = {
    "Bellairon": "assets/preview-bellairon.webp",
    "Sukai": "assets/preview-sukai.webp",
    "La Mezza": "assets/preview-lamezza.webp",
  };
  return (
    <section className="ventures" id="ventures">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num">{t.ventures.label}</span>
            <span className="eyebrow">Holding portfolio</span>
          </div>
          <h2 ref={introRef} className={`h-section lines ${introVisible ? 'is-visible' : ''}`} style={{fontSize: 'clamp(2.4rem, 5vw, 4rem)'}}>
            <span className="line"><span>{t.ventures.title_a}<em>{t.ventures.title_em}</em>{t.ventures.title_b}</span></span>
          </h2>
        </div>
        <p className="body-lg" style={{maxWidth: 540}}>{t.ventures.lead}</p>

        <div className="ventures__grid">
          {t.ventures.list.map((v, i) => {
            const isPlaceholder = v.year === "TBD";
            const key = (v.name_a || '').trim();
            const href = URLS[key];
            const preview = PREVIEWS[key];
            const isExternal = !!href;
            return (
            <a
              key={i}
              href={href || "#"}
              {...(isExternal ? { target: "_blank", rel: "noopener noreferrer" } : {})}
              className={`venture ${isPlaceholder ? 'venture--placeholder' : ''} ${isExternal ? 'venture--live' : ''}`}
              data-cursor
            >
              {/* Hover preview: live URL → blurred screenshot; placeholders → black wash */}
              <div className="venture__preview" aria-hidden="true">
                {preview ? (
                  <img
                    className="venture__preview-shot"
                    src={preview}
                    alt=""
                    loading="lazy"
                  />
                ) : null}
                <span className="venture__preview-veil"></span>
              </div>
              <div className="venture__year">
                {v.year}
                {isExternal && <span className="venture__ext"> ↗</span>}
              </div>
              <div>
                <h4 className="venture__name">{renderWithBrand(v.name_a)}<em>{v.name_em}</em></h4>
                <div className="venture__sector">{v.sector}</div>
              </div>
            </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ===== Contact =====
function Contact({ t }) {
  const [introRef, introVisible] = useReveal();
  const ctaRef = useMagnetic(0.2);
  const subject = encodeURIComponent(t.contact.cta_subject || 'BAZ26');
  const mailto = `mailto:${t.contact.email}?subject=${subject}`;

  return (
    <section className="section contact" id="contact">
      <div className="container">
        <div className="section-intro">
          <div className="section-intro__label">
            <span className="section-intro__num">{t.contact.label}</span>
            <span className="eyebrow">Let's talk</span>
          </div>
          <h2 ref={introRef} className={`h-section lines ${introVisible ? 'is-visible' : ''}`}>
            <span className="line"><span>{t.contact.title_a}<em>{t.contact.title_em}</em>{t.contact.title_b}</span></span>
          </h2>
        </div>

        <div className="contact__cta-wrap">
          <p className="body-lg contact__lead">{t.contact.lead}</p>
          <p className="contact__note">{t.contact.cta_note}</p>
          <a ref={ctaRef} href={mailto} className="btn btn--primary contact__cta">
            {t.contact.cta_label}
            <span className="contact__cta-email">{t.contact.email}</span>
            <span className="arrow">→</span>
          </a>
          <div className="contact__details">
            {t.contact.details.map((d, i) => (
              <div key={i} className="contact__detail">
                <h4>{d.h}</h4>
                <p>{d.p}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ===== Footer =====
function Footer({ t }) {
  return (
    <footer className="footer" id="footer">
      <div className="container">
        <div className="footer__big" aria-hidden="true">BAZ<em>26</em><span className="footer__big-cursor"></span></div>

        <div className="footer__layout">
          <div className="footer__col">
            <h5>BAZ26</h5>
            <p style={{color: 'var(--gray-300)', maxWidth: 280, fontSize: '0.95rem', lineHeight: 1.5}}>
              {t.footer.tag}
            </p>
            <p style={{color: 'var(--gray-400)', fontSize: '0.85rem', marginTop: '1rem'}}>
              Torino · Italia
            </p>
          </div>
          {t.footer.cols.map((c, i) => (
            <div key={i} className="footer__col">
              <h5>{c.h}</h5>
              {c.links.map((l, j) => (
                l.href
                  ? <a key={j} href={l.href}>{l.label}</a>
                  : <span key={j} className="footer__static">{l.label}</span>
              ))}
            </div>
          ))}
        </div>

        {t.footer.legal_line && (
          <p className="footer__legal-line">{t.footer.legal_line}</p>
        )}

        <div className="footer__bottom">
          <span>{t.footer.copy}</span>
          <div className="footer__bottom-links">
            {t.footer.legal.map((l, i) => (
              <a key={i} href={l.href}>{l.label}</a>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  NavBar, Hero, Marquee, About, Founders, Nome, Services, Approach, Ventures, Contact, Footer, DotNav,
});
