// typeform.jsx
// Webinar pre-live questionnaire, Typeform-style flow.
// Cover (Ric voice) + questions A-G live here. Mounted by index.html.
// Backend: /api/submit → Google Sheets. Answers keyed by screen id.

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

// ─────────────────────────────────────────────────────────────────────────────
// DEFAULT FLOW - declarative list of every screen in order.
// kind: 'info' | 'single' | 'multi' | 'text' | 'thanks'
// Only 'livello' (A) and 'competenze' (B) are required; everything else is
// optional so the form stays a 30-second tap-through for the rushed, while the
// motivated give the open-text gold.
// ─────────────────────────────────────────────────────────────────────────────

const DEFAULT_FLOW = [
  // ── Cover · voce di Ric ──
  {
    id: 'cover',
    kind: 'info',
    section: 'Benvenuto',
    eyebrow: 'Ciao raga, qui Ric 👋',
    title: 'Aiutami a preparare il webinar su misura per te.',
    body:
      "30 secondi, due tap. Dimmi a che punto sei con l'AI e cosa vuoi vedere lunedì in diretta. Così costruisco il programma per te, non a caso.",
    cta: 'Iniziamo',
  },

  // ── Opener · \"cosa fai\" (il video promette \"ditemi cosa fate\") ──
  {
    id: 'lavoro',
    kind: 'text',
    section: 'Chi sei',
    title: 'In una riga: di cosa ti occupi?',
    placeholder: 'Es. commercialista, e-commerce, agenzia marketing, freelance, studente…',  },

  // ── A · Il tuo livello con l'AI (la domanda madre) ──
  {
    id: 'livello',
    kind: 'single',
    section: 'Il tuo livello',
    title: "Con l'intelligenza artificiale, oggi, dove ti collochi onestamente?",
    options: [
      "Curioso: l'ho aperta poche volte, parto praticamente da zero",
      'Utente base: la uso ogni tanto per scrivere testi o farmi domande',
      'Utente quotidiano: la uso tutti i giorni, ma il lavoro lo faccio comunque io a mano',
      'Apprendista costruttore: ho provato a costruire qualcosa (automazioni, tool) e mi sono arenato',
      'Smanettone: costruisco già sistemi/automazioni, voglio salire di livello',
    ],
  },

  // ── B · Cosa sai già FARE (competenza reale) ──
  {
    id: 'competenze',
    kind: 'multi',
    section: 'Cosa sai fare',
    title: 'Quali di queste cose hai già fatto almeno una volta?',
    hint: "Puoi selezionare più di un'opzione",
    options: [
      'Scrivere prompt per ottenere quello che voglio',
      'Creare un GPT / un progetto / un assistente personalizzato',
      "Dare all'AI dei documenti e farci lavorare sopra",
      'Usare uno strumento di automazione (n8n, Make, Zapier...)',
      "Collegare l'AI a un tool esterno (mail, calendario, WhatsApp, un'API)",
      'Mettere davvero in funzione un sistema che lavora da solo',
      'Nessuna di queste',
    ],
  },

  // ── C · Con quali strumenti hai già messo le mani ──
  {
    id: 'strumenti',
    kind: 'multi',
    section: 'I tuoi strumenti',
    title: 'Quali di questi hai già provato?',
    hint: "Puoi selezionare più di un'opzione",    options: [
      'ChatGPT / Gemini / Claude nel browser',
      'Claude Code / Cursor / ambienti da "costruttore"',
      'n8n / Make / Zapier',
      'Replit / strumenti per creare app',
      'Nessuno, solo la chat',
    ],
  },

  // ── D · Il gap (dove sta il valore per loro) ──
  {
    id: 'gap',
    kind: 'text',
    section: 'Il tuo obiettivo',
    title: "Cosa vorresti saper fare con l'AI, che oggi non sai fare?",
    placeholder: 'Anche una riga secca va benissimo…',  },

  // ── E · La cosa noiosa numero uno (feeds demo + hot-seat) ──
  {
    id: 'attivita_noiosa',
    kind: 'text',
    section: 'Il tuo obiettivo',
    title:
      'Qual è il lavoro ripetitivo che ti porta via più tempo ogni settimana, quello che vorresti toglierti di dosso?',
    placeholder: 'Es. rispondere sempre alle stesse mail, sistemare fogli, cercare info…',  },

  // ── F · L'ostacolo numero uno (pesa i 3 Segreti) ──
  {
    id: 'ostacolo',
    kind: 'single',
    section: 'Cosa ti frena',
    title: "Cosa ti frena di più dal far lavorare l'AI al posto tuo?",    options: [
      'Non sono tecnico / ho paura del codice',
      'Ci ho già provato e ho fallito, forse non fa per me',
      'Non ho tempo da dedicarci',
      'Non so da dove iniziare, mi manca un metodo',
    ],
  },

  // ── G · La domanda diretta (theme mining) ──
  {
    id: 'domanda',
    kind: 'text',
    section: 'La tua domanda',
    title: "C'è UNA domanda a cui vorresti che rispondessi lunedì?",
    placeholder: 'Scrivila qui, le leggo tutte…',  },

  // ── Chiusura ──
  {
    id: 'thanks',
    kind: 'thanks',
    section: 'Fatto',
    title: 'Fatto. Grazie 🙌',
    body: 'Con queste risposte preparo il programma su misura. Ci vediamo lunedì.',
    bullets: [
      { n: '01', text: 'Appuntamento: lunedì ore 20:30, in diretta' },
      { n: '02', text: 'Il link della live te lo mando prima di iniziare' },
      { n: '03', text: 'Preparati la cosa noiosa che vuoi toglierti di dosso' },
    ],
  },
];

