// typeform.jsx
// Martes AI — pre-training Typeform-style flow.
// All sections + questions live here. Mounted by Martes Typeform.html.

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ─────────────────────────────────────────────────────────────────────────────
// FLOW — declarative list of every screen in order.
// kind: 'info' | 'single' | 'multi' | 'text' | 'thanks'
// ─────────────────────────────────────────────────────────────────────────────

const FLOW = [
  // ── SECTION 1 — Percorso formativo ──
  {
    id: 'cover',
    kind: 'info',
    section: 'Benvenuto',
    sectionIndex: 0,
    eyebrow: 'Ciao 👋',
    title: 'In vista della formazione AI fra qualche giorno…',
    body:
      "…ti chiediamo qualche minuto per raccontarci come lavori oggi.\nServe a costruire una giornata cucita su di te — niente risposte sbagliate, più sei onesto più sarà utile.",
    cta: 'Iniziamo',
  },
  {
    id: 'day1',
    kind: 'info',
    section: 'Percorso formativo',
    sectionIndex: 1,
    eyebrow: 'Giornata 01 · 5–6 ore · tutto il team',
    title: 'Fondamenta AI',
    body: "La prima giornata è dedicata a costruire le basi: cosa sa fare l'AI oggi, come parlarci, e quali strumenti useremo nel quotidiano.",
    bullets: [
      { n: '01', text: "Cos'è una Claude Skill: come si costruisce, quando usarla, fondamenti di automazioni e agents" },
      { n: '02', text: "Cos'è un MCP: il protocollo che collega Claude ai vostri sistemi" },
      { n: '03', text: "Cos'è un'API: il linguaggio con cui i software parlano tra loro" },
      { n: '04', text: 'Knowledge base, prompt engineering e context engineering applicati al mondo mediazione' },
      { n: '05', text: "Demo dei tool scelti in base ai risultati dell'AI assessment (Perplexity, Claude Cowork, Gamma…)" },
    ],
  },
  // ── SECTION 2 — Day 2 + Company Brain (merged) ──
  {
    id: 'brain',
    kind: 'brain',
    section: 'Giornata 02',
    sectionIndex: 2,
    eyebrow: 'Giornata 02 · solo AI Champions',
    title: 'Costruiamo il Company Brain',
    intro:
      "La seconda giornata è riservata agli AI Champions — il sotto-team con livello più avanzato. Insieme costruiamo, con Claude Code, il cervello operativo dell'azienda: un sistema AI che gestisce il 60–70% del lavoro ripetitivo, su 5 layer.",
    layers: [
      { n: '01', name: 'Contesto', desc: 'impara chi sei, cosa vendi, strategia, clienti' },
      { n: '02', name: 'Dati', desc: 'si collega a fatturato, CRM, metriche, fogli di calcolo' },
      { n: '03', name: 'Radar', desc: 'cattura meeting, conversazioni, decisioni — niente si perde' },
      { n: '04', name: 'Automazione', desc: 'email, follow-up, report, preventivi automatici' },
      { n: '05', name: 'Crescita', desc: 'dashboard personalizzata, workstation per nuovi progetti' },
    ],
    outro:
      'Non un chatbot generico — un assistente che conosce il tuo business e lavora per te su task operativi.',
  },
  {
    id: 'assess_intro',
    kind: 'info',
    section: 'AI Readiness Assessment',
    sectionIndex: 3,
    eyebrow: 'Adesso parliamo di te',
    title: 'Sei pronto?',
    body:
      "15 domande veloci sul tuo modo di lavorare oggi. Tre minuti, prometto — poi possiamo modellare la formazione su di te.",
    cta: 'Sono pronto',
  },
  // ── SECTION 3 — AI Readiness Assessment ──
  {
    id: 'q1',
    kind: 'single',
    section: 'Sentiment',
    sectionIndex: 3,
    qNum: 1,
    title: "Come descriveresti il tuo approccio all'AI oggi?",
    options: ['Curioso', 'Scettico', 'Entusiasta', 'Preoccupato'],
  },
  {
    id: 'q2',
    kind: 'single',
    section: 'Sentiment',
    sectionIndex: 3,
    qNum: 2,
    title: "Qual è la tua preoccupazione principale riguardo l'AI?",
    options: ['Mi sostituirà', 'Non capisco come usarla', 'Privacy dei dati', 'Nessuna'],
  },
  {
    id: 'q3',
    kind: 'single',
    section: 'Sentiment',
    sectionIndex: 3,
    qNum: 3,
    title: "Qual è il principale blocco che ti impedisce di usare l'AI nel lavoro?",
    options: [
      'Non so da dove iniziare',
      'Non mi fido dei risultati',
      'Non ho tempo per imparare',
      'Non vedo applicazioni nel mio ruolo',
      'Già la uso senza blocchi',
    ],
  },
  {
    id: 'q4',
    kind: 'single',
    section: 'Livello tecnico',
    sectionIndex: 3,
    qNum: 4,
    title: 'Hai mai usato strumenti AI?',
    options: ['Mai', 'Ho provato ChatGPT', 'Uso AI regolarmente', 'Uso AI per lavoro ogni giorno'],
  },
  {
    id: 'q5',
    kind: 'multi',
    section: 'Livello tecnico',
    sectionIndex: 3,
    qNum: 5,
    title: 'Con quale di questi hai familiarità?',
    hint: 'Scegli tutti quelli che si applicano',
    options: ['ChatGPT', 'Copilot', 'Claude', 'Claude Code', 'Gemini', 'Perplexity', 'Cowork', 'Nessuno'],
  },
  {
    id: 'q6',
    kind: 'multi',
    section: 'Tool & workflow',
    sectionIndex: 3,
    qNum: 6,
    title: 'Quali strumenti usi di più nel tuo lavoro quotidiano?',
    hint: 'Scegli tutti quelli che si applicano',
    options: ['Gmail', 'Outlook', 'Excel', 'Google Sheets', 'Word', 'Google Docs', 'Slack', 'Teams', 'CRM', 'Altro'],
  },
  {
    id: 'q7',
    kind: 'single',
    section: 'Tool & workflow',
    sectionIndex: 3,
    qNum: 7,
    title: 'Quanto tempo dedichi a email e comunicazione scritta al giorno?',
    options: ['Meno di 1h', '1–2h', '2–4h', 'Più di 4h'],
  },
  {
    id: 'q8',
    kind: 'text',
    section: 'Attività ripetitive',
    sectionIndex: 3,
    qNum: 8,
    title: "Descrivi un'attività che fai ogni settimana e che trovi ripetitiva o a basso valore",
    placeholder: 'Es. compilo report di fine settimana copiando dati da 3 sistemi diversi…',
  },
  {
    id: 'q9',
    kind: 'single',
    section: 'Attività ripetitive',
    sectionIndex: 3,
    qNum: 9,
    title: 'Quanto tempo ci dedichi a settimana?',
    options: ['Meno di 1h', '1–2h', '3–5h', 'Più di 5h'],
  },
  {
    id: 'q10',
    kind: 'text',
    section: 'Attività ripetitive',
    sectionIndex: 3,
    qNum: 10,
    title: 'Una seconda attività ripetitiva che ti viene in mente?',
    placeholder: 'Anche piccola, anche noiosissima…',
    optional: true,
  },
  {
    id: 'q11',
    kind: 'single',
    section: 'Attività ripetitive',
    sectionIndex: 3,
    qNum: 11,
    title: 'Quanto tempo a settimana per questa seconda attività?',
    options: ['Meno di 1h', '1–2h', '3–5h', 'Più di 5h'],
    optional: true,
  },
  {
    id: 'q12',
    kind: 'text',
    section: 'Attività ripetitive',
    sectionIndex: 3,
    qNum: 12,
    title: 'Una terza? (ultima, promesso)',
    placeholder: 'Opzionale',
    optional: true,
  },
  {
    id: 'q13',
    kind: 'single',
    section: 'Attività ripetitive',
    sectionIndex: 3,
    qNum: 13,
    title: 'Quanto tempo a settimana per la terza attività?',
    options: ['Meno di 1h', '1–2h', '3–5h', 'Più di 5h'],
    optional: true,
  },
  {
    id: 'q14',
    kind: 'text',
    section: 'Ruolo',
    sectionIndex: 3,
    qNum: 14,
    title: 'Qual è il tuo ruolo in azienda?',
    placeholder: 'Es. Mediatore senior, Office manager, Founder…',
  },
  {
    id: 'q15',
    kind: 'single',
    section: 'Ruolo',
    sectionIndex: 3,
    qNum: 15,
    title: 'Cosa speri di ottenere dalla formazione?',
    options: ['Risparmiare tempo', "Capire l'AI", 'Migliorare output', 'Altro'],
  },
  {
    id: 'thanks',
    kind: 'thanks',
    section: 'Fatto',
    sectionIndex: 4,
  },
];

