// app.jsx — registration form, reveal observer, App + Tweaks wiring.

// ---- reveal-on-scroll ----
function useReveal(deps) {
  React.useEffect(() => {
    document.documentElement.classList.add('js');
    const all = () => document.querySelectorAll('.rv, .rv-st');
    const vh = window.innerHeight || 800;
    const showInView = () => all().forEach(el => {
      const r = el.getBoundingClientRect();
      if (r.top < vh * 0.92 && r.bottom > 0) el.classList.add('in');
    });
    requestAnimationFrame(showInView);

    let io = null;
    if (typeof IntersectionObserver !== 'undefined') {
      io = new IntersectionObserver(es => es.forEach(e => {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      }), { threshold: 0.08, rootMargin: '0px 0px -8% 0px' });
      all().forEach(el => { if (!el.classList.contains('in')) io.observe(el); });
    } else {
      all().forEach(el => el.classList.add('in'));
    }
    // safety: never leave content hidden
    const t1 = setTimeout(showInView, 400);
    const t2 = setTimeout(() => all().forEach(el => el.classList.add('in')), 2500);

    return () => { if (io) io.disconnect(); clearTimeout(t1); clearTimeout(t2); };
  }, deps || []);
}

// ---- REGISTRATION FORM ----
// Posts to HubSpot Forms API (region eu1) — keeps our own elegant UI.
const HS_PORTAL = '144878023';
const HS_FORM = '1ac61c8c-b9d9-476c-b582-687d31a14fec';