// ─────────────────────────────────────────────────────────────────────────────
// buildFlow - assign sequential question numbers to answerable screens.
// ─────────────────────────────────────────────────────────────────────────────

function buildFlow() {
  const flow = DEFAULT_FLOW.map((screen) => ({ ...screen }));
  let n = 0;
  for (const s of flow) {
    if (s.kind === 'single' || s.kind === 'multi' || s.kind === 'text') {
      n += 1;
      s.qNum = n;
    }
  }
  return flow;
}

// ─────────────────────────────────────────────────────────────────────────────
// THEME - derived from tweaks
// ─────────────────────────────────────────────────────────────────────────────

function buildTheme(t) {
  const dark = t.dark;
  const accent = t.accent;
  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",
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// nowLabel - compile time as a readable Italian label, e.g. "martedì 7 luglio, 21:34".
// ─────────────────────────────────────────────────────────────────────────────

function nowLabel() {
  const d = new Date();
  const date = new Intl.DateTimeFormat('it-IT', { weekday: 'long', day: 'numeric', month: 'long' }).format(d);
  const time = new Intl.DateTimeFormat('it-IT', { hour: '2-digit', minute: '2-digit' }).format(d);
  return `${date}, ${time}`;
}

// ─────────────────────────────────────────────────────────────────────────────
// 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 FLOW = useMemo(() => buildFlow(), []);
  const PROGRESS_IDS = useMemo(
    () => FLOW.filter((s) => ['single', 'multi', 'text'].includes(s.kind)).map((s) => s.id),
    [FLOW]
  );
  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));
  }, [FLOW.length]);
  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 === '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) => {
      const tag = (e.target.tagName || '').toLowerCase();
      const inField = tag === 'input' || tag === 'textarea';

      if (e.key === 'Enter') {
        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 source = params.get('src') || params.get('source') || 'webinar';

      const payload = {
        source,
        answers,
        timestamp: nowLabel(),
      };

      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('[Webinar] submit error:', err);
      setSubmitState('error');
    }
  };

  // ── progress ──
  // Tied to the screen index so the bar advances on every step (cover → thanks),
  // monotonic and always responsive on each "Avanti".
  const progressPct = useMemo(() => {
    if (FLOW.length <= 1) return 0;
    return (idx / (FLOW.length - 1)) * 100;
  }, [idx, FLOW.length]);

  // ── 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} / {PROGRESS_IDS.length}</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 */}
      {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>;
}

// One slide at a time, no overlap. React key forces remount, CSS handles 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 === '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 screen={screen} onSubmit={onSubmit} submitState={submitState} answers={answers} />;
  return null;
}

// Big inline CTA - accent, 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>
  );
}

