// WealthIntelligence — Vault page (matrix view) + cassetta editor + activate modal
const VaultPage = ({state, t, openCassettaEditor, togglePersonOnCassetta, setCassettaActivated}) => {
  const [filter, setFilter] = useState('all'); // all | permanent | temporary
  const [activating, setActivating] = useState(null); // cassetta to activate

  const filtered = state.cassette.filter(c => filter==='all' || c.trigger===filter);

  const counts = {
    all: state.cassette.length,
    permanent: state.cassette.filter(c=>c.trigger==='permanent').length,
    temporary: state.cassette.filter(c=>c.trigger==='temporary').length,
  };

  return <div className="fade-in">
    <PageHeader
      eyebrow={t.vault.title}
      title={t.vault.hero}
      subtitle={t.vault.sub}
      actions={<button className="btn btn-primary" onClick={()=>openCassettaEditor()}><Icon name="plus" size={16}/>{t.vault.add}</button>}
    />

    {/* Trigger filter chips */}
    <div className="row" style={{gap:8, marginBottom:24, flexWrap:'wrap'}}>
      <button onClick={()=>setFilter('all')} className={`chip ${filter==='all'?'chip-solid':''}`} style={{cursor:'pointer', border:0, fontFamily:'inherit'}}>
        Tutte <span style={{opacity:.55, marginLeft:4}}>{counts.all}</span>
      </button>
      <button onClick={()=>setFilter('permanent')} className={`chip ${filter==='permanent'?'chip-permanent':''}`} style={{cursor:'pointer', border:0, fontFamily:'inherit'}}>
        <span className="trigger-dot permanent"/> {t.vault.triggers.permanent} <span style={{opacity:.65, marginLeft:4}}>{counts.permanent}</span>
      </button>
      <button onClick={()=>setFilter('temporary')} className={`chip ${filter==='temporary'?'chip-temporary':''}`} style={{cursor:'pointer', border:0, fontFamily:'inherit'}}>
        <span className="trigger-dot temporary"/> {t.vault.triggers.temporary} <span style={{opacity:.65, marginLeft:4}}>{counts.temporary}</span>
      </button>
    </div>

    {filtered.length === 0 ? (
      <div className="empty-state">
        <Icon name="vault" size={32} style={{marginBottom:12, opacity:.5}}/>
        <p style={{margin:0, fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:18}}>{t.vault.empty}</p>
        <button className="btn btn-primary" style={{marginTop:18}} onClick={()=>openCassettaEditor()}>
          <Icon name="plus" size={14}/>{t.vault.add}
        </button>
      </div>
    ) : (
      <div style={{overflow:'auto', borderRadius:'var(--r-lg)'}}>
        <table className="matrix">
          <thead>
            <tr>
              <th className="head-cassetta">{t.vault.col_cassetta}</th>
              <th className="head-trigger">{t.vault.col_trigger}</th>
              <th>{t.vault.col_items}</th>
              {state.people.map(p => (
                <th key={p.id} title={p.name}>
                  <div className="matrix-person-head">
                    <Monogram color={p.color} initials={p.initials} size="sm"/>
                    <span style={{fontSize:10, fontWeight:500, color:'var(--ink)', textTransform:'none', letterSpacing:0}}>
                      {p.name.split(' ')[0]}
                    </span>
                  </div>
                </th>
              ))}
              <th className="head-actions">{t.vault.col_actions}</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(c => (
              <tr key={c.id}>
                <td className="cell-cassetta" onClick={()=>openCassettaEditor(c)}>
                  <div className="cassetta-row" style={{cursor:'pointer'}}>
                    <CassettaBadge icon={c.icon} color={c.color}/>
                    <div>
                      <div className="cassetta-name">{c.name}</div>
                      <div className="cassetta-meta">
                        {c.activated ? <span className="status-pill active"><span className="trigger-dot"/>{t.vault.activated}</span> : <span className="status-pill">Inattiva</span>}
                      </div>
                    </div>
                  </div>
                </td>
                <td style={{textAlign:'center'}}><TriggerBadge trigger={c.trigger} t={t} short/></td>
                <td style={{textAlign:'center'}}>
                  <span className="t-num" style={{fontSize:18}}>{c.itemIds.length}</span>
                </td>
                {state.people.map(p => {
                  const on = c.assignees.includes(p.id);
                  return <td key={p.id} className={`cell-person ${on?'on':''}`}
                             onClick={()=>togglePersonOnCassetta(c.id, p.id)}
                             title={`${on?'Rimuovi':'Aggiungi'} ${p.name}`}>
                    <span className={`cell-dot ${on?'on':''}`}/>
                  </td>;
                })}
                <td>
                  <div className="row" style={{gap:6, justifyContent:'flex-end'}}>
                    <button className="btn btn-ghost btn-icon" title={t.common.edit} onClick={()=>openCassettaEditor(c)}>
                      <Icon name="edit" size={14}/>
                    </button>
                    {c.activated ? (
                      <button className="btn btn-secondary btn-sm" onClick={()=>setCassettaActivated(c.id, false)}>
                        <Icon name="check" size={13}/>{t.common.deactivate}
                      </button>
                    ) : (
                      <button
                        className={`btn btn-sm ${c.trigger==='temporary'?'btn-warn':'btn-danger'}`}
                        onClick={()=>setActivating(c)}>
                        {t.vault.activate}
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )}

    {activating && (
      <ActivateCassettaModal
        cassetta={activating}
        t={t}
        onClose={()=>setActivating(null)}
        onConfirm={()=>{ setCassettaActivated(activating.id, true); setActivating(null); }}
      />
    )}
  </div>;
};

// ------- Activate cassetta modal -------
const ActivateCassettaModal = ({cassetta, t, onClose, onConfirm}) => {
  const isTemp = cassetta.trigger === 'temporary';
  return <>
    <div className="backdrop" onClick={onClose}/>
    <div className="modal fade-in">
      <DialogHeader title={t.vault.activate_modal.title} onClose={onClose}/>
      <div style={{padding:24}}>
        <div className="row" style={{gap:14, marginBottom:18, alignItems:'flex-start'}}>
          <CassettaBadge icon={cassetta.icon} color={cassetta.color} size={44}/>
          <div>
            <div style={{fontWeight:500, fontSize:16}}>{cassetta.name}</div>
            <div style={{marginTop:6}}><TriggerBadge trigger={cassetta.trigger} t={t}/></div>
          </div>
        </div>
        <p className="muted" style={{margin:'0 0 20px', fontSize:14, lineHeight:1.5}}>
          {isTemp ? t.vault.activate_modal.sub_temporary : t.vault.activate_modal.sub_permanent}
        </p>
        <div className="row" style={{gap:10, justifyContent:'flex-end'}}>
          <button className="btn btn-ghost" onClick={onClose}>{t.common.cancel}</button>
          <button className={`btn ${isTemp?'btn-warn':'btn-danger'}`} onClick={onConfirm}>
            {t.vault.activate_modal.confirm}
          </button>
        </div>
      </div>
    </div>
  </>;
};

// ------- Cassetta editor (drawer) -------
const CassettaEditor = ({cassetta, isNew, state, t, onClose, onSave, onDelete}) => {
  const [draft, setDraft] = useState(() => cassetta || {
    id:null, name:'', icon:'◇', color:'#27666D', trigger:'permanent',
    assignees:[], itemIds:[], note:'',
  });
  const [confirmDel, setConfirmDel] = useState(false);

  const valid = draft.name.trim().length > 0;

  const togglePerson = (pid) => {
    setDraft(d => ({ ...d, assignees: d.assignees.includes(pid) ? d.assignees.filter(x=>x!==pid) : [...d.assignees, pid] }));
  };
  const toggleItem = (iid) => {
    setDraft(d => ({ ...d, itemIds: d.itemIds.includes(iid) ? d.itemIds.filter(x=>x!==iid) : [...d.itemIds, iid] }));
  };

  return <>
    <div className="backdrop" onClick={onClose}/>
    <div className="drawer fade-in">
      <DialogHeader title={isNew ? t.vault.editor.new : t.vault.editor.edit} onClose={onClose}/>

      <div style={{padding:24}}>
        <Field label={t.vault.editor.name}>
          <input className="input" placeholder={t.vault.editor.name_ph}
                 value={draft.name} onChange={e=>setDraft({...draft, name:e.target.value})}/>
        </Field>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
          <Field label={t.vault.editor.icon}>
            <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
              {window.WI.ICON_OPTIONS.map(ic => (
                <button key={ic} type="button"
                  onClick={()=>setDraft({...draft, icon:ic})}
                  style={{
                    width:36, height:36, borderRadius:8,
                    border:'1px solid '+(draft.icon===ic ? 'var(--ink)' : 'var(--line)'),
                    background: draft.icon===ic ? 'var(--paper-2)' : '#fff',
                    fontSize:18, cursor:'pointer', fontFamily:'inherit',
                  }}>{ic}</button>
              ))}
            </div>
          </Field>

          <Field label={t.vault.editor.color}>
            <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
              {window.WI.COLOR_OPTIONS.map(co => (
                <button key={co} type="button"
                  onClick={()=>setDraft({...draft, color:co})}
                  style={{
                    width:28, height:28, borderRadius:'50%',
                    border:'2px solid '+(draft.color===co ? 'var(--ink)' : 'transparent'),
                    background:co, cursor:'pointer',
                  }} aria-label={co}/>
              ))}
            </div>
          </Field>
        </div>

        <Field label={t.vault.editor.trigger} help={t.vault.editor.trigger_help}>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
            {window.WI.TRIGGERS.map(tr => (
              <button key={tr} type="button" onClick={()=>setDraft({...draft, trigger:tr})}
                style={{
                  padding:'14px', borderRadius:12,
                  border:'1px solid '+(draft.trigger===tr ? 'var(--ink)' : 'var(--line)'),
                  background: draft.trigger===tr ? 'var(--paper-2)' : '#fff',
                  fontFamily:'inherit', textAlign:'left', cursor:'pointer',
                }}>
                <div className="row" style={{gap:8, marginBottom:4}}>
                  <span className={`trigger-dot ${tr}`}/>
                  <span style={{fontSize:13, fontWeight:500}}>{t.vault.triggers[tr]}</span>
                </div>
                <div className="muted" style={{fontSize:11}}>
                  {tr==='permanent' ? 'Si attiva via inattività' : 'Si attiva manualmente dal profilo'}
                </div>
              </button>
            ))}
          </div>
        </Field>

        <Field label={t.vault.editor.assignees} help={t.vault.editor.assignees_help}>
          <div style={{display:'flex', flexWrap:'wrap', gap:8}}>
            {state.people.map(p => {
              const on = draft.assignees.includes(p.id);
              return <button key={p.id} type="button" onClick={()=>togglePerson(p.id)}
                style={{
                  padding:'6px 12px 6px 6px', borderRadius:999,
                  border:'1px solid '+(on ? 'var(--ink)' : 'var(--line)'),
                  background: on ? 'var(--ink)' : '#fff',
                  color: on ? '#fff' : 'var(--ink)',
                  display:'inline-flex', alignItems:'center', gap:8, cursor:'pointer',
                  fontFamily:'inherit', fontSize:13,
                }}>
                <Monogram color={p.color} initials={p.initials} size="sm"/>
                {p.name.split(' ')[0]}
              </button>;
            })}
          </div>
        </Field>

        <Field label={t.vault.editor.items} help={t.vault.editor.items_help}>
          <div style={{maxHeight:280, overflow:'auto', border:'1px solid var(--line)', borderRadius:10, background:'#fff'}}>
            {state.inventory.map(it => {
              const on = draft.itemIds.includes(it.id);
              return <label key={it.id} style={{
                display:'flex', alignItems:'center', gap:12, padding:'10px 14px',
                borderBottom:'1px solid var(--line)', cursor:'pointer',
                background: on ? 'var(--accent-soft)' : 'transparent',
              }}>
                <input type="checkbox" checked={on} onChange={()=>toggleItem(it.id)} style={{accentColor:'var(--accent)'}}/>
                <ItemBadge icon={it.icon} color={it.color} size={28}/>
                <div className="grow">
                  <div style={{fontSize:13, fontWeight:500}}>{it.name}</div>
                  <div className="muted" style={{fontSize:11}}>{t.inventory.cat[it.category]||it.category} · {it.value}</div>
                </div>
              </label>;
            })}
          </div>
        </Field>

        <Field label={t.vault.editor.note}>
          <textarea className="input" rows={3} placeholder={t.vault.editor.note_ph}
                    value={draft.note} onChange={e=>setDraft({...draft, note:e.target.value})}
                    style={{resize:'vertical', fontFamily:'inherit'}}/>
        </Field>
      </div>

      <div className="row" style={{
        position:'sticky', bottom:0, padding:'16px 24px', background:'var(--paper)',
        borderTop:'1px solid var(--line)', justifyContent:'space-between',
      }}>
        {!isNew ? (
          confirmDel ? (
            <div className="row" style={{gap:8}}>
              <span style={{fontSize:13}}>{t.vault.editor.delete_confirm}</span>
              <button className="btn btn-ghost btn-sm" onClick={()=>setConfirmDel(false)}>{t.common.cancel}</button>
              <button className="btn btn-danger btn-sm" onClick={()=>onDelete(draft.id)}>{t.common.delete}</button>
            </div>
          ) : (
            <button className="btn btn-ghost btn-sm" onClick={()=>setConfirmDel(true)}>
              <Icon name="trash" size={14}/>{t.common.delete}
            </button>
          )
        ) : <span/>}

        <div className="row" style={{gap:10}}>
          <button className="btn btn-ghost" onClick={onClose}>{t.common.cancel}</button>
          <button className="btn btn-primary" disabled={!valid} onClick={()=>onSave(draft)}>
            <Icon name="check" size={14}/>{t.common.save}
          </button>
        </div>
      </div>
    </div>
  </>;
};

Object.assign(window, { VaultPage, CassettaEditor, ActivateCassettaModal });