function Register() {
  const [form, setForm] = React.useState({ nome: '', email: '', org: '', ruolo: '' });
  const [consent, setConsent] = React.useState(false);
  const [errs, setErrs] = React.useState({});
  const [done, setDone] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [submitErr, setSubmitErr] = React.useState('');

  const set = (k) => (e) => {
    setForm(f => ({ ...f, [k]: e.target.value }));
    if (errs[k]) setErrs(er => ({ ...er, [k]: null }));
  };

  const validate = () => {
    const e = {};
    if (!form.nome.trim()) e.nome = 'Inserisci il tuo nome';
    if (!form.email.trim()) e.email = 'Inserisci l\u2019email';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Email non valida';
    else if (/(gmail|yahoo|hotmail|outlook|icloud|libero)\./i.test(form.email)) e.email = 'Usa un\u2019email aziendale';
    if (!form.org.trim()) e.org = 'Inserisci l\u2019organizzazione';
    if (!consent) e.consent = 'Devi acconsentire al trattamento dei dati per iscriverti';
    return e;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    setSubmitErr('');
    const e = validate();
    setErrs(e);
    if (Object.keys(e).length > 0) return;

    const parts = form.nome.trim().split(/\s+/);
    const firstname = parts.shift() || '';
    const lastname = parts.join(' ');
    const fields = [
      { name: 'email', value: form.email.trim() },
      { name: 'firstname', value: firstname },
      { name: 'lastname', value: lastname },
      { name: 'company', value: form.org.trim() },
      { name: 'jobtitle', value: form.ruolo },
    ].filter(f => f.value);
    const payload = {
      fields,
      legalConsentOptions: {
        consent: {
          consentToProcess: true,
          text: 'Acconsento al trattamento dei dati da parte di Nexalyse Ltd.',
        },
      },
      context: { pageUri: 'https://keynote.kpi6.com', pageName: 'Keynote GMR 18/06' },
    };
    // HubSpot Forms API — EU1 datacenter (this account is eu1). Public endpoint:
    // portalId + formId only, NO token in the browser. Submitting via the Forms
    // endpoint (not Contacts API) is what fires the HubSpot→Zoom workflow.
    const url = `https://api-eu1.hsforms.com/submissions/v3/integration/submit/${HS_PORTAL}/${HS_FORM}`;

    setBusy(true);
    try {
      const res = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        setBusy(false);
        setDone(true);          // confirmation ONLY on a real 200
        return;
      }
      const detail = await res.text().catch(() => '');
      console.error('HubSpot submit', res.status, detail);
      setBusy(false);
      // keep the user's data; show a readable error
      setSubmitErr('Iscrizione non riuscita, riprova. Se il problema persiste, scrivici.');
    } catch (err) {
      console.error('HubSpot submit error', err);
      setBusy(false);
      setSubmitErr('Iscrizione non riuscita, controlla la connessione e riprova.');
    }
  };

  if (done) {
    return (
      <div className="form-wrap" id="iscriviti">
        <div className="form-side">
          <span className="mlabel" data-num="✓">Iscrizione confermata</span>
          <div className="when">
            <span className="d">18 giugno 2026</span>
            <span className="h">ore 17:00 CEST &middot; online</span>
          </div>
          <div className="facts">
            <div className="fact"><span className="fi">&bull;</span><span>~45 min + Q&amp;A dal vivo, online</span></div>
            <div className="fact"><span className="fi">&bull;</span><span>Registrazione disponibile per tutti gli iscritti</span></div>
            <div className="fact"><span className="fi">&bull;</span><span>Lancio dei sei prodotti dal vivo, su un caso reale</span></div>
          </div>
        </div>
        <div className="form-main">
          <div className="confirm">
            <div className="check">&#10003;</div>
            <h3>Ci sei, {form.nome.split(' ')[0]}!</h3>
            <p>A breve ricevi via email a <strong style={{ color: 'var(--ink-2)' }}>{form.email}</strong> il link per partecipare al keynote. Ci vediamo il <strong style={{ color: 'var(--ink-2)' }}>18 giugno alle 17:00</strong>.</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="form-wrap" id="iscriviti">
      <div className="form-side">
        <span className="mlabel" data-num="↘">Riserva il tuo posto al keynote</span>
        <div className="when">
          <span className="d">18 giugno 2026</span>
          <span className="h">ore 17:00 CEST &middot; online</span>
        </div>
        <div className="facts">
          <div className="fact"><span className="fi">&bull;</span><span>~45 min + Q&amp;A dal vivo, online</span></div>
          <div className="fact"><span className="fi">&bull;</span><span>Accesso su iscrizione</span></div>
          <div className="fact"><span className="fi">&bull;</span><span>Non puoi esserci? La registrazione va a tutti gli iscritti</span></div>
        </div>
      </div>
      <div className="form-main">
        <h3>Riserva il tuo posto al keynote</h3>
        <form onSubmit={submit} noValidate>
          <div className={`field ${errs.nome ? 'err' : ''}`}>
            <label htmlFor="f-nome">Nome</label>
            <input id="f-nome" type="text" value={form.nome} onChange={set('nome')} placeholder="Nome e cognome"/>
            <span className="msg">{errs.nome}</span>
          </div>
          <div className={`field ${errs.email ? 'err' : ''}`}>
            <label htmlFor="f-email">Email aziendale</label>
            <input id="f-email" type="email" value={form.email} onChange={set('email')} placeholder="nome@agenzia.com"/>
            <span className="msg">{errs.email}</span>
          </div>
          <div className="form-row2">
            <div className={`field ${errs.org ? 'err' : ''}`}>
              <label htmlFor="f-org">Organizzazione</label>
              <input id="f-org" type="text" value={form.org} onChange={set('org')} placeholder="La tua agenzia"/>
              <span className="msg">{errs.org}</span>
            </div>
            <div className="field">
              <label htmlFor="f-ruolo">Ruolo</label>
              <select id="f-ruolo" value={form.ruolo} onChange={set('ruolo')}>
                <option value="">Seleziona&hellip;</option>
                <option>Founder / Owner</option>
                <option>Partner / Director</option>
                <option>Manager</option>
                <option>Consulente / Analyst</option>
                <option>Altro</option>
              </select>
              <span className="msg"></span>
            </div>
          </div>
          <label htmlFor="f-consent" style={{ display: 'flex', gap: 9, alignItems: 'flex-start', fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-3)', cursor: 'pointer', margin: '4px 0 2px' }}>
            <input id="f-consent" type="checkbox" checked={consent} onChange={(ev) => { setConsent(ev.target.checked); if (errs.consent) setErrs(er => ({ ...er, consent: null })); }} style={{ marginTop: 3, flex: '0 0 auto', width: 15, height: 15, accentColor: 'var(--acc)' }}/>
            <span>Acconsento al trattamento dei dati da parte di <strong style={{ color: 'var(--ink-2)' }}>Nexalyse Ltd</strong> per la gestione dell&rsquo;iscrizione e le comunicazioni relative al keynote.</span>
          </label>
          {errs.consent && <span className="msg" style={{ display: 'block', color: '#F87171', fontSize: 12, marginBottom: 4 }}>{errs.consent}</span>}
          <button type="submit" className="btn btn-primary form-submit" disabled={busy}>{busy ? 'Invio in corso…' : <>Confermo la partecipazione <span className="ar">&rarr;</span></>}</button>
          {submitErr && <p role="alert" style={{ color: '#F87171', marginTop: 10, fontSize: 13 }}>{submitErr}</p>}
          <p className="privacy">Dati trattati da <strong style={{ color: 'var(--ink-3)' }}>Nexalyse Ltd</strong> (part of KPI6) come titolare; i prodotti presentati sono marchi GMR. Niente spam. <a href="#">Privacy policy (GDPR)</a>.</p>
        </form>
      </div>
    </div>
  );
}

// ---- FINAL CTA + form ----
function Final() {
  return (
    <section className="sec final" id="cta">
      <div className="glow"/>
      <div className="wrap inner">
        <span className="mlabel rv" data-num="09">Il 18 giugno, dal vivo</span>
        <h2 className="disp h-l rv" style={{ textAlign: 'center', maxWidth: 1000 }}>
          Il tuo prossimo deliverable<br/><span className="acc">pu&ograve; essere diverso.</span>
        </h2>
        <p className="lead rv" style={{ textAlign: 'center', marginLeft: 'auto', marginRight: 'auto' }}>
          Iscriviti ora: se non puoi esserci dal vivo, ti mandiamo la registrazione.
        </p>
        <div className="rv" style={{ width: '100%', marginTop: 18 }}>
          <Register/>
        </div>
      </div>
    </section>
  );
}

// ---- TWEAK DEFAULTS ----
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroLayout": "type",
  "accent": "#34D399",
  "density": "regular"
}/*EDITMODE-END*/;