// ── ASCII SPHERE (cover background, ported from mastermind-invite) ──
function AsciiSphere() {
  const canvasRef = useRef(null);
  const frameRef = useRef(0);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const chars = '░▒▓█▀▄▌▐│─┤├┴┬╭╮╰╯';
    let time = 0;

    const resize = () => {
      const dpr = window.devicePixelRatio || 1;
      const rect = canvas.getBoundingClientRect();
      canvas.width = rect.width * dpr;
      canvas.height = rect.height * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    const render = () => {
      const rect = canvas.getBoundingClientRect();
      ctx.clearRect(0, 0, rect.width, rect.height);

      const centerX = rect.width / 2;
      const centerY = rect.height / 2;
      const radius = Math.min(rect.width, rect.height) * 0.46;

      ctx.font = '13px monospace';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      const points = [];
      for (let phi = 0; phi < Math.PI * 2; phi += 0.13) {
        for (let theta = 0; theta < Math.PI; theta += 0.13) {
          const x = Math.sin(theta) * Math.cos(phi + time * 0.5);
          const y = Math.sin(theta) * Math.sin(phi + time * 0.5);
          const z = Math.cos(theta);

          const rotY = time * 0.3;
          const newX = x * Math.cos(rotY) - z * Math.sin(rotY);
          const newZ = x * Math.sin(rotY) + z * Math.cos(rotY);

          const rotX = time * 0.2;
          const newY = y * Math.cos(rotX) - newZ * Math.sin(rotX);
          const finalZ = y * Math.sin(rotX) + newZ * Math.cos(rotX);

          const depth = (finalZ + 1) / 2;
          const charIndex = Math.floor(depth * (chars.length - 1));

          points.push({
            x: centerX + newX * radius,
            y: centerY + newY * radius,
            z: finalZ,
            char: chars[charIndex],
          });
        }
      }

      points.sort((a, b) => a.z - b.z);

      points.forEach((point) => {
        const depth = (point.z + 1) / 2; // 0 (back) → 1 (front)
        const alpha = 0.15 + depth * 0.7;
        const r = Math.round(243 - (243 - 74) * depth);
        const g = Math.round(243 - (243 - 222) * depth);
        const b = Math.round(243 - (243 - 128) * depth);
        ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${alpha})`;
        ctx.fillText(point.char, point.x, point.y);
      });

      time += reduce ? 0 : 0.02;
      frameRef.current = requestAnimationFrame(render);
    };
    render();

    return () => {
      window.removeEventListener('resize', resize);
      cancelAnimationFrame(frameRef.current);
    };
  }, []);

  return <canvas ref={canvasRef} className="mt-cover-sphere" />;
}

// ── 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]);

  const isCover = screen.id === 'cover';
  return (
    <div className={`mt-screen mt-screen-info${isCover ? ' mt-screen-cover' : ''}`}>
      {isCover && (
        <div className="mt-cover-bg" aria-hidden="true">
          <AsciiSphere />
          <div className="mt-cover-scrim" />
        </div>
      )}
      {isCover && <img className="mt-cover-logo" src="/martes-logo.png" alt="Martes AI" />}
      {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>
  );
}

// ── 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:'));

  // Options that clear every other selection when picked.
  const EXCLUSIVE = ['Nessuno', 'Mai', 'Nessuna di queste', 'Nessuno, solo la chat'];
  const isExclusive = (o) => EXCLUSIVE.includes(o);
  const withoutExclusive = (arr) => arr.filter((s) => !EXCLUSIVE.includes(s));

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

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

  const handleAltroText = (v) => {
    setAltroText(v);
    const clean = sel.filter((s) => s !== 'Altro' && !s.startsWith('Altro:') && !isExclusive(s));
    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>
  );
}

// ── THANKS (grazie + prossimi passi) ──
function ThanksScreen({ screen, onSubmit, submitState, answers }) {
  const sentRef = useRef(false);
  useEffect(() => {
    if (!sentRef.current) {
      sentRef.current = true;
      onSubmit();
    }
  }, []);
  const hasBullets = screen && screen.bullets && screen.bullets.length > 0;
  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">{(screen && screen.title) || 'Grazie mille per il tuo tempo.'}</h1>
      <p className="mt-body mt-thanks-body">{(screen && screen.body) || 'Ci vediamo lunedì.'}</p>
      {hasBullets && (
        <ol className="mt-bullets mt-thanks-bullets">
          {screen.bullets.map((b) => (
            <li key={b.n} className="mt-bullet">
              <span className="mt-bullet-n">{b.n}</span>
              <span className="mt-bullet-t">{b.text}</span>
            </li>
          ))}
        </ol>
      )}
      <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;