// Indices that count toward the progress bar (skip cover + assess_intro)
const PROGRESS_IDS = FLOW.filter((s) => !['cover', 'day1', 'day2', 'brain', 'assess_intro', 'thanks'].includes(s.id)).map((s) => s.id);

// ─────────────────────────────────────────────────────────────────────────────
// THEME — derived from tweaks
// ─────────────────────────────────────────────────────────────────────────────

function buildTheme(t) {
  const dark = t.dark;
  const accent = t.accent;
  // luminance-aware accent ink (text color on accent buttons)
  const accentInk = '#050505';
  return {
    bg: dark ? '#050505' : '#FAFAF7',
    cardBg: dark ? '#0A0A0A' : '#FFFFFF',
    fg: dark ? '#F5F5F4' : '#0A0A0A',
    fgMuted: dark ? 'rgba(245,245,244,0.55)' : 'rgba(10,10,10,0.55)',
    fgDim: dark ? 'rgba(245,245,244,0.35)' : 'rgba(10,10,10,0.4)',
    border: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)',
    borderStrong: dark ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.18)',
    accent,
    accentDim: accent + '22',
    accentInk,
    fontFamily:
      t.font === 'manrope'
        ? "'Manrope', ui-sans-serif, system-ui, sans-serif"
        : t.font === 'inter'
        ? "'Inter', ui-sans-serif, system-ui, sans-serif"
        : "'Instrument Serif', ui-serif, Georgia, serif",
    questionFontFamily:
      t.font === 'serif'
        ? "'Instrument Serif', ui-serif, Georgia, serif"
        : t.font === 'inter'
        ? "'Inter', ui-sans-serif, system-ui, sans-serif"
        : "'Manrope', ui-sans-serif, system-ui, sans-serif",
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// MAIN COMPONENT
// ─────────────────────────────────────────────────────────────────────────────

