// memories.jsx — MemoriesPage, CirclePage, BequestsPage, ProfilePage
// t, useState etc. available from components.jsx (loaded first)

// ─── MemoryDrawer ─────────────────────────────────────────────────────────────
function MemoryDrawer({ memory, people, onClose, onSave }) {
  const isNew = !memory.id;
  const [editing, setEditing] = useState(isNew);
  const [kind, setKind] = useState(memory.kind || 'letter');
  const [title, setTitle] = useState(memory.title || '');
  const [body, setBody] = useState(memory.body || '');
  const [assignees, setAssignees] = useState(memory.assignees || []);

  const kindOptions = [
    { id: 'letter', label: t.memories.kinds.letter, icon: 'letter' },
    { id: 'audio', label: t.memories.kinds.audio, icon: 'audio' },
    { id: 'photo', label: t.memories.kinds.photo, icon: 'photo' },
    { id: 'video', label: t.memories.kinds.video, icon: 'video' },
    { id: 'doc', label: t.memories.kinds.doc, icon: 'doc' },
  ];

  const kindClass = { letter: 'mem-letter', audio: 'mem-audio', photo: 'mem-photo', video: 'mem-video', doc: 'mem-doc' };
  const kindIconColor = { letter: 'var(--ink)', audio: '#fff', photo: 'var(--jade-800)', video: '#fff', doc: 'var(--gr-500)' };
  const cls = kindClass[kind] || 'mem-doc';
  const iconColor = kindIconColor[kind] || 'var(--ink)';

  function toggleAssignee(id) {
    setAssignees(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  }

  function handleSave() {
    onSave({
      ...memory,
      id: memory.id || ('m' + Date.now()),
      kind,
      title,
      body,
      assignees,
      date: memory.date || new Date().toISOString().split('T')[0],
    });
    onClose();
  }

  const assignedPeople = assignees.map(id => people.find(p => p.id === id)).filter(Boolean);

  return (
    <>
      <div className="backdrop" onClick={onClose} />
      <div className="drawer fade-in">
        {/* Colored cover at top */}
        <div className={`mem-drawer-cover ${cls}`}>
          <div className="row" style={{ justifyContent: 'space-between', position: 'relative', zIndex: 1 }}>
            <span className="kind-tag">
              <Icon name={kind} size={11} />
              {t.memories.kinds[kind]}
            </span>
            <button
              className="btn btn-ghost btn-icon"
              onClick={onClose}
              style={{ padding: 6, opacity: 0.55 }}
            >
              <Icon name="close" size={18} />
            </button>
          </div>
          {/* Large centered icon */}
          <div style={{
            position: 'absolute', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)',
            opacity: 0.14, pointerEvents: 'none',
          }}>
            <Icon name={kind} size={88} color={iconColor} />
          </div>
          {/* Letter preview inside cover */}
          {!editing && kind === 'letter' && body && (
            <div style={{
              position: 'absolute', bottom: 16, left: 24, right: 24,
              fontFamily: 'var(--f-serif)', fontStyle: 'italic',
              fontSize: 12, lineHeight: 1.6, color: 'var(--ink)', opacity: 0.6,
              overflow: 'hidden', display: '-webkit-box',
              WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
            }}>
              {body}
            </div>
          )}
        </div>

        <div className="drawer-body">
          {/* Kind selector (edit/new only) */}
          {editing && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '.1em', marginBottom: 8 }}>Tipo</div>
              <div className="row" style={{ flexWrap: 'wrap', gap: 6 }}>
                {kindOptions.map(k => (
                  <button
                    key={k.id}
                    className={kind === k.id ? 'chip chip-solid' : 'chip'}
                    style={{ cursor: 'pointer', border: 'none' }}
                    onClick={() => setKind(k.id)}
                  >
                    <Icon name={k.icon} size={12} color={kind === k.id ? '#fff' : 'var(--ink-muted)'} />
                    {k.label}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Title */}
          {editing ? (
            <input
              className="input"
              placeholder="Titolo della memoria"
              value={title}
              onChange={e => setTitle(e.target.value)}
              style={{ marginBottom: 12, fontSize: 15, fontWeight: 500 }}
              autoFocus={isNew}
            />
          ) : (
            <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--ink)', marginBottom: 4, lineHeight: 1.25 }}>
              {title}
            </div>
          )}

          {/* Date (view) */}
          {!editing && memory.date && (
            <div className="t-mono" style={{ marginBottom: 16 }}>
              {new Date(memory.date).toLocaleDateString('it-IT', { year: 'numeric', month: 'long', day: 'numeric' })}
            </div>
          )}

          {/* Body textarea (edit) */}
          {editing && (kind === 'letter' || kind === 'doc') && (
            <textarea
              className="input"
              placeholder={kind === 'letter' ? 'Scrivi la tua lettera...' : 'Descrizione o note...'}
              value={body}
              onChange={e => setBody(e.target.value)}
              style={{
                minHeight: 140, resize: 'vertical', lineHeight: 1.7, marginBottom: 16,
                fontFamily: kind === 'letter' ? 'var(--f-serif)' : 'inherit',
                fontStyle: kind === 'letter' ? 'italic' : 'normal',
              }}
            />
          )}

          {/* Letter body (view) */}
          {!editing && kind === 'letter' && body && (
            <div style={{
              fontFamily: 'var(--f-serif)', fontStyle: 'italic',
              fontSize: 15, lineHeight: 1.8, color: 'var(--ink)',
              marginBottom: 20, whiteSpace: 'pre-line',
              borderLeft: '3px solid var(--line)', paddingLeft: 16,
            }}>
              {body}
            </div>
          )}

          {/* Duration (audio/video) */}
          {!editing && (kind === 'audio' || kind === 'video') && memory.duration && (
            <div style={{ fontFamily: 'var(--f-mono)', fontSize: 28, color: 'var(--ink)', marginBottom: 16, fontWeight: 500 }}>
              {memory.duration}
            </div>
          )}

          {/* Photo count */}
          {!editing && kind === 'photo' && memory.count && (
            <div style={{ fontSize: 15, color: 'var(--ink-muted)', marginBottom: 16 }}>
              {memory.count} foto
            </div>
          )}

          <hr className="divider" style={{ margin: '16px 0' }} />

          {/* Assignees */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '.1em', marginBottom: 10 }}>
              Per chi
            </div>
            {editing ? (
              <div className="people-picker">
                {people.map(p => {
                  const sel = assignees.includes(p.id);
                  return (
                    <div
                      key={p.id}
                      className={`people-picker-item${sel ? ' selected' : ''}`}
                      onClick={() => toggleAssignee(p.id)}
                    >
                      <Monogram initials={p.initials} color={p.color} size="sm" />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{p.name}</div>
                        <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{p.rel}</div>
                      </div>
                      {sel && (
                        <div style={{ width: 20, height: 20, borderRadius: '50%', background: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <Icon name="check" size={11} color="#fff" strokeWidth={2.5} />
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : assignedPeople.length > 0 ? (
              <div className="col" style={{ gap: 10 }}>
                {assignedPeople.map(p => (
                  <div key={p.id} className="row" style={{ gap: 10 }}>
                    <Monogram initials={p.initials} color={p.color} size="sm" />
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{p.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{p.rel}</div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ fontSize: 13, color: 'var(--ink-muted)', fontStyle: 'italic' }}>
                Nessuna persona assegnata
              </div>
            )}
          </div>
        </div>

        <div className="drawer-footer">
          {editing ? (
            <>
              <button className="btn btn-secondary" onClick={isNew ? onClose : () => setEditing(false)}>
                {t.common.cancel}
              </button>
              <button
                className="btn btn-primary"
                onClick={handleSave}
                disabled={!title.trim()}
                style={{ opacity: title.trim() ? 1 : 0.45 }}
              >
                <Icon name="check" size={15} color="#fff" />
                {isNew ? 'Salva memoria' : 'Salva modifiche'}
              </button>
            </>
          ) : (
            <>
              <button className="btn btn-secondary" onClick={onClose}>{t.common.cancel}</button>
              <button className="btn btn-secondary" onClick={() => setEditing(true)}>
                <Icon name="edit" size={14} />
                Modifica
              </button>
            </>
          )}
        </div>
      </div>
    </>
  );
}

// ─── MemoriesPage ─────────────────────────────────────────────────────────────
function MemoriesPage({ data, onUpdate }) {
  const seed = data || DOPO.SEED;
  const { memories, people } = seed;
  const [kindFilter, setKindFilter] = useState('all');
  const [detailMemory, setDetailMemory] = useState(null);
  const [showNew, setShowNew] = useState(false);

  function saveMemory(updated) {
    onUpdate(d => ({
      ...d,
      memories: d.memories.some(m => m.id === updated.id)
        ? d.memories.map(m => m.id === updated.id ? updated : m)
        : [...d.memories, updated],
    }));
  }

  const kinds = [
    { id: 'all', label: 'Tutte' },
    { id: 'letter', label: t.memories.kinds.letter, icon: 'letter' },
    { id: 'audio', label: t.memories.kinds.audio, icon: 'audio' },
    { id: 'photo', label: t.memories.kinds.photo, icon: 'photo' },
    { id: 'video', label: t.memories.kinds.video, icon: 'video' },
    { id: 'doc', label: t.memories.kinds.doc, icon: 'doc' },
  ];

  const kindClass = { letter: 'mem-letter', audio: 'mem-audio', photo: 'mem-photo', video: 'mem-video', doc: 'mem-doc' };
  const kindIconColor = { letter: 'var(--ink)', audio: '#fff', photo: 'var(--jade-800)', video: '#fff', doc: 'var(--gr-500)' };

  const filtered = kindFilter === 'all' ? memories : memories.filter(m => m.kind === kindFilter);

  return (
    <div className="fade-in">
      <PageHeader
        eyebrow="dopo.me"
        title={t.memories.title}
        subtitle={t.memories.sub}
        actions={
          <button className="btn btn-primary" onClick={() => setShowNew(true)}>
            <Icon name="plus" size={15} color="#fff" />
            {t.memories.add}
          </button>
        }
      />

      {/* Kind filter chips */}
      <div className="row" style={{ flexWrap: 'wrap', gap: 8, marginBottom: 28 }}>
        {kinds.map(k => (
          <button
            key={k.id}
            className={`chip${kindFilter === k.id ? ' chip-solid' : ''}`}
            style={{ cursor: 'pointer', border: 'none' }}
            onClick={() => setKindFilter(k.id)}
          >
            {k.icon && <Icon name={k.icon} size={13} color={kindFilter === k.id ? '#fff' : 'var(--ink-muted)'} />}
            {k.label}
            <span style={{ fontSize: 11, opacity: 0.6, marginLeft: 2 }}>
              {k.id === 'all' ? memories.length : memories.filter(m => m.kind === k.id).length}
            </span>
          </button>
        ))}
      </div>

      {/* Memory grid */}
      <div className="mem-grid">
        {filtered.map(m => {
          const cls = kindClass[m.kind] || 'mem-doc';
          const iconColor = kindIconColor[m.kind] || 'var(--ink)';
          const label = t.memories.kinds[m.kind] || m.kind;
          const assignedPeople = m.assignees.map(id => people.find(p => p.id === id)).filter(Boolean);

          return (
            <div key={m.id} className="mem-card" onClick={() => setDetailMemory(m)}>
              <div className={`mem-card-cover ${cls}`} style={{ padding: 16 }}>
                {/* Kind tag */}
                <div style={{ position: 'relative', zIndex: 1 }}>
                  <span className="kind-tag">
                    <Icon name={m.kind} size={11} />
                    {label}
                  </span>
                </div>

                {/* Large centered icon */}
                <div style={{
                  position: 'absolute', top: '50%', left: '50%',
                  transform: 'translate(-50%, -50%)',
                  opacity: 0.14, pointerEvents: 'none',
                }}>
                  <Icon name={m.kind} size={72} color={iconColor} />
                </div>

                {/* Letter preview */}
                {m.kind === 'letter' && (
                  <div style={{
                    position: 'absolute', bottom: 16, left: 16, right: 16,
                    fontFamily: 'var(--f-serif)', fontStyle: 'italic',
                    fontSize: 12, lineHeight: 1.55, color: 'var(--ink)', opacity: 0.65,
                    overflow: 'hidden', display: '-webkit-box',
                    WebkitLineClamp: 4, WebkitBoxOrient: 'vertical',
                  }}>
                    {m.body}
                  </div>
                )}

                {/* Audio duration */}
                {m.kind === 'audio' && (
                  <div style={{ position: 'absolute', bottom: 16, left: 16 }}>
                    <div style={{ fontFamily: 'var(--f-mono)', fontSize: 20, fontWeight: 500, color: '#fff' }}>
                      {m.duration}
                    </div>
                  </div>
                )}

                {/* Video duration */}
                {m.kind === 'video' && (
                  <div style={{ position: 'absolute', bottom: 16, left: 16 }}>
                    <div style={{ fontFamily: 'var(--f-mono)', fontSize: 18, fontWeight: 500, color: '#fff' }}>
                      {m.duration}
                    </div>
                  </div>
                )}

                {/* Photo count */}
                {m.kind === 'photo' && (
                  <div style={{ position: 'absolute', bottom: 16, left: 16 }}>
                    <span style={{ fontSize: 13, color: '#fff', fontWeight: 600 }}>{m.count} foto</span>
                  </div>
                )}

                {/* Doc label */}
                {m.kind === 'doc' && (
                  <div style={{ position: 'absolute', bottom: 16, left: 16 }}>
                    <span style={{ fontSize: 11, color: 'var(--gr-500)', fontFamily: 'var(--f-mono)' }}>PDF</span>
                  </div>
                )}

                {/* Assignees */}
                {assignedPeople.length > 0 && (
                  <div style={{ position: 'absolute', bottom: 16, right: 16 }}>
                    <MonoStack ids={m.assignees} people={people} max={2} />
                  </div>
                )}
              </div>

              <div className="mem-card-meta">
                <div className="mem-card-title">{m.title}</div>
                <div className="mem-card-sub">
                  {assignedPeople.length > 0 && (
                    <span>{t.memories.for_} {assignedPeople.map(p => p.name.split(' ')[0]).join(', ')} · </span>
                  )}
                  {new Date(m.date).toLocaleDateString('it-IT', { year: 'numeric', month: 'short' })}
                </div>
              </div>
            </div>
          );
        })}

        {/* Add new card */}
        <div className="mem-card mem-card-new" onClick={() => setShowNew(true)}>
          <div className="mem-card-cover mem-card-new-cover">
            <div style={{
              width: 44, height: 44, borderRadius: '50%',
              background: 'var(--paper-2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="plus" size={22} color="var(--ink-muted)" />
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-muted)', textAlign: 'center' }}>
              {t.memories.add}
            </div>
          </div>
          <div className="mem-card-meta">
            <div className="mem-card-title" style={{ color: 'var(--ink-muted)' }}>Nuova memoria</div>
          </div>
        </div>
      </div>

      {/* Detail drawer */}
      {detailMemory && (
        <MemoryDrawer
          memory={detailMemory}
          people={people}
          onClose={() => setDetailMemory(null)}
          onSave={saveMemory}
        />
      )}

      {/* New memory drawer */}
      {showNew && (
        <MemoryDrawer
          memory={{}}
          people={people}
          onClose={() => setShowNew(false)}
          onSave={saveMemory}
        />
      )}
    </div>
  );
}

// ─── CirclePage ──────────────────────────────────────────────────────────────
function CirclePage({ data }) {
  const seed = data || DOPO.SEED;
  const { people, services, assets, memories } = seed;

  function getPersonCounts(personId) {
    const svcCount = services.filter(s => s.assignees.includes(personId)).length;
    const astCount = assets.filter(a => a.assignees.includes(personId)).length;
    const memCount = memories.filter(m => m.assignees.includes(personId)).length;
    return svcCount + astCount + memCount;
  }

  return (
    <div className="fade-in">
      <PageHeader
        eyebrow="dopo.me"
        title={t.circle.title}
        subtitle={t.circle.sub}
        actions={
          <button className="btn btn-primary">
            <Icon name="plus" size={15} color="#fff" />
            {t.circle.add}
          </button>
        }
      />

      <div className="circle-grid">
        {people.map(p => {
          const count = getPersonCounts(p.id);
          const itemLabel = count === 1 ? t.circle.items_left_one : t.circle.items_left;
          const assignedServices = services.filter(s => s.assignees.includes(p.id));
          const assignedAssets = assets.filter(a => a.assignees.includes(p.id));
          const assignedMems = memories.filter(m => m.assignees.includes(p.id));

          return (
            <div key={p.id} className="card person-card">
              {/* Header */}
              <div className="row" style={{ marginBottom: 16 }}>
                <Monogram initials={p.initials} color={p.color} size="lg" />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>
                    {p.name}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-muted)', textTransform: 'capitalize' }}>
                    {p.rel}
                  </div>
                </div>
                <div>
                  {p.invited ? (
                    <span className="chip chip-accent">
                      <Icon name="check" size={12} color="var(--accent-ink)" strokeWidth={2.5} />
                      {t.circle.invited}
                    </span>
                  ) : (
                    <span className="chip chip-warn">
                      {t.circle.not_invited}
                    </span>
                  )}
                </div>
              </div>

              <hr className="divider" style={{ margin: '0 0 14px' }} />

              {/* Contact info */}
              <div className="col" style={{ gap: 6, marginBottom: 14 }}>
                <div className="row" style={{ gap: 8 }}>
                  <Icon name="mail" size={13} color="var(--ink-muted)" />
                  <span style={{ fontSize: 12, color: 'var(--ink-muted)' }}>{p.email}</span>
                </div>
                <div className="row" style={{ gap: 8 }}>
                  <Icon name="people" size={13} color="var(--ink-muted)" />
                  <span style={{ fontSize: 12, color: 'var(--ink-muted)' }}>{p.phone}</span>
                </div>
              </div>

              {/* Assignment counts */}
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
                {assignedServices.length > 0 && (
                  <span className="chip chip-muted">
                    <Icon name="service" size={12} />
                    {assignedServices.length} servizi
                  </span>
                )}
                {assignedAssets.length > 0 && (
                  <span className="chip chip-muted">
                    <Icon name="shield" size={12} />
                    {assignedAssets.length} asset
                  </span>
                )}
                {assignedMems.length > 0 && (
                  <span className="chip chip-muted">
                    <Icon name="memories" size={12} />
                    {assignedMems.length} memorie
                  </span>
                )}
                {count === 0 && (
                  <span className="chip chip-warn">
                    <Icon name="alert" size={12} />
                    Niente assegnato
                  </span>
                )}
              </div>

              {/* Actions */}
              <div className="row" style={{ gap: 8 }}>
                {!p.invited && (
                  <button className="btn btn-accent btn-sm" style={{ flex: 1, justifyContent: 'center' }}>
                    <Icon name="mail" size={13} color="#fff" />
                    {t.circle.send_invite}
                  </button>
                )}
                <button className="btn btn-secondary btn-sm" style={p.invited ? { flex: 1, justifyContent: 'center' } : {}}>
                  <Icon name="edit" size={13} />
                  Modifica
                </button>
              </div>
            </div>
          );
        })}

        {/* Add person card */}
        <div
          className="card"
          style={{
            padding: 20,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 12,
            cursor: 'pointer',
            border: '2px dashed var(--line)',
            background: 'transparent',
            minHeight: 220,
            transition: 'all .15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink)'; e.currentTarget.style.background = 'var(--paper-2)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.background = 'transparent'; }}
        >
          <div style={{
            width: 48,
            height: 48,
            borderRadius: '50%',
            background: 'var(--paper-2)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <Icon name="plus" size={22} color="var(--ink-muted)" />
          </div>
          <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink-muted)' }}>
            {t.circle.add}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── BequestsPage ────────────────────────────────────────────────────────────
function BequestsPage({ data }) {
  const seed = data || DOPO.SEED;
  const { bequests } = seed;

  const kindIcon = { letter: 'letter', photo: 'photo', video: 'video', audio: 'audio', service: 'service', doc: 'doc' };
  const kindLabel = { letter: 'Lettera', photo: 'Foto', video: 'Video', audio: 'Audio', service: 'Servizio', doc: 'Documento' };
  const kindClass = { letter: 'mem-letter', photo: 'mem-photo', video: 'mem-video', audio: 'mem-audio', service: 'mem-doc', doc: 'mem-doc' };

  return (
    <div className="fade-in">
      <PageHeader
        eyebrow="dopo.me"
        title={t.bequests.title}
        subtitle={t.bequests.sub}
      />

      <div className="bequest-grid">
        {bequests.map(b => (
          <div key={b.id} className="card bequest-card">
            {/* Cover */}
            <div className={`${kindClass[b.kind] || 'mem-doc'}`} style={{
              borderRadius: 10,
              height: 120,
              display: 'flex',
              alignItems: 'flex-end',
              padding: 14,
              marginBottom: 16,
              position: 'relative',
              overflow: 'hidden',
            }}>
              <span className="kind-tag">
                <Icon name={kindIcon[b.kind] || 'doc'} size={11} />
                {kindLabel[b.kind] || b.kind}
              </span>
              {b.locked && (
                <div style={{ position: 'absolute', top: 14, right: 14 }}>
                  <Icon name="lock" size={16} color={b.kind === 'letter' ? 'var(--ink-muted)' : 'rgba(255,255,255,0.7)'} />
                </div>
              )}
            </div>

            {/* From */}
            <div className="row" style={{ marginBottom: 10 }}>
              <Monogram initials={b.from.initials} color={b.from.color} size="sm" />
              <div>
                <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{t.bequests.from}</div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>
                  {b.from.name}
                  <span style={{ fontWeight: 400, color: 'var(--ink-muted)', marginLeft: 4 }}>
                    — {b.from.rel}
                  </span>
                </div>
              </div>
            </div>

            {/* Title */}
            <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--ink)', marginBottom: 8, lineHeight: 1.3 }}>
              {b.locked ? (
                <span style={{ filter: 'blur(5px)', userSelect: 'none' }}>{b.title}</span>
              ) : b.title}
            </div>

            {/* Date */}
            {!b.locked && (
              <div className="t-mono" style={{ marginBottom: 14 }}>
                {b.date !== '—' ? new Date(b.date).toLocaleDateString('it-IT', { year: 'numeric', month: 'long', day: 'numeric' }) : b.date}
              </div>
            )}

            {/* Locked overlay */}
            {b.locked ? (
              <div style={{
                padding: '12px 14px',
                background: 'var(--paper-2)',
                borderRadius: 10,
                border: '1px solid var(--line)',
                display: 'flex',
                alignItems: 'center',
                gap: 10,
              }}>
                <Icon name="lock" size={16} color="var(--ink-muted)" />
                <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4 }}>
                  {t.bequests.locked}
                </div>
              </div>
            ) : (
              <button className="btn btn-secondary btn-sm" style={{ width: '100%', justifyContent: 'center' }}>
                {b.kind === 'letter' ? 'Leggi la lettera' : b.kind === 'photo' ? 'Guarda le foto' : 'Apri'}
                <Icon name="arrow_right" size={13} />
              </button>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── ProfilePage ─────────────────────────────────────────────────────────────
function ProfilePage({ data, onUpdate }) {
  const seed = data || DOPO.SEED;
  const { user, mailboxes, inactivity, people, profileProgress } = seed;
  const [inact, setInact] = useState(inactivity);
  const [saved, setSaved] = useState(false);
  const [connectingId, setConnectingId] = useState(null);

  function updateInact(updater) {
    setInact(prev => {
      const next = updater(prev);
      onUpdate(d => ({ ...d, inactivity: next }));
      return next;
    });
    setSaved(true);
    setTimeout(() => setSaved(false), 1800);
  }

  function connectMailbox(mbId) {
    setConnectingId(mbId);
    setTimeout(() => {
      onUpdate(d => ({
        ...d,
        mailboxes: d.mailboxes.map(mb =>
          mb.id === mbId
            ? { ...mb, connected: true, lastScan: 'adesso', servicesFound: Math.floor(Math.random() * 50) + 20 }
            : mb
        ),
      }));
      setConnectingId(null);
    }, 1800);
  }

  const trustedPeople = inact.trustedContacts
    .map(id => people.find(p => p.id === id))
    .filter(Boolean);

  const mailKindLabel = { google: 'Gmail', apple: 'iCloud Mail', microsoft: 'Outlook' };
  const mailKindColor = { google: '#B22D2D', apple: '#63939A', microsoft: '#307D86' };

  return (
    <div className="fade-in">
      <PageHeader
        eyebrow="dopo.me"
        title={t.profile.title}
      />

      <div className="profile-grid">
        {/* Left column */}
        <div className="col" style={{ gap: 28 }}>
          {/* Inactivity */}
          <div className="card" style={{ padding: 24 }}>
            <div className="row" style={{ marginBottom: 6 }}>
              <div style={{ flex: 1 }}>
                <div className="row" style={{ gap: 10, marginBottom: 4 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>
                    {t.profile.inactivity}
                  </div>
                  {saved && (
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, color: 'var(--olive-500)', fontWeight: 500 }}>
                      <Icon name="check" size={13} color="var(--olive-500)" strokeWidth={2.5} />
                      Salvato
                    </span>
                  )}
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-muted)', lineHeight: 1.5, maxWidth: 400 }}>
                  {t.profile.inactivity_desc}
                </div>
              </div>
              <label className="switch">
                <input
                  type="checkbox"
                  checked={inact.enabled}
                  onChange={e => updateInact(prev => ({ ...prev, enabled: e.target.checked }))}
                />
                <span className="slider" />
              </label>
            </div>

            {inact.enabled && (
              <div style={{ marginTop: 16 }}>
                <div className="inact-setting">
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>
                      Periodo di inattività
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>
                      {t.profile.months}
                    </div>
                  </div>
                  <div className="row" style={{ gap: 8 }}>
                    <button
                      className="btn btn-secondary btn-sm btn-icon"
                      onClick={() => updateInact(prev => ({ ...prev, months: Math.max(1, prev.months - 1) }))}
                    >
                      <Icon name="close" size={14} />
                    </button>
                    <span style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 24, minWidth: 32, textAlign: 'center' }}>
                      {inact.months}
                    </span>
                    <button
                      className="btn btn-secondary btn-sm btn-icon"
                      onClick={() => updateInact(prev => ({ ...prev, months: Math.min(36, prev.months + 1) }))}
                    >
                      <Icon name="plus" size={14} />
                    </button>
                  </div>
                </div>

                <div className="inact-setting">
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>
                      Tentativi di ping
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>
                      {t.profile.pings}
                    </div>
                  </div>
                  <div className="row" style={{ gap: 8 }}>
                    <button
                      className="btn btn-secondary btn-sm btn-icon"
                      onClick={() => updateInact(prev => ({ ...prev, pingCount: Math.max(1, prev.pingCount - 1) }))}
                    >
                      <Icon name="close" size={14} />
                    </button>
                    <span style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', fontSize: 24, minWidth: 32, textAlign: 'center' }}>
                      {inact.pingCount}
                    </span>
                    <button
                      className="btn btn-secondary btn-sm btn-icon"
                      onClick={() => updateInact(prev => ({ ...prev, pingCount: Math.min(10, prev.pingCount + 1) }))}
                    >
                      <Icon name="plus" size={14} />
                    </button>
                  </div>
                </div>

                <div className="inact-setting" style={{ borderBottom: 0 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>
                      Contatti di fiducia
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginBottom: 8 }}>
                      Saranno avvisati dopo i tentativi falliti
                    </div>
                    <div className="row" style={{ flexWrap: 'wrap', gap: 8 }}>
                      {trustedPeople.map(p => (
                        <div key={p.id} className="row" style={{ gap: 6 }}>
                          <Monogram initials={p.initials} color={p.color} size="sm" />
                          <span style={{ fontSize: 13, color: 'var(--ink)' }}>{p.name.split(' ')[0]}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Mailboxes */}
          <div className="card" style={{ padding: 24 }}>
            <div className="row" style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)', flex: 1 }}>
                {t.profile.mailboxes}
              </div>
              <button className="btn btn-secondary btn-sm">
                <Icon name="plus" size={13} />
                {t.profile.add_mailbox}
              </button>
            </div>

            {mailboxes.map(mb => (
              <div key={mb.id} className="mailbox-row">
                <div style={{
                  width: 36,
                  height: 36,
                  borderRadius: 8,
                  background: mailKindColor[mb.kind] + '15',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                  <Icon name="mail" size={16} color={mailKindColor[mb.kind]} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>
                    {mailKindLabel[mb.kind]}
                  </div>
                  <div className="t-mono">{mb.email}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  {mb.connected ? (
                    <>
                      <div className="row" style={{ gap: 6, marginBottom: 2, justifyContent: 'flex-end' }}>
                        <div className="connected-dot" />
                        <span style={{ fontSize: 12, color: 'var(--olive-500)', fontWeight: 500 }}>Connessa</span>
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>
                        {mb.servicesFound} servizi · {mb.lastScan}
                      </div>
                    </>
                  ) : connectingId === mb.id ? (
                    <div className="row" style={{ gap: 6, justifyContent: 'flex-end' }}>
                      <span style={{ fontSize: 12, color: 'var(--ink-muted)', fontStyle: 'italic' }}>Connessione…</span>
                    </div>
                  ) : (
                    <div className="row" style={{ gap: 6, justifyContent: 'flex-end' }}>
                      <div className="disconnected-dot" />
                      <button
                        className="btn btn-secondary btn-sm"
                        onClick={() => connectMailbox(mb.id)}
                        disabled={connectingId !== null}
                      >
                        Connetti
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Right column */}
        <div className="col" style={{ gap: 20 }}>
          {/* User card */}
          <div className="card" style={{ padding: 24 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', marginBottom: 20 }}>
              <Monogram initials={user.initials} color={user.color} size="xl" style={{ marginBottom: 16 }} />
              <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>
                {user.name}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-muted)' }}>
                {user.email}
              </div>
            </div>

            <hr className="divider" style={{ margin: '0 0 16px' }} />

            {/* Progress */}
            <div>
              <div className="row" style={{ marginBottom: 8 }}>
                <span style={{ fontSize: 13, color: 'var(--ink)', flex: 1 }}>Profilo completato</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent)' }}>{profileProgress}%</span>
              </div>
              <div className="progress">
                <div style={{ width: `${profileProgress}%` }} />
              </div>
            </div>

            <div style={{ marginTop: 16 }}>
              <button className="btn btn-secondary btn-sm" style={{ width: '100%', justifyContent: 'center' }}>
                <Icon name="edit" size={13} />
                Modifica profilo
              </button>
            </div>
          </div>

          {/* Sensitive flows */}
          <div className="card" style={{ padding: 24 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>
              {t.profile.sensitive}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-muted)', marginBottom: 16, lineHeight: 1.5 }}>
              Azioni delicate che richiedono verifica manuale.
            </div>

            <div style={{
              padding: '14px 16px',
              background: 'var(--red-0)',
              border: '1px solid var(--red-200)',
              borderRadius: 12,
              display: 'flex',
              gap: 12,
              alignItems: 'flex-start',
            }}>
              <Icon name="heart" size={18} color="var(--red-500)" style={{ flexShrink: 0, marginTop: 1 }} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 4 }}>
                  {t.profile.report_death}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4, marginBottom: 12 }}>
                  {t.profile.report_death_desc}
                </div>
                <button className="btn btn-sm" style={{ background: 'var(--red-500)', color: '#fff', borderColor: 'transparent' }}>
                  <Icon name="alert" size={13} color="#fff" />
                  Segnala un decesso
                </button>
              </div>
            </div>
          </div>

          {/* Settings quick links */}
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            {[
              { icon: 'bell', label: 'Notifiche', desc: 'Email, push, SMS' },
              { icon: 'lock', label: 'Sicurezza', desc: 'Password, 2FA' },
              { icon: 'key', label: 'API & Integrazioni', desc: 'Connessioni esterne' },
              { icon: 'trash', label: 'Elimina account', desc: 'Azione irreversibile', danger: true },
            ].map((item, i) => (
              <div
                key={i}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '14px 16px',
                  borderBottom: i < 3 ? '1px solid var(--line)' : 'none',
                  cursor: 'pointer',
                  transition: 'background .12s',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--paper-2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
              >
                <Icon name={item.icon} size={16} color={item.danger ? 'var(--red-500)' : 'var(--ink-muted)'} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: item.danger ? 'var(--red-500)' : 'var(--ink)' }}>
                    {item.label}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{item.desc}</div>
                </div>
                <Icon name="chevron_right" size={14} color="var(--gr-400)" />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MemoriesPage, CirclePage, BequestsPage, ProfilePage });
