// pages.jsx — all routed pages for the Per Tullia site

// Steps shown in the progress dots (gate is pre-flow)
const FLOW = ['lettera', 'chi-sei', 'da-chi', 'messaggio', 'regalo', 'grazie'];

// shared little helper
function Eyebrow({ children, color = T.inkMuted }) {
  return (
    <div style={{
      fontFamily: T.sans, fontSize: 11, letterSpacing: 1.8,
      textTransform: 'uppercase', color,
    }}>{children}</div>
  );
}

function H1({ children, italic, color = T.ink, style = {} }) {
  return (
    <h1 style={{
      fontFamily: T.serif,
      fontSize: 'clamp(40px, 7vw, 76px)',
      lineHeight: 1.0,
      color, margin: 0, letterSpacing: -1,
      fontStyle: italic ? 'italic' : 'normal',
      ...style,
    }}>{children}</h1>
  );
}

function H2({ children, italic, color = T.ink, style = {} }) {
  return (
    <h2 style={{
      fontFamily: T.serif,
      fontSize: 'clamp(30px, 4.6vw, 50px)',
      lineHeight: 1.05,
      color, margin: 0, letterSpacing: -0.5,
      fontStyle: italic ? 'italic' : 'normal',
      ...style,
    }}>{children}</h2>
  );
}