function MartesTypeform({ tweaks, setTweak, embedded, startIdx = 0 }) {
  const [idx, setIdx] = useState(startIdx);
  const [dir, setDir] = useState(1); // 1 = forward (slide up), -1 = back (slide down)
  const [answers, setAnswers] = useState({});
  const [submitState, setSubmitState] = useState('idle'); // idle | sending | sent | error
  const containerRef = useRef(null);

  const theme = useMemo(() => buildTheme(tweaks), [tweaks]);
  const screen = FLOW[idx];

  const goNext = useCallback(() => {
    setDir(1);
    setIdx((i) => Math.min(i + 1, FLOW.length - 1));
  }, []);
  const goPrev = useCallback(() => {
    setDir(-1);
    setIdx((i) => Math.max(i - 1, 0));
  }, []);

  // ── answer helpers ──
  const setAnswer = (id, val) => setAnswers((a) => ({ ...a, [id]: val }));
  const getAnswer = (id) => answers[id];

  const isAnswered = (s) => {
    if (!s) return true;
    if (s.kind === 'info' || s.kind === 'brain' || s.kind === 'thanks') return true;
    if (s.optional) return true;
    const v = answers[s.id];
    if (s.kind === 'multi') return Array.isArray(v) && v.length > 0;
    if (s.kind === 'text') return typeof v === 'string' && v.trim().length > 0;
    return v !== undefined && v !== null && v !== '';
  };

  const canAdvance = isAnswered(screen);

  const handleSingleSelect = (s, opt) => {
    setAnswer(s.id, opt);
  };

  // ── keyboard nav ──
  useEffect(() => {
    const onKey = (e) => {
      // ignore when typing into an input/textarea (except Enter/arrow handling below)
      const tag = (e.target.tagName || '').toLowerCase();
      const inField = tag === 'input' || tag === 'textarea';

      if (e.key === 'Enter') {
        // shift+enter inside textarea = newline; plain enter = advance
        if (inField && tag === 'textarea' && e.shiftKey) return;
        if (canAdvance) {
          e.preventDefault();
          if (screen.kind === 'thanks') {
            submit();
          } else {
            goNext();
          }
        }
        return;
      }
      if (inField) return;
      if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
        if (canAdvance) goNext();
      } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
        goPrev();
      } else if (screen.kind === 'single' && /^[1-9]$/.test(e.key)) {
        const n = parseInt(e.key, 10) - 1;
        if (screen.options[n]) handleSingleSelect(screen, screen.options[n]);
      } else if (screen.kind === 'multi' && /^[a-z]$/i.test(e.key)) {
        const n = e.key.toLowerCase().charCodeAt(0) - 97;
        if (screen.options[n]) toggleMulti(screen, screen.options[n]);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [screen, canAdvance, goNext, goPrev]);

  const toggleMulti = (s, opt) => {
    setAnswers((a) => {
      const cur = Array.isArray(a[s.id]) ? a[s.id] : [];
      const next = cur.includes(opt) ? cur.filter((x) => x !== opt) : [...cur, opt];
      return { ...a, [s.id]: next };
    });
  };

  const submit = async () => {
    if (submitState === 'sending' || submitState === 'sent') return;
    setSubmitState('sending');
    try {
      const params = new URLSearchParams(window.location.search);
      const client = params.get('client') || 'Sconosciuto';

      const payload = {
        client,
        answers,
        timestamp: new Date().toISOString(),
      };

      const res = await fetch('/api/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const err = await res.text();
        throw new Error(err);
      }

      setSubmitState('sent');
    } catch (err) {
      console.error('[Assessment] submit error:', err);
      setSubmitState('error');
    }
  };

  // ── progress ──
  const progressPct = useMemo(() => {
    const i = PROGRESS_IDS.indexOf(screen.id);
    if (i < 0) {
      // info screens: hold prior value, except cover (0) and thanks (100)
      if (screen.id === 'cover') return 0;
      if (screen.id === 'thanks') return 100;
      // for day1/day2/brain/assess_intro, scale by sectionIndex
      return Math.max(0, Math.min(8, screen.sectionIndex * 2));
    }
    return ((i + 1) / PROGRESS_IDS.length) * 100;
  }, [screen]);

  // ── render ──
  return (
    <div
      ref={containerRef}
      className="mt-root"
      style={{
        '--bg': theme.bg,
        '--card': theme.cardBg,
        '--fg': theme.fg,
        '--fg-muted': theme.fgMuted,
        '--fg-dim': theme.fgDim,
        '--border': theme.border,
        '--border-strong': theme.borderStrong,
        '--accent': theme.accent,
        '--accent-dim': theme.accentDim,
        '--accent-ink': theme.accentInk,
        '--font': theme.fontFamily,
        '--font-q': theme.questionFontFamily,
        '--transition': tweaks.transition,
      }}
    >
      {/* progress bar */}
      {tweaks.showProgress && (
        <div className="mt-progress-wrap">
          <div className="mt-progress-track">
            <div className="mt-progress-fill" style={{ width: `${progressPct}%` }} />
          </div>
          <div className="mt-progress-meta">
            {screen.qNum && <span>{screen.qNum} / 15</span>}
          </div>
        </div>
      )}

      {/* slides */}
      <div className="mt-stage">
        <CrossFadeStage screenKey={screen.id} dir={dir} transition={tweaks.transition}>
          <ScreenRenderer
            screen={screen}
            answer={getAnswer(screen.id)}
            onSelect={(opt) => handleSingleSelect(screen, opt)}
            onToggle={(opt) => toggleMulti(screen, opt)}
            onText={(v) => setAnswer(screen.id, v)}
            onSetAnswer={(v) => setAnswer(screen.id, v)}
            onSubmit={submit}
            submitState={submitState}
            answers={answers}
          />
        </CrossFadeStage>
      </div>

      {/* CTA — rendered OUTSIDE the stage so position:fixed works (transform on .mt-slide breaks it) */}
      {screen.kind !== 'thanks' && (
        <InlineCTA
          label={screen.cta || 'Avanti'}
          onClick={screen.kind === 'thanks' ? submit : goNext}
          disabled={!canAdvance}
          onBack={goPrev}
          canBack={idx > 0}
        />
      )}

      {/* footer — desktop only nav arrows */}
      {screen.kind !== 'thanks' && (
        <div className="mt-footer">
          <div className="mt-footer-left">
            <button
              className="mt-nav-btn"
              onClick={goPrev}
              disabled={idx === 0}
              aria-label="Indietro"
              title="Indietro (↑)"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M4 10l4-4 4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button
              className="mt-nav-btn"
              onClick={goNext}
              disabled={!canAdvance || idx === FLOW.length - 1}
              aria-label="Avanti"
              title="Avanti (↓)"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
          <div className="mt-footer-meta">
            <kbd>↵</kbd> per andare avanti
          </div>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SLIDE — vertical Typeform-style enter/exit
// ─────────────────────────────────────────────────────────────────────────────

function Slide({ children, dir, transition }) {
  const cls = `mt-slide mt-slide-${transition} mt-slide-dir-${dir > 0 ? 'fwd' : 'back'}`;
  return <div className={cls}>{children}</div>;
}

// SimpleStage — one slide at a time, no overlap, no dual-mount.
// Uses React key to force unmount/remount, CSS handles the fade-in.
function CrossFadeStage({ screenKey, dir, transition, children }) {
  return (
    <div
      key={screenKey}
      className={`mt-slide mt-slide-${transition} mt-slide-enter`}
    >
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SCREEN RENDERER
// ─────────────────────────────────────────────────────────────────────────────

function ScreenRenderer({ screen, answer, onSelect, onToggle, onText, onSetAnswer, onSubmit, submitState, answers }) {
  if (screen.kind === 'info') return <InfoScreen screen={screen} />;
  if (screen.kind === 'brain') return <BrainScreen screen={screen} />;
  if (screen.kind === 'single') return <SingleScreen screen={screen} answer={answer} onSelect={onSelect} />;
  if (screen.kind === 'multi') return <MultiScreen screen={screen} answer={answer} onToggle={onToggle} onSetAnswer={onSetAnswer} />;
  if (screen.kind === 'text') return <TextScreen screen={screen} answer={answer} onText={onText} />;
  if (screen.kind === 'thanks') return <ThanksScreen onSubmit={onSubmit} submitState={submitState} answers={answers} />;
  return null;
}

// Big inline CTA — green, prominent, right-aligned just below the screen content.
function InlineCTA({ label, onClick, disabled, onBack, canBack }) {
  return (
    <div className="mt-inline-cta-row">
      {canBack && (
        <button className="mt-inline-back" onClick={onBack} type="button" aria-label="Indietro">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
            <path d="M9 3l-4 4 4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <span>Indietro</span>
        </button>
      )}
      <button className="mt-inline-cta" onClick={onClick} disabled={disabled}>
        <span>{label}</span>
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
          <path d="M3 9h11M10 4l5 5-5 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>
    </div>
  );
}

// ── INFO ──
function InfoScreen({ screen }) {
  const [visibleCount, setVisibleCount] = useState(0);
  const hasBullets = screen.bullets && screen.bullets.length > 0;

  useEffect(() => {
    if (!hasBullets || visibleCount >= screen.bullets.length) return;
    const t = setTimeout(() => setVisibleCount((c) => c + 1), 150 + visibleCount * 120);
    return () => clearTimeout(t);
  }, [visibleCount, hasBullets, screen.bullets]);

  return (
    <div className="mt-screen mt-screen-info">
      {screen.eyebrow && <div className="mt-eyebrow">{screen.eyebrow}</div>}
      {screen.subtitle && <div className="mt-subtitle">{screen.subtitle}</div>}
      <h1 className="mt-title">{screen.title}</h1>
      {screen.body && <p className="mt-body">{screen.body}</p>}
      {hasBullets && (
        <ol className="mt-bullets">
          {screen.bullets.map((b, i) => (
            <li
              key={b.n}
              className="mt-bullet"
              style={{
                opacity: i < visibleCount ? 1 : 0,
                transform: i < visibleCount ? 'translateX(0)' : 'translateX(16px)',
                transition: 'opacity 300ms ease, transform 300ms ease',
              }}
            >
              <span className="mt-bullet-n">{b.n}</span>
              <span className="mt-bullet-t">{b.text}</span>
            </li>
          ))}
        </ol>
      )}
    </div>
  );
}

// ── BRAIN ──
function BrainScreen({ screen }) {
  const [visibleCount, setVisibleCount] = useState(0);

  useEffect(() => {
    if (visibleCount >= screen.layers.length) return;
    const t = setTimeout(() => setVisibleCount((c) => c + 1), 150 + visibleCount * 120);
    return () => clearTimeout(t);
  }, [visibleCount, screen.layers.length]);

  return (
    <div className="mt-screen mt-screen-brain">
      <div className="mt-brain-text">
        {screen.eyebrow && <div className="mt-eyebrow">{screen.eyebrow}</div>}
        <h1 className="mt-title">{screen.title}</h1>
        <p className="mt-body">{screen.intro}</p>
        <p className="mt-body mt-body-dim">{screen.outro}</p>
      </div>
      <div className="mt-brain-stack" role="list">
        {screen.layers.map((l, i) => (
          <div
            key={l.n}
            role="listitem"
            className="mt-brain-layer"
            style={{
              '--i': i,
              opacity: i < visibleCount ? 1 : 0,
              transform: i < visibleCount ? 'translateX(0)' : 'translateX(16px)',
              transition: 'opacity 300ms ease, transform 300ms ease',
            }}
          >
            <div className="mt-brain-layer-n">{l.n}</div>
            <div className="mt-brain-layer-body">
              <div className="mt-brain-layer-name">{l.name}</div>
              <div className="mt-brain-layer-desc">{l.desc}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── SINGLE ──
function SingleScreen({ screen, answer, onSelect }) {
  const [altroText, setAltroText] = useState('');

  const handleSelect = (opt) => {
    if (opt === 'Altro') {
      onSelect(altroText ? `Altro: ${altroText}` : 'Altro');
    } else {
      onSelect(opt);
    }
  };

  const handleAltroText = (v) => {
    setAltroText(v);
    onSelect(v ? `Altro: ${v}` : 'Altro');
  };

  return (
    <div className="mt-screen mt-screen-q">
      <QHeader screen={screen} />
      <div className="mt-options">
        {screen.options.map((opt, i) => {
          const selected = opt === 'Altro'
            ? (answer === 'Altro' || (answer && answer.startsWith('Altro:')))
            : answer === opt;
          return (
            <React.Fragment key={opt}>
              <button
                className={`mt-option ${selected ? 'is-selected' : ''}`}
                onClick={() => handleSelect(opt)}
              >
                <span className="mt-option-key">{i + 1}</span>
                <span className="mt-option-label">{opt}</span>
                <span className="mt-option-check">
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                    <path d="M3 7.5l3 3 5-6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </span>
              </button>
              {opt === 'Altro' && selected && (
                <input
                  className="mt-altro-input"
                  type="text"
                  placeholder="Specifica…"
                  value={altroText}
                  onChange={(e) => handleAltroText(e.target.value)}
                  autoFocus
                />
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

// ── MULTI ──
function MultiScreen({ screen, answer, onToggle, onSetAnswer }) {
  const sel = Array.isArray(answer) ? answer : [];
  const [altroText, setAltroText] = useState('');
  const isAltroOn = sel.some((s) => s === 'Altro' || s.startsWith('Altro:'));

  const handleToggle = (opt) => {
    if (opt === 'Nessuno') {
      onSetAnswer(sel.includes('Nessuno') ? [] : ['Nessuno']);
      return;
    }
    const withoutNessuno = sel.filter((s) => s !== 'Nessuno');
    const isOn = withoutNessuno.includes(opt);
    onSetAnswer(isOn ? withoutNessuno.filter((s) => s !== opt) : [...withoutNessuno, opt]);
  };

  const handleAltroToggle = () => {
    if (isAltroOn) {
      onSetAnswer(sel.filter((s) => s !== 'Altro' && !s.startsWith('Altro:')));
      setAltroText('');
    } else {
      const withoutNessuno = sel.filter((s) => s !== 'Nessuno');
      onSetAnswer([...withoutNessuno, altroText ? `Altro: ${altroText}` : 'Altro']);
    }
  };

  const handleAltroText = (v) => {
    setAltroText(v);
    const clean = sel.filter((s) => s !== 'Altro' && !s.startsWith('Altro:') && s !== 'Nessuno');
    onSetAnswer([...clean, v ? `Altro: ${v}` : 'Altro']);
  };

  return (
    <div className="mt-screen mt-screen-q">
      <QHeader screen={screen} />
      <div className="mt-options">
        {screen.options.map((opt, i) => {
          const isOn = opt === 'Altro' ? isAltroOn : sel.includes(opt);
          return (
            <React.Fragment key={opt}>
              <button
                className={`mt-option ${isOn ? 'is-selected' : ''}`}
                onClick={() => opt === 'Altro' ? handleAltroToggle() : handleToggle(opt)}
              >
                <span className="mt-option-key">{String.fromCharCode(65 + i)}</span>
                <span className="mt-option-label">{opt}</span>
                <span className="mt-option-check mt-option-check-multi">
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                    <path d="M3 7.5l3 3 5-6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </span>
              </button>
              {opt === 'Altro' && isAltroOn && (
                <input
                  className="mt-altro-input"
                  type="text"
                  placeholder="Specifica cosa usi…"
                  value={altroText}
                  onChange={(e) => handleAltroText(e.target.value)}
                  autoFocus
                />
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

// ── TEXT ──
function TextScreen({ screen, answer, onText }) {
  const ref = useRef(null);
  useEffect(() => {
    const t = setTimeout(() => ref.current && ref.current.focus(), 350);
    return () => clearTimeout(t);
  }, [screen.id]);
  return (
    <div className="mt-screen mt-screen-q">
      <QHeader screen={screen} />
      <textarea
        ref={ref}
        className="mt-textarea"
        rows={3}
        placeholder={screen.placeholder || 'Scrivi qui…'}
        value={answer || ''}
        onChange={(e) => onText(e.target.value)}
      />
      <div className="mt-text-hint">
        <kbd>Shift</kbd> + <kbd>Invio</kbd> per andare a capo
      </div>
    </div>
  );
}

// ── THANKS ──
function ThanksScreen({ onSubmit, submitState, answers }) {
  // Auto-submit on first reveal
  const sentRef = useRef(false);
  useEffect(() => {
    if (!sentRef.current) {
      sentRef.current = true;
      onSubmit();
    }
  }, []);
  return (
    <div className="mt-screen mt-screen-thanks">
      <div className="mt-thanks-mark">
        <svg width="64" height="64" viewBox="0 0 64 64" fill="none" aria-hidden="true">
          <circle cx="32" cy="32" r="30" stroke="var(--accent)" strokeWidth="1.5" />
          <path
            d="M20 33l8 8 16-18"
            stroke="var(--accent)"
            strokeWidth="2.4"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="mt-thanks-tick"
          />
        </svg>
      </div>
      <h1 className="mt-title mt-thanks-title">Grazie mille per il tuo tempo.</h1>
      <p className="mt-body mt-thanks-body">Ci vediamo alla formazione.</p>
      <div className="mt-thanks-status">
        {submitState === 'sending' && <span>Sto inviando le risposte…</span>}
        {submitState === 'sent' && <span className="mt-thanks-sent">Risposte inviate ✓</span>}
        {submitState === 'error' && <span className="mt-thanks-err">Errore — riprova</span>}
      </div>
      <div className="mt-thanks-meta">{Object.keys(answers).length} risposte registrate</div>
    </div>
  );
}

// ── QUESTION HEADER ──
function QHeader({ screen }) {
  return (
    <div className="mt-q-head">
      <div className="mt-q-num">
        <span className="mt-q-num-n">{screen.qNum}</span>
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
          <path d="M2 5h6M5 2l3 3-3 3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <h2 className="mt-q-title">
        {screen.title}
        {screen.optional && <span className="mt-q-optional"> · opzionale</span>}
      </h2>
      {screen.hint && <div className="mt-q-hint">{screen.hint}</div>}
    </div>
  );
}

window.MartesTypeform = MartesTypeform;
