// screens.jsx — Onboarding / form screens for the Invitino app
// Each screen receives { state, setState, next, back }

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// Shared chrome
// ─────────────────────────────────────────────────────────────
function ScreenHeader({ step, totalSteps, onBack }) {
  if (step == null) return null;
  return (
    <div style={{ padding: '14px 22px 8px', display: 'flex', alignItems: 'center', gap: 12 }}>
      {onBack ? (
        <button onClick={onBack} className="iconbtn" aria-label="indietro" style={{ width: 36, height: 36, background: '#fff' }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M15 18 L 9 12 L 15 6"/>
          </svg>
        </button>
      ) : <div style={{ width: 36 }} />}
      <div className="dots" style={{ flex: 1, justifyContent: 'center' }}>
        {Array.from({ length: totalSteps }).map((_, i) => (
          <div key={i} className={`dot ${i === step ? 'active' : i < step ? 'done' : ''}`} style={i === step ? { width: 28 } : {}} />
        ))}
      </div>
      <div style={{ width: 36 }} />
    </div>
  );
}

function CTAFooter({ children }) {
  return (
    <div style={{
      padding: '12px 20px 24px',
      background: 'linear-gradient(180deg, transparent 0%, var(--bg) 30%)',
    }}>{children}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// 0. Welcome screen
// ─────────────────────────────────────────────────────────────
function WelcomeScreen({ onStart }) {
  return (
    <div className="app-shell fade-step">
      <div className="app-scroll" style={{ display: 'flex', flexDirection: 'column' }}>
        {/* Hero illustration block */}
        <div style={{
          position: 'relative',
          minHeight: 380,
          background: 'linear-gradient(165deg, #FFE3D2 0%, #FFD0E2 60%, #E8D5FF 100%)',
          overflow: 'hidden',
          display: 'flex', alignItems: 'flex-end',
        }}>
          {/* floating preview cards */}
          <div style={{ position: 'absolute', left: '8%', top: '18%', transform: 'rotate(-8deg)', width: 140, aspectRatio: '3 / 4', boxShadow: '0 12px 28px rgba(45,36,56,0.18)', borderRadius: 14, overflow: 'hidden' }}>
            <Invitation themeId="unicorni" layoutId="illustrato" data={{ nome: 'Sofia', eta: '4', data: '2026-04-20', ora: '16:30', luogo: 'Via Roma 1' }} />
          </div>
          <div style={{ position: 'absolute', right: '6%', top: '14%', transform: 'rotate(7deg)', width: 130, aspectRatio: '3 / 4', boxShadow: '0 12px 28px rgba(45,36,56,0.18)', borderRadius: 14, overflow: 'hidden' }}>
            <Invitation themeId="bosco" layoutId="minimal" data={{ nome: 'Leo', eta: '3', data: '2026-04-20', ora: '16:30', luogo: 'Via Roma 1' }} />
          </div>
          <div style={{ position: 'absolute', left: '38%', top: '40%', transform: 'rotate(-2deg)', width: 130, aspectRatio: '3 / 4', boxShadow: '0 16px 36px rgba(45,36,56,0.22)', borderRadius: 14, overflow: 'hidden', zIndex: 2 }}>
            <Invitation themeId="spazio" layoutId="tipografico" data={{ nome: 'Marco', eta: '5', data: '2026-04-20', ora: '16:30', luogo: 'Via Roma 1' }} />
          </div>
          {/* sparkles */}
          <Sparkle size={20} color="#FFB84D" style={{ position: 'absolute', left: '28%', top: '12%' }} />
          <Sparkle size={14} color="#FF6B9D" style={{ position: 'absolute', right: '24%', bottom: '20%' }} />
          <Star size={16} color="#FF6B9D" style={{ position: 'absolute', left: '14%', bottom: '14%' }} />
        </div>

        {/* Copy block */}
        <div style={{ padding: '32px 24px 0', flex: 1 }}>
          <div className="h-eyebrow">INVITINO</div>
          <h1 className="h-display" style={{ marginTop: 10, marginBottom: 0, fontSize: 36 }}>
            Inviti per la festa<br/>in <em style={{ color: 'var(--primary)', fontStyle: 'italic' }}>2 minuti</em>.
          </h1>
          <p style={{ marginTop: 14, fontSize: 15, lineHeight: 1.5, color: 'var(--ink-2)' }}>
            Rispondi a 4 domande, scegli tra 4 anteprime e scarica il tuo invito senza watermark per <b>1€</b>.
          </p>

          <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Bullet>Senza account, senza app da scaricare</Bullet>
            <Bullet>Pronto da mandare su WhatsApp</Bullet>
            <Bullet>4 stili grafici per ogni tema</Bullet>
          </div>
        </div>

        <div style={{ height: 24 }} />
      </div>

      <CTAFooter>
        <button className="btn-primary" onClick={onStart} style={{ width: '100%' }}>
          Crea il mio invito
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M5 12 H 19 M 13 6 L 19 12 L 13 18"/>
          </svg>
        </button>
        <div style={{ marginTop: 10, fontSize: 12, color: 'var(--ink-3)', textAlign: 'center' }}>
          Anteprime gratis. Paghi solo se ti piace.
        </div>
      </CTAFooter>
    </div>
  );
}

function Bullet({ children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'var(--ink)' }}>
      <div style={{
        width: 24, height: 24, borderRadius: 999,
        background: 'var(--primary)', color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 12 L 10 17 L 19 7"/>
        </svg>
      </div>
      <span style={{ fontWeight: 500 }}>{children}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 1. Nome
// ─────────────────────────────────────────────────────────────
function NomeScreen({ state, setState, next, back, step, totalSteps }) {
  const inputRef = useRef(null);
  useEffect(() => {
    const t = setTimeout(() => inputRef.current?.focus(), 350);
    return () => clearTimeout(t);
  }, []);
  const valid = state.nome && state.nome.trim().length > 0;
  return (
    <div className="app-shell fade-step">
      <ScreenHeader step={step} totalSteps={totalSteps} onBack={back} />
      <div className="app-scroll" style={{ padding: '24px 24px 0' }}>
        <div className="h-eyebrow">DOMANDA 1 DI 4</div>
        <h2 className="h-display" style={{ marginTop: 10 }}>
          Come si chiama<br/>il festeggiato?
        </h2>
        <p style={{ marginTop: 8, fontSize: 14, color: 'var(--ink-2)' }}>
          Solo il nome: andrà a stampa grande sull'invito.
        </p>

        <div style={{ marginTop: 28, position: 'relative' }}>
          <input
            ref={inputRef}
            className="input"
            placeholder="es. Francesca"
            value={state.nome || ''}
            onChange={e => setState({ ...state, nome: e.target.value })}
            onKeyDown={e => e.key === 'Enter' && valid && next()}
            maxLength={20}
          />
        </div>

        {valid && (
          <div style={{ marginTop: 20, padding: '14px 18px', background: '#fff', borderRadius: 16, border: '1px solid var(--line)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.15em', color: 'var(--ink-3)' }}>ANTEPRIMA</div>
            <div style={{ fontFamily: 'Caveat, cursive', fontSize: 36, lineHeight: 1.1, color: 'var(--primary)', marginTop: 4 }}>
              È la festa di {state.nome}!
            </div>
          </div>
        )}
      </div>

      <CTAFooter>
        <button className="btn-primary" disabled={!valid} onClick={next} style={{ width: '100%' }}>
          Avanti
        </button>
      </CTAFooter>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2. Età
// ─────────────────────────────────────────────────────────────
function EtaScreen({ state, setState, next, back, step, totalSteps }) {
  const valid = state.eta && state.eta > 0;
  return (
    <div className="app-shell fade-step">
      <ScreenHeader step={step} totalSteps={totalSteps} onBack={back} />
      <div className="app-scroll" style={{ padding: '24px 24px 0' }}>
        <div className="h-eyebrow">DOMANDA 2 DI 4</div>
        <h2 className="h-display" style={{ marginTop: 10 }}>
          Quanti anni<br/>compie {state.nome || '...'}?
        </h2>

        <div style={{
          marginTop: 32,
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 10,
        }}>
          {Array.from({ length: 12 }).map((_, i) => {
            const age = i + 1;
            const sel = state.eta === age;
            return (
              <button
                key={age}
                onClick={() => setState({ ...state, eta: age })}
                style={{
                  aspectRatio: '1 / 1',
                  borderRadius: 16,
                  background: sel ? 'var(--ink)' : '#fff',
                  color: sel ? '#fff' : 'var(--ink)',
                  border: sel ? 'none' : '1.5px solid var(--line)',
                  fontFamily: 'DM Serif Display, serif',
                  fontSize: 28, lineHeight: 1,
                  fontWeight: 400,
                  transition: 'transform 0.1s ease',
                }}
              >{age}</button>
            );
          })}
        </div>

        {valid && (
          <div style={{ marginTop: 24, padding: '14px 18px', background: '#fff', borderRadius: 16, border: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                width: 56, height: 56, borderRadius: 999,
                background: 'var(--primary)', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'DM Serif Display, serif', fontSize: 32,
              }}>{state.eta}</div>
              <div>
                <div style={{ fontSize: 18, fontWeight: 700 }}>{state.nome} compie {state.eta}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{state.eta === 1 ? 'anno' : 'anni'}</div>
              </div>
            </div>
          </div>
        )}
      </div>

      <CTAFooter>
        <button className="btn-primary" disabled={!valid} onClick={next} style={{ width: '100%' }}>Avanti</button>
      </CTAFooter>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3. Tema
// ─────────────────────────────────────────────────────────────
function TemaScreen({ state, setState, next, back, step, totalSteps }) {
  const valid = !!state.tema;
  return (
    <div className="app-shell fade-step">
      <ScreenHeader step={step} totalSteps={totalSteps} onBack={back} />
      <div className="app-scroll" style={{ padding: '24px 24px 0' }}>
        <div className="h-eyebrow">DOMANDA 3 DI 4</div>
        <h2 className="h-display" style={{ marginTop: 10 }}>
          Scegli un tema.
        </h2>
        <p style={{ marginTop: 8, fontSize: 14, color: 'var(--ink-2)' }}>
          Cambierà colori e illustrazioni dell'invito. Potrai vedere tutti gli stili tra un attimo.
        </p>

        <div style={{
          marginTop: 22,
          display: 'grid', gridTemplateColumns: '1fr 1fr',
          gap: 12,
        }}>
          {Object.values(THEMES).map(t => {
            const sel = state.tema === t.id;
            return (
              <div
                key={t.id}
                className={`theme-card ${sel ? 'selected' : ''}`}
                onClick={() => setState({ ...state, tema: t.id })}
                style={{ aspectRatio: '1 / 1' }}
              >
                <ThemeTile theme={t} />
                <div className="check">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M5 12 L 10 17 L 19 7"/>
                  </svg>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ height: 16 }} />
      </div>

      <CTAFooter>
        <button className="btn-primary" disabled={!valid} onClick={next} style={{ width: '100%' }}>Avanti</button>
      </CTAFooter>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 4. Dettagli (data, ora, luogo)
// ─────────────────────────────────────────────────────────────
function DettagliScreen({ state, setState, next, back, step, totalSteps }) {
  const valid = state.data && state.ora && state.luogo && state.luogo.trim().length > 0;
  return (
    <div className="app-shell fade-step">
      <ScreenHeader step={step} totalSteps={totalSteps} onBack={back} />
      <div className="app-scroll" style={{ padding: '24px 24px 0' }}>
        <div className="h-eyebrow">DOMANDA 4 DI 4</div>
        <h2 className="h-display" style={{ marginTop: 10 }}>
          Quando e dove?
        </h2>

        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <FieldRow label="Data della festa">
            <input
              type="date"
              className="input"
              style={{ fontSize: 18 }}
              value={state.data || ''}
              onChange={e => setState({ ...state, data: e.target.value })}
            />
          </FieldRow>
          <FieldRow label="Orario">
            <input
              type="time"
              className="input"
              style={{ fontSize: 18 }}
              value={state.ora || ''}
              onChange={e => setState({ ...state, ora: e.target.value })}
            />
          </FieldRow>
          <FieldRow label="Indirizzo o luogo">
            <input
              type="text"
              className="input"
              style={{ fontSize: 18 }}
              placeholder="Via Roma 1, Milano"
              value={state.luogo || ''}
              onChange={e => setState({ ...state, luogo: e.target.value })}
            />
          </FieldRow>
        </div>

        <div style={{ marginTop: 18, padding: '12px 14px', background: '#FFF6E8', borderRadius: 14, fontSize: 12, color: 'var(--ink-2)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <div style={{ fontSize: 16, lineHeight: 1 }}>💡</div>
          <div>Potrai modificare tutto dopo aver scelto l'invito che ti piace di più.</div>
        </div>
        <div style={{ height: 16 }} />
      </div>

      <CTAFooter>
        <button className="btn-primary" disabled={!valid} onClick={next} style={{ width: '100%' }}>
          Crea le anteprime
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 3 L 14 9 L 20 9 L 15 13 L 17 19 L 12 16 L 7 19 L 9 13 L 4 9 L 10 9 Z"/>
          </svg>
        </button>
      </CTAFooter>
    </div>
  );
}

function FieldRow({ label, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-2)', letterSpacing: '0.02em' }}>{label}</span>
      {children}
    </label>
  );
}

// ─────────────────────────────────────────────────────────────
// 5. Generating (loading)
// ─────────────────────────────────────────────────────────────
function GeneratingScreen({ state, onDone }) {
  const [phase, setPhase] = useState(0);
  const phases = [
    'Mescolo i colori...',
    'Disegno le decorazioni...',
    'Sistemo i dettagli...',
    'Quasi fatto!',
  ];
  useEffect(() => {
    let i = 0;
    const id = setInterval(() => {
      i++;
      setPhase(i);
      if (i >= phases.length) {
        clearInterval(id);
        setTimeout(onDone, 400);
      }
    }, 600);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="app-shell fade-step" style={{ background: 'linear-gradient(180deg, #FFE9DD 0%, #FFD0E2 100%)' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 32px', textAlign: 'center' }}>
        {/* spinner of mini cards */}
        <div style={{ position: 'relative', width: 220, height: 220, marginBottom: 28 }}>
          {[0, 1, 2, 3].map(i => {
            const angle = (i * 90) + (phase * 90);
            const r = 70;
            const x = Math.cos(angle * Math.PI / 180) * r;
            const y = Math.sin(angle * Math.PI / 180) * r;
            return (
              <div key={i} style={{
                position: 'absolute', left: '50%', top: '50%',
                width: 60, aspectRatio: '3 / 4',
                marginLeft: -30, marginTop: -40,
                transform: `translate(${x}px, ${y}px) rotate(${angle / 4}deg)`,
                transition: 'transform 0.6s cubic-bezier(0.4, 0, 0.2, 1)',
                borderRadius: 8,
                overflow: 'hidden',
                boxShadow: '0 6px 18px rgba(45, 36, 56, 0.18)',
              }}>
                <Invitation themeId={state.tema} layoutId={LAYOUTS[i].id} data={state} />
              </div>
            );
          })}
          {/* center sparkle */}
          <div style={{
            position: 'absolute', left: '50%', top: '50%',
            width: 56, height: 56, marginLeft: -28, marginTop: -28,
            background: '#fff', borderRadius: 999,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 4px 16px rgba(45, 36, 56, 0.18)',
          }}>
            <Sparkle size={28} color="#FFB84D" />
          </div>
        </div>

        <div className="h-display" style={{ fontSize: 28 }}>
          Sto preparando<br/>4 inviti per <em style={{ color: 'var(--primary)', fontStyle: 'italic' }}>{state.nome}</em>
        </div>
        <div style={{ marginTop: 16, fontSize: 14, color: 'var(--ink-2)', minHeight: 20 }}>
          {phases[Math.min(phase, phases.length - 1)]}
        </div>

        {/* progress */}
        <div style={{ marginTop: 24, width: '70%', height: 6, background: 'rgba(255,255,255,0.5)', borderRadius: 999, overflow: 'hidden' }}>
          <div style={{
            width: `${Math.min(100, ((phase + 1) / phases.length) * 100)}%`,
            height: '100%',
            background: 'var(--primary)',
            transition: 'width 0.5s ease',
          }} />
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2.5 Foto (optional photo upload)
// ─────────────────────────────────────────────────────────────
function FotoScreen({ state, setState, next, back, step, totalSteps }) {
  const fileRef = useRef(null);
  const onPick = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => setState({ ...state, photo: reader.result });
    reader.readAsDataURL(f);
  };
  const removePhoto = () => setState({ ...state, photo: null });

  return (
    <div className="app-shell fade-step">
      <ScreenHeader step={step} totalSteps={totalSteps} onBack={back} />
      <div className="app-scroll" style={{ padding: '24px 24px 0' }}>
        <div className="h-eyebrow">FOTO · OPZIONALE</div>
        <h2 className="h-display" style={{ marginTop: 10 }}>
          Vuoi mettere una foto?
        </h2>
        <p style={{ marginTop: 8, fontSize: 14, color: 'var(--ink-2)' }}>
          Una foto del bimbo o del suo personaggio preferito. Apparirà sull'invito al posto del cerchio con l'età.
        </p>

        <div style={{ marginTop: 24 }}>
          {!state.photo ? (
            <button
              onClick={() => fileRef.current?.click()}
              style={{
                width: '100%', aspectRatio: '4 / 3',
                borderRadius: 22,
                border: '2px dashed var(--line-2)',
                background: '#fff',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                gap: 12, padding: 20,
                color: 'var(--ink)',
              }}
            >
              <div style={{
                width: 56, height: 56, borderRadius: 999,
                background: 'var(--primary)', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 5 V 19 M 5 12 H 19"/>
                </svg>
              </div>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 16, fontWeight: 700 }}>Carica una foto</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>JPG o PNG · funziona meglio in formato quadrato</div>
              </div>
            </button>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{
                width: '100%', aspectRatio: '4 / 3',
                borderRadius: 22,
                background: '#000',
                overflow: 'hidden',
                position: 'relative',
              }}>
                <img src={state.photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => fileRef.current?.click()} style={{ flex: 1, height: 44, borderRadius: 14, background: 'var(--bg-2)', fontWeight: 700, fontSize: 14 }}>Cambia</button>
                <button onClick={removePhoto} style={{ flex: 1, height: 44, borderRadius: 14, background: '#fff', border: '1.5px solid var(--line)', fontWeight: 700, fontSize: 14, color: 'var(--ink-2)' }}>Rimuovi</button>
              </div>
            </div>
          )}
          <input ref={fileRef} type="file" accept="image/*" onChange={onPick} style={{ display: 'none' }} />
        </div>

        <div style={{ marginTop: 18, padding: '12px 14px', background: '#FFF6E8', borderRadius: 14, fontSize: 12, color: 'var(--ink-2)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <div style={{ fontSize: 16, lineHeight: 1 }}>💡</div>
          <div>Per usare un personaggio dei cartoni (Bing, Peppa, ecc.) basta caricare una sua immagine dal telefono.</div>
        </div>
        <div style={{ height: 16 }} />
      </div>

      <CTAFooter>
        <button className="btn-primary" onClick={next} style={{ width: '100%' }}>
          {state.photo ? 'Avanti' : 'Salta · senza foto'}
        </button>
      </CTAFooter>
    </div>
  );
}

Object.assign(window, {
  WelcomeScreen, NomeScreen, EtaScreen, FotoScreen, TemaScreen, DettagliScreen, GeneratingScreen,
  ScreenHeader, CTAFooter, Bullet,
});