const ACCENTS = {
  '#34D399': 'rgba(52,211,153,', // emerald (group)
  '#3B82F6': 'rgba(59,130,246,', // blue
  '#8B5CF6': 'rgba(139,92,246,', // violet
  '#EC4899': 'rgba(236,72,153,', // pink
  '#F59E0B': 'rgba(245,158,11,', // amber
};
const DENSITY = { compact: '76px', regular: '104px', comfy: '132px' };

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  React.useEffect(() => {
    const root = document.documentElement.style;
    const base = ACCENTS[t.accent] || ACCENTS['#34D399'];
    root.setProperty('--acc', t.accent);
    root.setProperty('--acc-soft', base + '0.12)');
    root.setProperty('--acc-line', base + '0.40)');
    root.setProperty('--sec-pad', DENSITY[t.density] || DENSITY.regular);
  }, [t.accent, t.density]);

  useReveal([t.heroLayout]);

  return (
    <>
      <Header/>
      <main>
        <Hero variant={t.heroLayout}/>
        <Launch/>
        <Products/>
        <Problem/>
        <Solution/>
        <PerChi/>
        <Opportunity/>
        <Stage/>
        <Scaletta/>
        <Final/>
      </main>
      <Footer/>

      <TweaksPanel>
        <TweakSection label="Hero"/>
        <TweakRadio label="Layout hero" value={t.heroLayout}
          options={[{ value: 'type', label: 'Tipografico' }, { value: 'monograms', label: 'Prodotti' }, { value: 'team', label: 'Team' }]}
          onChange={(v) => setTweak('heroLayout', v)}/>
        <TweakSection label="Accento"/>
        <TweakColor label="Colore accento" value={t.accent}
          options={['#34D399', '#3B82F6', '#8B5CF6', '#EC4899', '#F59E0B']}
          onChange={(v) => setTweak('accent', v)}/>
        <TweakSection label="Layout"/>
        <TweakRadio label="Densità" value={t.density}
          options={['compact', 'regular', 'comfy']}
          onChange={(v) => setTweak('density', v)}/>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