// ─────────────────────────────────────────────────────────────
// 0 · Gate (entrance — pre-flow)
// ─────────────────────────────────────────────────────────────
function GatePage({ go }) {
  const [pw, setPw] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  async function enter() {
    if (!pw || busy) return;
    setBusy(true); setErr('');
    try {
      await window.Api.gate(pw);   // verifica la password lato server
      go('lettera');
    } catch (e) {
      setErr('Password non valida. Riprova.');
      setBusy(false);
    }
  }

  return (
    <Page tone="cream">
      {/* animated dachshund wallpaper underlay */}
      <DachshundWallpaper opacity={0.95} size={420} speed={120} />
      {/* soft vignette to make the centered card pop */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1,
        background: 'radial-gradient(60% 50% at 50% 50%, rgba(245,238,223,0.75), rgba(245,238,223,0.2) 60%, transparent 90%)',
      }} />

      <div style={{
        flex: 1, display: 'grid', placeItems: 'center', textAlign: 'center',
        position: 'relative', zIndex: 2,
      }}>
        <div style={{
          maxWidth: 460, width: '100%',
          background: 'rgba(250,246,236,0.88)',
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          padding: 'clamp(28px, 5vw, 48px) clamp(28px, 5vw, 56px)',
          borderRadius: 28,
          border: `1px solid ${T.hairline}`,
          boxShadow: '0 1px 0 rgba(58,36,24,0.04), 0 30px 80px rgba(58,36,24,0.15)',
        }}>
          <Eyebrow>benvenuto nella lista nascita</Eyebrow>
          <div style={{
            marginTop: 8, fontFamily: T.serif, fontStyle: 'italic',
            fontSize: 'clamp(18px, 2.4vw, 22px)', color: T.inkSoft, lineHeight: 1.25,
          }}>
            per la piccola Ferrero El Hamdani
          </div>

          <H1 italic style={{ marginTop: 18, fontSize: 'clamp(56px, 11vw, 104px)' }}>
            ciao.
          </H1>

          <p style={{
            marginTop: 22, fontFamily: T.body, fontSize: 17,
            color: T.inkMuted, lineHeight: 1.55,
          }}>
            Digita la password per entrare.
          </p>

          <div style={{ marginTop: 30 }}>
            <Input
              type="password" value={pw}
              onChange={v => { setPw(v); setErr(''); }}
              onKeyDown={e => { if (e.key === 'Enter') enter(); }}
              placeholder="•  •  •  •  •  •"
              style={{ textAlign: 'center', fontSize: 22, letterSpacing: 8 }}
            />
          </div>

          {err && (
            <div style={{
              marginTop: 16, fontFamily: T.sans, fontSize: 14,
              color: T.terracottaDeep,
            }}>{err}</div>
          )}

          <div style={{ marginTop: 26, display: 'flex', justifyContent: 'center' }}>
            <PrimaryButton onClick={enter} disabled={busy || !pw}>
              {busy ? 'Verifico…' : 'Entra'}
            </PrimaryButton>
          </div>

          <div style={{
            marginTop: 32, fontFamily: T.sans, fontSize: 11, letterSpacing: 1.4,
            color: T.inkFaint, textTransform: 'uppercase',
          }}>
            Omar &nbsp;·&nbsp; Camilla &nbsp;·&nbsp; Tullia
          </div>
        </div>
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// 1 · Lettera — the heart of the site
// Desktop: illustration left, letter right · Mobile: stacked
// ─────────────────────────────────────────────────────────────
function LetteraPage({ go }) {
  const paragraphs = [
    { kind: 'pull',   text: 'La nostra lista nascita. Ma fatta a modo nostro, più una lettera.' },
    { kind: 'body',   text: 'Abbiamo già tante cose. La nonna ne aveva conservate parecchie, e molte ce le avete regalate voi. Per questo abbiamo pensato a una lista un po\u2019 diversa.' },
    { kind: 'body',   text: 'Qui dentro puoi lasciarle un messaggio per quando avrà 18 anni, e se ti va, regalarle un pezzettino di futuro. Niente body, niente tutine, di quelle ne abbiamo già abbastanza per vestire mezzo quartiere.' },
    { kind: 'body',   text: 'Grazie di esserci.' },
  ];

  const [shown, setShown] = React.useState(0);
  React.useEffect(() => {
    const t = paragraphs.map((_, i) =>
      setTimeout(() => setShown(s => Math.max(s, i + 1)), 300 + i * 380)
    );
    return () => t.forEach(clearTimeout);
  }, []);

  return (
    <Page tone="cream">
      <TopBar steps={FLOW} current={0} onBack={() => go('gate')} />

      <div style={{
        flex: 1, display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr)',
        gap: 'clamp(28px, 5vw, 64px)', alignItems: 'center',
      }} className="lettera-grid">

        {/* illustration */}
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <FamilyPhoto rounded={28} />
        </div>

        {/* letter */}
        <article style={{ maxWidth: 540 }}>
          <div style={{
            opacity: shown >= 1 ? 1 : 0,
            transform: shown >= 1 ? 'translateY(0)' : 'translateY(10px)',
            transition: 'opacity 1.2s, transform 1.2s',
            marginBottom: 20,
          }}>
            <Eyebrow>lista nascita · agosto 2026</Eyebrow>
          </div>
          {paragraphs.map((p, i) => {
            const visible = i < shown;
            const transition = 'opacity 1.2s cubic-bezier(.2,.7,.3,1), transform 1.2s cubic-bezier(.2,.7,.3,1)';
            const baseStyle = {
              margin: '0 0 18px',
              opacity: visible ? 1 : 0,
              transform: visible ? 'translateY(0)' : 'translateY(10px)',
              transition,
            };
            if (p.kind === 'hello') {
              return <H1 key={i} italic style={{ ...baseStyle, fontSize: 'clamp(44px, 6vw, 64px)' }}>
                {p.text}
              </H1>;
            }
            if (p.kind === 'pull') {
              return <p key={i} style={{
                ...baseStyle,
                fontFamily: T.serif, fontStyle: 'italic',
                fontSize: 'clamp(24px, 2.5vw, 30px)',
                lineHeight: 1.3, color: T.terracottaDeep,
                marginTop: 6, marginBottom: 22,
                letterSpacing: -0.2,
              }}>{p.text}</p>;
            }
            return <p key={i} style={{
              ...baseStyle,
              fontFamily: T.body, fontSize: 'clamp(16px, 1.4vw, 19px)',
              lineHeight: 1.6, color: T.ink,
            }}>{p.text}</p>;
          })}

          <p style={{
            marginTop: 30,
            fontFamily: T.serif, fontStyle: 'italic',
            fontSize: 'clamp(20px, 1.8vw, 24px)', lineHeight: 1.4,
            color: T.inkSoft,
            opacity: shown >= paragraphs.length ? 1 : 0,
            transition: 'opacity 1.5s',
          }}>
            Omar e Camilla.
          </p>

          <div style={{
            marginTop: 36,
            opacity: shown >= paragraphs.length ? 1 : 0,
            transform: shown >= paragraphs.length ? 'translateY(0)' : 'translateY(10px)',
            transition: 'opacity 1.2s, transform 1.2s',
          }}>
            <PrimaryButton onClick={() => go('chi-sei')}>Entra nella lettera</PrimaryButton>
          </div>
        </article>
      </div>

      {/* end of letter */}
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// 2 · Chi sei?
// ─────────────────────────────────────────────────────────────
function ChiSeiPage({ go, state, setState }) {
  return (
    <Page tone="sky">
      <TopBar steps={FLOW} current={1} onBack={() => go('lettera')} />

      <div style={{
        flex: 1, display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr)', gap: 'clamp(28px, 5vw, 56px)',
        alignItems: 'center',
      }} className="two-col">

        <div>
          <Eyebrow>passo 1</Eyebrow>
          <H1 style={{ marginTop: 14 }}>
            Ci fa piacere<br/>
            sapere chi sei.
          </H1>

          <div style={{ marginTop: 36, maxWidth: 440, display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{
              fontFamily: T.body, fontSize: 'clamp(16px, 1.4vw, 19px)',
              color: T.inkSoft, lineHeight: 1.6,
            }}>
              Scrivi il tuo nome, così sapremo a chi dire grazie.
            </p>

            <Input
              placeholder="Il tuo nome"
              value={state.name || ''}
              onChange={v => setState({ name: v, loginMethod: 'manual' })}
            />

            <div style={{ marginTop: 12 }}>
              <PrimaryButton onClick={() => go('da-chi')} disabled={!state.name}>
                Continua
              </PrimaryButton>
            </div>
          </div>
        </div>

        {/* right column intentionally empty for focus */}

      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// 3 · Da chi viene — Solo o Gruppo
// ─────────────────────────────────────────────────────────────
function DaChiPage({ go, state, setState }) {
  const isGroup = state.kind === 'group';
  const names = state.groupNames || [''];

  function setKind(k) { setState({ kind: k, groupNames: k === 'group' ? names : undefined }); }
  function setName(i, v) {
    const next = [...names]; next[i] = v;
    setState({ groupNames: next });
  }
  function addName() { setState({ groupNames: [...names, ''] }); }
  function removeName(i) {
    const next = names.filter((_, j) => j !== i);
    setState({ groupNames: next.length ? next : [''] });
  }

  const canContinue = state.kind === 'solo' || (isGroup && names.some(n => n.trim()));

  return (
    <Page tone="lilac">
      <TopBar steps={FLOW} current={2} onBack={() => go('chi-sei')} />

      <div style={{ flex: 1, maxWidth: 760, marginInline: 'auto', width: '100%' }}>
        <Eyebrow>passo 2</Eyebrow>
        <H1 style={{ marginTop: 14 }}>
          Da parte tua,<br/>
          <em style={{ fontStyle: 'italic', color: T.lavenderDeep }}>o da parte di tutti?</em>
        </H1>
        <p style={{
          marginTop: 18, fontFamily: T.body, fontSize: 'clamp(16px, 1.4vw, 19px)',
          color: T.inkSoft, lineHeight: 1.6, maxWidth: 540,
        }}>
          Se siete in più persone — colleghi, amici, una famiglia intera — possiamo scrivere tutti i vostri nomi, così quando lo leggerà saprà bene a chi dire grazie.
        </p>

        <div style={{
          marginTop: 32, display: 'grid', gap: 16,
          gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
        }}>
          <KindCard
            selected={state.kind === 'solo'}
            onClick={() => setKind('solo')}
            tone={T.dustyBlue}
            icon={<SingleDachIcon size={120} />}
            title="Solo io"
            sub="Il regalo è da parte mia."
          />
          <KindCard
            selected={state.kind === 'group'}
            onClick={() => setKind('group')}
            tone={T.lavender}
            icon={<GroupDachIcon size={120} />}
            title="Siamo in più"
            sub="Aggiungi tutti i nomi del gruppo."
          />
        </div>

        {isGroup && (
          <div style={{
            marginTop: 28, padding: 'clamp(20px, 3vw, 28px)',
            background: T.paper, borderRadius: 20,
            border: `1px solid ${T.hairline}`,
          }}>
            <Eyebrow>i nomi del gruppo</Eyebrow>
            <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {names.map((n, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                  <span style={{
                    fontFamily: T.serif, fontStyle: 'italic',
                    fontSize: 18, color: T.inkMuted, width: 24,
                  }}>{i + 1}.</span>
                  <div style={{ flex: 1 }}>
                    <Input
                      placeholder={i === 0 ? 'es. Marta Rossi' : 'un altro nome'}
                      value={n} onChange={v => setName(i, v)}
                    />
                  </div>
                  {names.length > 1 && (
                    <button onClick={() => removeName(i)} style={{
                      background: 'transparent', border: 'none',
                      color: T.inkFaint, cursor: 'pointer', padding: 8, fontSize: 18,
                      fontFamily: T.serif, lineHeight: 1,
                    }} title="rimuovi">×</button>
                  )}
                </div>
              ))}
            </div>
            <div style={{ marginTop: 14 }}>
              <TextLink onClick={addName}>+ aggiungi un nome</TextLink>
            </div>
          </div>
        )}

        <div style={{ marginTop: 36, display: 'flex', justifyContent: 'flex-end' }}>
          <PrimaryButton onClick={() => go('messaggio')} disabled={!canContinue}>
            Continua
          </PrimaryButton>
        </div>
      </div>
    </Page>
  );
}

function KindCard({ selected, onClick, tone, icon, title, sub }) {
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', cursor: 'pointer',
      padding: '22px 20px 24px',
      background: selected ? T.paper : 'rgba(255,255,255,0.4)',
      border: `1.5px solid ${selected ? T.coat : T.hairline}`,
      borderRadius: 20, position: 'relative',
      display: 'flex', flexDirection: 'column', gap: 14,
      transition: 'border-color .2s, background .2s, transform .2s',
      transform: selected ? 'translateY(-2px)' : 'translateY(0)',
    }}>
      <div style={{
        position: 'absolute', top: 18, right: 18,
        width: 22, height: 22, borderRadius: 999,
        background: selected ? T.terracotta : 'transparent',
        border: `1.5px solid ${selected ? T.terracotta : T.hairline}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 2,
      }}>
        {selected && <svg width="12" height="10" viewBox="0 0 12 10"><path d="M1 5l3.5 3.5L11 1.5" stroke={T.cream} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </div>
      <div>{icon}</div>
      <div>
        <div style={{ fontFamily: T.serif, fontSize: 24, color: T.ink, letterSpacing: -0.3 }}>{title}</div>
        <div style={{ marginTop: 4, fontFamily: T.body, fontSize: 15, color: T.inkMuted, lineHeight: 1.4 }}>{sub}</div>
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// 4 · Messaggio per lei
// ─────────────────────────────────────────────────────────────
function MessaggioPage({ go, state, setState }) {
  return (
    <Page tone="sunshine">
      <TopBar steps={FLOW} current={3} onBack={() => go('da-chi')} />

      <div style={{ flex: 1, maxWidth: 760, marginInline: 'auto', width: '100%' }}>
        <Eyebrow>passo 3 · un messaggio per lei</Eyebrow>
        <H1 style={{ marginTop: 14 }}>
          La tua lettera<br/>
          <span style={{ color: T.terracottaDeep }}>per il 2044.</span>
        </H1>
        <p style={{
          marginTop: 16, fontFamily: T.body, fontSize: 'clamp(16px, 1.4vw, 19px)',
          color: T.inkSoft, lineHeight: 1.6, maxWidth: 560,
        }}>
          Niente conteggio caratteri, niente pressione. Scrivi come a tavola, come se lei fosse già qui.
        </p>

        {/* prompt 1 */}
        <div style={{ marginTop: 36 }}>
          <Eyebrow>1 di 2 · come immagini il mondo</Eyebrow>
          <H2 style={{ marginTop: 10 }}>
            Quando avrà 18 anni,<br/>
            <span style={{ color: T.terracottaDeep }}>che mondo trova?</span>
          </H2>
          <div style={{ marginTop: 18 }}>
            <PaperArea
              rows={5}
              value={state.world || ''}
              onChange={v => setState({ world: v })}
              placeholder="Spero che ci saranno ancora i bar dove si paga il caffè un euro, e che tu ne troverai uno…"
            />
          </div>
        </div>

        {/* prompt 2 */}
        <div style={{ marginTop: 44 }}>
          <Eyebrow>2 di 2 · un consiglio</Eyebrow>
          <H2 style={{ marginTop: 10 }}>
            Quale consiglio<br/>
            <span style={{ color: T.terracottaDeep }}>vuoi lasciarle?</span>
          </H2>
          <div style={{ marginTop: 18 }}>
            <PaperArea
              rows={5}
              value={state.advice || ''}
              onChange={v => setState({ advice: v })}
              placeholder="Non fidarti di chi parla troppo veloce, e non smettere mai di ballare in cucina…"
            />
          </div>
        </div>

        <div style={{ marginTop: 36, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <TextLink onClick={() => go('regalo')}>Salto, vado al regalo →</TextLink>
          <PrimaryButton onClick={() => go('regalo')}>
            Ho scritto. Avanti.
          </PrimaryButton>
        </div>
      </div>
    </Page>
  );
}

// ─────────────────────────────────────────────────────────────
// 5 · Regalo — direzione + modo (combined)
// ─────────────────────────────────────────────────────────────
const DIRECTIONS = [
  { id: 'ai',    title: 'ETF AI',  body: 'Nvidia, AMD, OpenAI quando si quoterà.', color: 'sage' },
  { id: 'btc',   title: 'Bitcoin',   body: 'Nella prospettiva che arrivi al milione.', color: 'butter' },
  { id: 'robo',  title: 'Robotica',  body: 'ETF specializzati in aziende di physical AI.', color: 'lavender' },
];
const METHODS = [
  { id: 'satispay', title: 'Satispay',         sub: 'Veloce. Apri l’app e via.' },
  { id: 'iban',     title: 'Bonifico (IBAN)',  sub: 'Per chi preferisce il vecchio bonifico.' },
  { id: 'busta',    title: 'Una busta, in mano',sub: 'Ce la dai quando vieni a conoscerla.' },
];

function RegaloPage({ go, state, setState }) {
  const [skip, setSkip] = React.useState(false);

  const amountNum = parseInt(state.amount, 10) || 0;
  const amountOk = amountNum > 0;   // importo libero, nessun minimo
  const canContinue = skip || (state.direction && state.method && amountOk);

  return (
    <Page tone="meadow">
      <TopBar steps={FLOW} current={4} onBack={() => go('messaggio')} />

      <div style={{ flex: 1, width: '100%' }}>
        <div style={{ maxWidth: 760, marginInline: 'auto' }}>
          <Eyebrow>passo 4 · facoltativo</Eyebrow>
          <H1 style={{ marginTop: 14 }}>
            Se ti va,<br/>
            <em style={{ fontStyle: 'italic', color: T.sageDeep }}>un pezzettino di futuro.</em>
          </H1>
          <p style={{
            marginTop: 16, fontFamily: T.body, fontSize: 'clamp(16px, 1.4vw, 19px)',
            color: T.inkSoft, lineHeight: 1.6, maxWidth: 580,
          }}>
            Nessun obbligo. Le tue parole bastano già. Se invece ti va, investiremo noi per lei — scegli soltanto come, e in che direzione.
          </p>

          <div style={{ marginTop: 14 }}>
            <TextLink onClick={() => { setSkip(true); go('grazie'); }}>
              Le mie parole bastano, vado avanti →
            </TextLink>
          </div>
        </div>

        {/* STEP A — direction */}
        <SectionTitle n="A" title="In che direzione" sub="Scegli quella che ti somiglia di più." />
        <div style={{
          display: 'grid', gap: 16, maxWidth: 1100, marginInline: 'auto',
          gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
        }}>
          {DIRECTIONS.map(d => (
            <DirectionCard
              key={d.id}
              dir={d}
              selected={state.direction === d.id}
              onClick={() => setState({ direction: d.id })}
            />
          ))}
        </div>

        {/* STEP B — method */}
        <SectionTitle n="B" title="Come vuoi farlo" sub="Tre modi, tutti tranquilli." />
        <div style={{
          display: 'grid', gap: 12, maxWidth: 760, marginInline: 'auto',
        }}>
          {METHODS.map(m => (
            <MethodRow
              key={m.id}
              method={m}
              selected={state.method === m.id}
              onClick={() => setState({ method: m.id })}
            />
          ))}
        </div>

        {/* STEP C — amount (free input only) */}
        <SectionTitle n="C" title="Quanto" sub="Importo libero, quello che ti va." />
        <div style={{ maxWidth: 760, marginInline: 'auto' }}>
          <div style={{
            display: 'flex', alignItems: 'baseline', gap: 10,
            maxWidth: 320,
            borderBottom: `1px solid ${T.hairline}`,
          }}>
            <span style={{
              fontFamily: T.serif, fontSize: 34, color: T.inkSoft, lineHeight: 1,
            }}>€</span>
            <input
              type="text" inputMode="numeric"
              placeholder="0"
              value={state.amount || ''}
              onChange={e => setState({ amount: e.target.value.replace(/[^\d]/g, '') })}
              style={{
                flex: 1, width: '100%', padding: '10px 2px',
                background: 'transparent', border: 'none', outline: 'none',
                fontFamily: T.serif, fontSize: 34, color: T.ink, letterSpacing: 0.2,
              }}
            />
          </div>
        </div>

        <div style={{
          maxWidth: 760, marginInline: 'auto', marginTop: 36,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16,
        }}>
          <TextLink onClick={() => go('grazie')}>Salto, vado avanti →</TextLink>
          <PrimaryButton onClick={() => go('grazie')} disabled={!canContinue}>
            Conferma il regalo
          </PrimaryButton>
        </div>
      </div>
    </Page>
  );
}

function SectionTitle({ n, title, sub }) {
  return (
    <div style={{
      marginTop: 48, marginBottom: 18, maxWidth: 760, marginInline: 'auto',
      display: 'flex', alignItems: 'baseline', gap: 14,
    }}>
      <span style={{
        fontFamily: T.serif, fontStyle: 'italic', fontSize: 32,
        color: T.terracottaDeep, lineHeight: 1,
      }}>{n}.</span>
      <div>
        <H2 style={{ fontSize: 'clamp(24px, 3vw, 32px)' }}>{title}</H2>
        {sub && <div style={{
          marginTop: 4, fontFamily: T.body, fontStyle: 'italic',
          fontSize: 16, color: T.inkMuted,
        }}>{sub}</div>}
      </div>
    </div>
  );
}

function DirectionCard({ dir, selected, onClick }) {
  const accent = T[dir.color];
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', cursor: 'pointer', position: 'relative',
      padding: '22px 22px 26px',
      background: selected ? T.paper : 'rgba(255,255,255,0.5)',
      border: `1.5px solid ${selected ? T.coat : T.hairline}`,
      borderRadius: 22, overflow: 'hidden',
      transition: 'border-color .2s, background .2s, transform .2s',
      transform: selected ? 'translateY(-3px)' : 'translateY(0)',
      boxShadow: selected ? '0 12px 24px rgba(58,36,24,0.08)' : 'none',
    }}>
      <div style={{
        position: 'absolute', right: -10, top: -10,
        width: 70, height: 70, borderRadius: 999, background: accent, opacity: 0.65,
      }} />
      <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <DirectionIcon id={dir.id} />
        <div style={{
          width: 22, height: 22, borderRadius: 999,
          background: selected ? T.terracotta : 'transparent',
          border: `1.5px solid ${selected ? T.terracotta : T.hairline}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {selected && <svg width="12" height="10" viewBox="0 0 12 10"><path d="M1 5l3.5 3.5L11 1.5" stroke={T.cream} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
        </div>
      </div>
      <div style={{ position: 'relative', marginTop: 18, fontFamily: T.sans, fontSize: 11, letterSpacing: 1.6, textTransform: 'uppercase', color: T.inkMuted }}>
        direzione
      </div>
      <div style={{ position: 'relative', marginTop: 4, fontFamily: T.serif, fontSize: 25, lineHeight: 1.1, color: T.ink, letterSpacing: -0.3 }}>
        {dir.title}
      </div>
      <div style={{ position: 'relative', marginTop: 8, fontFamily: T.body, fontSize: 15, color: T.inkSoft, lineHeight: 1.5 }}>
        {dir.body}
      </div>
    </button>
  );
}

function DirectionIcon({ id }) {
  if (id === 'ai') return (
    <svg width="48" height="48" viewBox="0 0 60 60">
      <rect x="12" y="32" width="36" height="22" rx="2" fill="none" stroke={T.ink} strokeWidth="1.4" />
      <path d="M14 36 H 46 M14 40 H 46 M14 44 H 46 M14 48 H 46" stroke={T.inkFaint} strokeWidth="0.6" />
      <path d="M30 32 Q 30 20, 30 12" stroke={T.sageDeep} strokeWidth="1.4" fill="none" strokeLinecap="round" />
      <ellipse cx="22" cy="20" rx="7" ry="3.5" fill={T.sage} transform="rotate(-25 22 20)" />
      <ellipse cx="38" cy="16" rx="7" ry="3.5" fill={T.sage} transform="rotate(25 38 16)" />
      <ellipse cx="30" cy="8" rx="6" ry="3" fill={T.sage} />
    </svg>
  );
  if (id === 'btc') return (
    <svg width="48" height="48" viewBox="0 0 60 60">
      <ellipse cx="30" cy="34" rx="20" ry="22" fill={T.butter} />
      <ellipse cx="30" cy="34" rx="20" ry="22" fill="none" stroke={T.ink} strokeWidth="1.4" />
      <path d="M30 14 Q 36 32, 30 56 Q 24 32, 30 14 Z" fill="none" stroke={T.ink} strokeWidth="1" opacity="0.5" />
      <path d="M30 14 Q 30 8, 26 6" stroke={T.sageDeep} strokeWidth="1.4" fill="none" strokeLinecap="round" />
      <path d="M30 14 Q 30 9, 34 8" stroke={T.sageDeep} strokeWidth="1.4" fill="none" strokeLinecap="round" />
    </svg>
  );
  return (
    <svg width="48" height="48" viewBox="0 0 60 60">
      <rect x="18" y="32" width="24" height="22" rx="3" fill="none" stroke={T.ink} strokeWidth="1.4" />
      <line x1="22" y1="32" x2="22" y2="22" stroke={T.ink} strokeWidth="1.4" />
      <line x1="30" y1="32" x2="30" y2="20" stroke={T.ink} strokeWidth="1.4" />
      <line x1="38" y1="32" x2="38" y2="22" stroke={T.ink} strokeWidth="1.4" />
      <circle cx="22" cy="22" r="1.5" fill={T.ink} />
      <circle cx="30" cy="20" r="1.5" fill={T.ink} />
      <circle cx="38" cy="22" r="1.5" fill={T.ink} />
      <circle cx="30" cy="12" r="3" fill={T.terracotta} />
      <circle cx="26" cy="10" r="3" fill={T.lavender} />
      <circle cx="34" cy="10" r="3" fill={T.lavender} />
      <circle cx="30" cy="8" r="3" fill={T.butter} />
      <line x1="30" y1="14" x2="30" y2="20" stroke={T.sageDeep} strokeWidth="1.4" />
    </svg>
  );
}

function MethodRow({ method, selected, onClick }) {
  return (
    <button onClick={onClick} style={{
      cursor: 'pointer', textAlign: 'left',
      padding: '18px 20px',
      background: selected ? T.paper : 'rgba(255,255,255,0.45)',
      border: `1.5px solid ${selected ? T.coat : T.hairline}`,
      borderRadius: 18,
      display: 'flex', alignItems: 'center', gap: 14,
      transition: 'all .2s',
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 999,
        background: selected ? T.terracotta : 'transparent',
        border: `1.5px solid ${selected ? T.terracotta : T.hairline}`,
        flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {selected && <svg width="12" height="10" viewBox="0 0 12 10"><path d="M1 5l3.5 3.5L11 1.5" stroke={T.cream} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: T.serif, fontSize: 22, color: T.ink, letterSpacing: -0.2 }}>{method.title}</div>
        <div style={{ marginTop: 2, fontFamily: T.body, fontSize: 14, color: T.inkMuted }}>{method.sub}</div>
      </div>
      <MethodGlyph id={method.id} />
    </button>
  );
}

function MethodGlyph({ id }) {
  if (id === 'satispay') return (
    <div style={{
      width: 38, height: 38, borderRadius: 12, background: T.terracotta,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: T.cream, fontFamily: T.serif, fontStyle: 'italic', fontSize: 20,
    }}>S</div>
  );
  if (id === 'iban') return (
    <div style={{
      width: 38, height: 38, borderRadius: 12, background: T.dustyBlue,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <svg width="20" height="20" viewBox="0 0 26 26"><path d="M3 10 L13 4 L23 10 L23 12 L3 12 Z" fill={T.cream}/><rect x="5" y="13" width="2" height="7" fill={T.cream}/><rect x="10" y="13" width="2" height="7" fill={T.cream}/><rect x="15" y="13" width="2" height="7" fill={T.cream}/><rect x="20" y="13" width="2" height="7" fill={T.cream}/><rect x="3" y="21" width="20" height="2" fill={T.cream}/></svg>
    </div>
  );
  return (
    <div style={{
      width: 38, height: 38, borderRadius: 12, background: T.sage,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <svg width="20" height="16" viewBox="0 0 26 20"><rect x="1" y="2" width="24" height="16" rx="2" fill="none" stroke={T.cream} strokeWidth="1.5"/><path d="M1 4 L13 12 L25 4" fill="none" stroke={T.cream} strokeWidth="1.5" strokeLinejoin="round"/></svg>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 6 · Grazie
// ─────────────────────────────────────────────────────────────

// Riquadro con un dato da pagamento (IBAN o handle Satispay) + tasto copia
function PayBox({ label, value, sub, mono = false }) {
  const [copied, setCopied] = React.useState(false);
  function copy() {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(value).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 1600);
      }).catch(() => {});
    }
  }
  return (
    <div style={{
      marginTop: 24, padding: '18px 22px',
      background: T.paper, borderRadius: 18, border: `1px solid ${T.hairline}`,
      display: 'inline-block', textAlign: 'left', maxWidth: '100%',
    }}>
      <Eyebrow>{label}</Eyebrow>
      <div style={{ marginTop: 10, display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
        <span style={{
          fontFamily: mono ? 'ui-monospace, Menlo, monospace' : T.serif,
          fontSize: mono ? 17 : 22, color: T.ink, letterSpacing: mono ? 0.6 : 0,
          wordBreak: 'break-all',
        }}>{value}</span>
        <button onClick={copy} style={{
          background: 'transparent', border: `1px solid ${T.hairline}`,
          borderRadius: 999, padding: '6px 14px', cursor: 'pointer',
          fontFamily: T.sans, fontSize: 13, color: T.inkSoft,
        }}>{copied ? 'copiato ✓' : 'copia'}</button>
      </div>
      {sub && (
        <div style={{ marginTop: 8, fontFamily: T.body, fontSize: 14, color: T.inkMuted }}>
          {sub}
        </div>
      )}
    </div>
  );
}

// Riquadro Satispay: il valore è un link alla pagina con il QR.
// Mostriamo un pulsante "Apri Satispay" (non l'URL grezzo) + copia link.
function SatispayBox({ link }) {
  const [copied, setCopied] = React.useState(false);
  function copy() {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(link).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 1600);
      }).catch(() => {});
    }
  }
  return (
    <div style={{
      marginTop: 24, padding: '18px 22px',
      background: T.paper, borderRadius: 18, border: `1px solid ${T.hairline}`,
      display: 'inline-block', textAlign: 'left', maxWidth: '100%',
    }}>
      <Eyebrow>Manda il regalo su Satispay</Eyebrow>
      <div style={{ marginTop: 12, display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <a href={link} target="_blank" rel="noopener noreferrer" style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,
          padding: '14px 24px', background: T.terracotta, color: T.cream,
          fontFamily: T.sans, fontSize: 16, fontWeight: 500, letterSpacing: 0.3,
          borderRadius: 999, textDecoration: 'none',
          boxShadow: '0 8px 22px rgba(168,101,79,0.18)',
        }}>
          <span style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 18 }}>S</span>
          Apri Satispay
        </a>
        <button onClick={copy} style={{
          background: 'transparent', border: `1px solid ${T.hairline}`,
          borderRadius: 999, padding: '10px 16px', cursor: 'pointer',
          fontFamily: T.sans, fontSize: 13, color: T.inkSoft,
        }}>{copied ? 'link copiato ✓' : 'copia link'}</button>
      </div>
      <div style={{ marginTop: 8, fontFamily: T.body, fontSize: 14, color: T.inkMuted }}>
        Si apre la pagina Satispay con il QR da inquadrare.
      </div>
    </div>
  );
}

function GraziePage({ go, state }) {
  const [saveErr, setSaveErr] = React.useState('');
  const gift = window.Api.gift();   // IBAN/Satispay consegnati dal server dopo il gate

  // Invio dei dati raccolti. L'id è unico per la sessione: se l'utente torna
  // indietro e rientra, il record viene aggiornato (non duplicato).
  React.useEffect(() => {
    let alive = true;
    window.Api.submit(state).catch(() => {
      if (alive) setSaveErr('Non sono riuscito a salvare online. Controlla la connessione: i tuoi dati restano comunque su questo dispositivo.');
    });
    return () => { alive = false; };
  }, []);

  return (
    <Page tone="blossom">
      <TopBar steps={FLOW} current={5} onBack={() => go('regalo')} />

      <div style={{ flex: 1, textAlign: 'center', maxWidth: 720, marginInline: 'auto', width: '100%' }}>
        <div style={{
          position: 'relative', height: 180,
          display: 'flex', justifyContent: 'center', alignItems: 'center',
          marginTop: 12,
        }}>
          <Flower size={92} petal={T.lavender} center={T.butter}
            style={{ position: 'absolute', left: '15%', top: 28, animation: 'sway 7s ease-in-out infinite' }} />
          <Flower size={68} petal={T.terracotta} center={T.butter}
            style={{ position: 'absolute', right: '20%', top: 8, animation: 'sway 8s ease-in-out infinite reverse' }} />
          <Flower size={120} petal={T.dustyBlue} center={T.butter}
            style={{ animation: 'sway 9s ease-in-out infinite' }} />
          <Flower size={56} petal={T.sage} center={T.butter}
            style={{ position: 'absolute', left: '32%', bottom: -4, animation: 'sway 6s ease-in-out infinite' }} />
          <Flower size={64} petal={T.butter} center={T.terracotta}
            style={{ position: 'absolute', right: '32%', bottom: 4, animation: 'sway 10s ease-in-out infinite reverse' }} />
          <Bird size={32} color={T.inkSoft}
            style={{ position: 'absolute', top: -10, right: '10%' }} />
        </div>

        <H1 italic style={{
          marginTop: 20, fontSize: 'clamp(60px, 12vw, 120px)',
          color: T.ink,
        }}>grazie.</H1>

        {/* recap */}
        {(state.direction || state.amount) && (
          <div style={{
            marginTop: 28, padding: '20px 24px',
            background: T.paper, borderRadius: 18,
            border: `1px solid ${T.hairline}`,
            display: 'inline-block', textAlign: 'left',
            maxWidth: '100%',
          }}>
            <Eyebrow>il tuo regalo</Eyebrow>
            <div style={{ marginTop: 8, display: 'flex', gap: 14, alignItems: 'baseline', flexWrap: 'wrap' }}>
              {state.amount && (
                <span style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 28, color: T.ink }}>
                  € {state.amount}
                </span>
              )}
              {state.direction && (
                <span style={{ fontFamily: T.body, fontSize: 15, color: T.inkSoft }}>
                  verso <em style={{ fontStyle: 'italic', color: T.terracottaDeep }}>
                    {DIRECTIONS.find(d => d.id === state.direction)?.title}
                  </em>
                </span>
              )}
              {state.method && (
                <span style={{ fontFamily: T.body, fontSize: 15, color: T.inkMuted }}>
                  · {METHODS.find(m => m.id === state.method)?.title}
                </span>
              )}
            </div>
          </div>
        )}

        {/* Come completare il regalo (solo se è stato scelto un metodo) */}
        {state.method === 'iban' && gift.iban && (
          <PayBox label="Per il bonifico, questo è l’IBAN" value={gift.iban}
                  sub="Intestato a Camilla Ferrero" mono />
        )}
        {state.method === 'satispay' && gift.satispay && (
          <SatispayBox link={gift.satispay} />
        )}

        {saveErr && (
          <div style={{
            marginTop: 20, fontFamily: T.sans, fontSize: 13, color: T.terracottaDeep,
            maxWidth: 520, marginInline: 'auto', lineHeight: 1.5,
          }}>{saveErr}</div>
        )}

        <div style={{
          marginTop: 36, padding: 24, borderRadius: 22,
          background: 'rgba(168,184,158,0.22)',
        }}>
          <Eyebrow>il gioco delle previsioni</Eyebrow>
          <div style={{
            marginTop: 10, fontFamily: T.serif, fontStyle: 'italic',
            fontSize: 'clamp(18px, 2vw, 24px)', color: T.ink, lineHeight: 1.3,
          }}>
            Quando avrà 18 anni rileggeremo tutto insieme.<br/>
            Chi avrà visto più lontano, avrà un piccolo premio da parte nostra.
          </div>
        </div>

        <div style={{
          marginTop: 40, fontFamily: T.serif, fontStyle: 'italic',
          fontSize: 'clamp(20px, 2.4vw, 26px)', color: T.ink, lineHeight: 1.4,
          maxWidth: 560, marginInline: 'auto',
        }}>
          Grazie per la tua generosità.<br/>
          Qualunque cosa tu le abbia lasciato — parole o un pezzettino di
          futuro — ci scalda il cuore. 🤍
        </div>

        <div style={{
          marginTop: 28, fontFamily: T.serif, fontStyle: 'italic',
          fontSize: 18, color: T.inkSoft,
        }}>
          Omar e Camilla.
        </div>
      </div>

      {/* end of grazie */}
    </Page>
  );
}

Object.assign(window, {
  FLOW,
  GatePage, LetteraPage, ChiSeiPage, DaChiPage, MessaggioPage, RegaloPage, GraziePage,
});
