// page-shell.jsx — shared building blocks for sub-pages
// PageHero, ContentSection, CtaBand, DetailRow, StatRow, PageBoot

function PageHero({ eyebrow, title, sub, actions, children, back = true, big = true }) {
  return (
    <section className="page-hero">
      <ParallaxLayer speed={0.15} className="page-hero-mesh" aria-hidden />
      <ParticleField count={28} opacity={0.4}/>
      <div className="page-hero-grid" aria-hidden></div>
      <div className="container">
        {back && (
          <a href="index.html" className="ph-back">
            <Icon name="arrow" size={14}/> Home
          </a>
        )}
        {eyebrow && (
          <div className="ph-eyebrow mo-reveal is-in">
            <span style={{
              width: 22, height: 1,
              background: 'linear-gradient(to right, var(--accent), transparent)'
            }}></span>
            {eyebrow}
          </div>
        )}
        <h1 className="ph-title">
          <WordReveal step={70}>{title}</WordReveal>
        </h1>
        {sub && (
          <p className="ph-sub mo-reveal is-in" style={{ '--mo-delay': '400ms' }}>
            {sub}
          </p>
        )}
        {actions && (
          <div className="ph-actions mo-reveal is-in" style={{ '--mo-delay': '500ms' }}>
            {actions}
          </div>
        )}
        {children}
      </div>
    </section>
  );
}

function StatRow({ stats }) {
  return (
    <div className="stat-row">
      {stats.map((s, i) => (
        <div key={i} className={'stat-cell mo-reveal ' + (s.accent ? 'stat-cell-accent' : '')}
             style={{ '--mo-delay': `${i * 80}ms` }}>
          <b>
            {typeof s.value === 'number'
              ? <Counter value={s.value} prefix={s.prefix || ''} suffix={s.suffix || ''} decimals={s.decimals || 0}/>
              : s.value}
          </b>
          <span>{s.label}</span>
        </div>
      ))}
    </div>
  );
}

function ContentSection({ children, alt = false, elev = false, id }) {
  const cls = 'section ' + (alt ? 'section-alt ' : '') + (elev ? 'section-elev ' : '');
  return (
    <section className={cls} id={id}>
      <div className="container">{children}</div>
    </section>
  );
}

function CtaBand({
  title = "Hai un'idea? Costruiamola insieme.",
  sub   = 'Quindici minuti, ti diciamo se possiamo aiutarti.',
  primary   = ['Prenota una demo', 'contatti.html'],
  secondary = ['Scrivici', 'mailto:hello@metawebstudio.it'],
}) {
  return (
    <section className="section">
      <div className="container">
        <div className="cta-band mo-reveal">
          <h2 className="cta-band-title">{title}</h2>
          <p className="cta-band-sub">{sub}</p>
          <div className="cta-band-actions">
            <a className="btn btn-grad btn-lg" href={primary[1]}>
              {primary[0]} <Icon name="arrow" size={16}/>
            </a>
            <a className="btn btn-outline btn-lg" href={secondary[1]}>
              <Icon name="mail" size={16}/> {secondary[0]}
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

function DetailRow({ eyebrow, title, body, bullets, visual, reverse = false }) {
  return (
    <div className={'detail-row ' + (reverse ? 'reverse' : '')}>
      <div className="detail-left mo-reveal">
        <div className="detail-eyebrow">{eyebrow}</div>
        <h3 className="detail-h">{title}</h3>
        {Array.isArray(body)
          ? body.map((b, i) => <p key={i} className="detail-p">{b}</p>)
          : <p className="detail-p">{body}</p>}
        {bullets && (
          <ul className="detail-bullets">
            {bullets.map((b, i) => <li key={i}>{b}</li>)}
          </ul>
        )}
      </div>
      <div className="detail-right mo-reveal" style={{ '--mo-delay': '120ms' }}>
        {visual}
      </div>
    </div>
  );
}

// ── PageBoot ───────────────────────────────────────────────────────────────
// Wraps any subpage with Navbar + Footer + Tweaks + theme management +
// custom cursor. Mirrors the wiring in index.html so every subpage feels the
// same.
function PageBoot({ children, defaults = { palette: 'signature', mode: 'dark' } }) {
  const [t, setTweak] = useTweaks(defaults);

  React.useEffect(() => { applyTheme(t.palette, t.mode); }, [t.palette, t.mode]);
  useGlobalReveal();

  // Sync external data-theme changes (ThemeToggle) back to the tweak state.
  React.useEffect(() => {
    const obs = new MutationObserver(() => {
      const cur = getCurrentMode();
      if (cur !== t.mode) setTweak('mode', cur);
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
    return () => obs.disconnect();
  }, [t.mode]);

  const paletteOptions = Object.keys(PALETTES).map(k => ({ value: k, label: PALETTES[k].name }));
  const paletteSwatches = Object.keys(PALETTES).map(k => {
    const p = PALETTES[k]; return [p.accent, p.accent2];
  });
  const paletteKeys = Object.keys(PALETTES);

  return (
    <>
      <CursorFollower/>
      <Navbar palette={t.palette} onDemoClick={() => { window.location.href = 'contatti.html'; }}/>
      <main>{children}</main>
      <Footer/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Tema"/>
        <TweakRadio
          label="Modalità"
          value={t.mode}
          options={['dark', 'light']}
          onChange={(v) => setTweak('mode', v)}
        />
        <TweakSection label="Palette colori"/>
        <TweakColor
          label="Variante"
          value={paletteSwatches[paletteKeys.indexOf(t.palette)]}
          options={paletteSwatches}
          onChange={(arr) => {
            const i = paletteSwatches.findIndex(s => JSON.stringify(s).toLowerCase() === JSON.stringify(arr).toLowerCase());
            if (i >= 0) setTweak('palette', paletteKeys[i]);
          }}
        />
        <TweakSelect
          label="Nome variante"
          value={t.palette}
          options={paletteOptions}
          onChange={(v) => setTweak('palette', v)}
        />
      </TweaksPanel>
      <CookieBanner/>
    </>
  );
}

Object.assign(window, {
  PageHero, StatRow, ContentSection, CtaBand, DetailRow, PageBoot,
});
