// WealthIntelligence — Trustworthy People page + PersonDetailDrawer
const TrustworthyPage = ({state, t, openPersonDetail, openPersonEditor}) => {
  return <div className="fade-in">
    <PageHeader
      eyebrow={t.trustworthy.title}
      title={t.trustworthy.hero}
      subtitle={t.trustworthy.sub}
      actions={<button className="btn btn-primary" onClick={()=>openPersonEditor()}><Icon name="plus" size={16}/>{t.trustworthy.add}</button>}
    />

    <div style={{display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:16}}>
      {state.people.map(p => {
        const cassette = state.cassette.filter(c => c.assignees.includes(p.id));
        const permanent = cassette.filter(c => c.trigger==='permanent');
        const temporary = cassette.filter(c => c.trigger==='temporary');

        return <div key={p.id} className="card" style={{padding:24, cursor:'pointer'}} onClick={()=>openPersonDetail(p)}>
          <div className="row" style={{alignItems:'flex-start', gap:16, marginBottom:18}}>
            <Monogram color={p.color} initials={p.initials} size="lg"/>
            <div className="grow">
              <h3 style={{margin:0, fontSize:20, fontFamily:'var(--f-serif)', fontStyle:'italic', fontWeight:400}}>{p.name}</h3>
              <div className="muted" style={{fontSize:13, marginTop:2}}>{p.rel}</div>
              <div className="row" style={{gap:10, marginTop:10}}>
                <span className={`chip ${p.invited?'chip-accent':'chip-warn'}`} style={{gap:6}}>
                  <span style={{width:6, height:6, borderRadius:'50%', background:p.invited?'var(--olive-500)':'var(--yel-600)'}}/>
                  {p.invited ? t.trustworthy.invited : t.trustworthy.not_invited}
                </span>
              </div>
            </div>
            <div style={{textAlign:'right'}}>
              <div className="t-num" style={{fontSize:42, lineHeight:1, color:'var(--accent-ink)'}}>{cassette.length}</div>
              <div className="muted" style={{fontSize:11, letterSpacing:'.08em', textTransform:'uppercase'}}>
                {cassette.length===1 ? t.trustworthy.cassetta_assigned_one : t.trustworthy.cassette_assigned}
              </div>
            </div>
          </div>

          <hr className="divider"/>

          <div style={{padding:'16px 0', display:'flex', flexDirection:'column', gap:10}}>
            <div className="row" style={{gap:10}}>
              <span className="trigger-dot permanent"/>
              <span style={{fontSize:13}}>{permanent.length} {t.trustworthy.permanent_count}</span>
            </div>
            <div className="row" style={{gap:10}}>
              <span className="trigger-dot temporary"/>
              <span style={{fontSize:13}}>{temporary.length} {t.trustworthy.temporary_count}</span>
            </div>
          </div>

          {cassette.length > 0 && (
            <div style={{padding:'8px 0 12px', display:'flex', flexWrap:'wrap', gap:6}}>
              {cassette.map(c => (
                <span key={c.id} className="chip" style={{background:c.color, color:'#fff', borderColor:'transparent'}}>
                  <span style={{fontSize:11}}>{c.icon}</span>
                  {c.name}
                </span>
              ))}
            </div>
          )}

          <div className="muted" style={{fontSize:13, borderTop:'1px solid var(--line)', paddingTop:14}}>
            {p.phone} · {p.email}
          </div>
        </div>;
      })}
    </div>
  </div>;
};

// ------- Person detail drawer -------
const PersonDetailDrawer = ({person, state, t, onClose, onOpenCassetta, onEdit}) => {
  const cassette = state.cassette.filter(c => c.assignees.includes(person.id));
  const permanent = cassette.filter(c => c.trigger==='permanent');
  const temporary = cassette.filter(c => c.trigger==='temporary');

  // Items covered = union of items in all assigned cassette
  const itemSet = new Set();
  cassette.forEach(c => c.itemIds.forEach(iid => itemSet.add(iid)));
  const items = [...itemSet].map(iid => state.inventory.find(it=>it.id===iid)).filter(Boolean);
  const totalEur = items.reduce((s, it) => s + (it.valueEur || 0), 0);

  const renderCassetteGroup = (list) => (
    <div style={{display:'flex', flexWrap:'wrap', gap:8}}>
      {list.map(c => (
        <button key={c.id} className="chip" style={{
          background:c.color, color:'#fff', borderColor:'transparent',
          cursor:'pointer', fontFamily:'inherit', padding:'6px 12px',
        }} onClick={()=>onOpenCassetta(c)}>
          <span style={{fontSize:12}}>{c.icon}</span>
          {c.name}
          <span style={{opacity:.7, fontSize:11}}>· {c.itemIds.length}</span>
        </button>
      ))}
    </div>
  );

  return <>
    <div className="backdrop" onClick={onClose}/>
    <div className="drawer fade-in">
      <DialogHeader title={person.name} onClose={onClose}/>

      <div style={{padding:24}}>
        <div className="row" style={{gap:18, marginBottom:24, alignItems:'flex-start'}}>
          <Monogram color={person.color} initials={person.initials} size="xl"/>
          <div className="grow">
            <h2 style={{margin:0, fontFamily:'var(--f-serif)', fontStyle:'italic', fontWeight:400, fontSize:26, lineHeight:1.1}}>{person.name}</h2>
            <div className="muted" style={{fontSize:14, marginTop:4}}>{person.rel}</div>
            <div className="row" style={{gap:8, marginTop:12}}>
              <span className={`chip ${person.invited?'chip-accent':'chip-warn'}`} style={{gap:6}}>
                <span style={{width:6, height:6, borderRadius:'50%', background:person.invited?'var(--olive-500)':'var(--yel-600)'}}/>
                {person.invited ? t.trustworthy.invited : t.trustworthy.not_invited}
              </span>
            </div>
          </div>
        </div>

        {/* Contact */}
        <div className="card-paper" style={{padding:16, background:'var(--paper-2)', borderRadius:12, border:'1px solid var(--line)', marginBottom:24}}>
          <div className="t-eyebrow" style={{marginBottom:8}}>{t.trustworthy.detail.contact}</div>
          <div style={{fontSize:14, marginBottom:4}}>
            <Icon name="mail" size={14} style={{marginRight:8, opacity:.6}}/>
            {person.email}
          </div>
          <div style={{fontSize:14}}>
            <Icon name="bell" size={14} style={{marginRight:8, opacity:.6}}/>
            {person.phone}
          </div>
        </div>

        {/* Cassette assigned */}
        <div style={{marginBottom:28}}>
          <div className="row" style={{justifyContent:'space-between', marginBottom:10, alignItems:'baseline'}}>
            <div className="t-eyebrow">{t.trustworthy.detail.cassette}</div>
            <span className="muted" style={{fontSize:12}}>{cassette.length}</span>
          </div>
          {cassette.length === 0 ? (
            <p className="muted" style={{margin:0, fontSize:13, fontStyle:'italic'}}>{t.trustworthy.detail.no_cassette}</p>
          ) : (
            <div style={{display:'flex', flexDirection:'column', gap:18}}>
              {permanent.length > 0 && (
                <div>
                  <div className="row" style={{gap:8, marginBottom:8, fontSize:12}}>
                    <span className="trigger-dot permanent"/>
                    <span style={{fontWeight:500, color:'var(--trigger-permanent)'}}>{t.vault.triggers.permanent}</span>
                  </div>
                  {renderCassetteGroup(permanent)}
                </div>
              )}
              {temporary.length > 0 && (
                <div>
                  <div className="row" style={{gap:8, marginBottom:8, fontSize:12}}>
                    <span className="trigger-dot temporary"/>
                    <span style={{fontWeight:500, color:'var(--trigger-temporary)'}}>{t.vault.triggers.temporary}</span>
                  </div>
                  {renderCassetteGroup(temporary)}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Items covered */}
        <div style={{marginBottom:24}}>
          <div className="row" style={{justifyContent:'space-between', marginBottom:8, alignItems:'baseline'}}>
            <div className="t-eyebrow">{t.trustworthy.detail.items_covered}</div>
            {totalEur > 0 && <span className="t-num" style={{fontSize:18, color:'var(--accent-ink)'}}>{fmtEur(totalEur)}</span>}
          </div>
          <div className="muted" style={{fontSize:12, marginBottom:10}}>{t.trustworthy.detail.items_covered_help}</div>

          {items.length === 0 ? (
            <p className="muted" style={{margin:0, fontSize:13, fontStyle:'italic'}}>{t.trustworthy.detail.no_items_covered}</p>
          ) : (
            <div className="card" style={{padding:0, overflow:'hidden'}}>
              {items.map((it, i) => (
                <div key={it.id} className="row" style={{
                  padding:'10px 14px', gap:12,
                  borderBottom: i < items.length-1 ? '1px solid var(--line)' : '0',
                }}>
                  <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}</div>
                  </div>
                  {typeof it.valueEur === 'number' && (
                    <span className="t-num" style={{fontSize:13}}>{fmtEur(it.valueEur)}</span>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="row" style={{
        position:'sticky', bottom:0, padding:'16px 24px', background:'var(--paper)',
        borderTop:'1px solid var(--line)', justifyContent:'space-between',
      }}>
        {!person.invited ? (
          <button className="btn btn-secondary btn-sm"><Icon name="mail" size={14}/>{t.trustworthy.send_invite}</button>
        ) : <span/>}
        <div className="row" style={{gap:10}}>
          <button className="btn btn-ghost" onClick={onClose}>{t.common.close}</button>
          <button className="btn btn-primary" onClick={onEdit}><Icon name="edit" size={14}/>{t.trustworthy.detail.edit}</button>
        </div>
      </div>
    </div>
  </>;
};

// ------- Person editor (drawer) -------
const PersonEditor = ({person, isNew, t, onClose, onSave, onDelete}) => {
  const computeInitials = (name) => (name||'').split(/\s+/).filter(Boolean).map(w => w[0]).join('').slice(0,2).toUpperCase();
  const [draft, setDraft] = useState(() => person || {
    id:null, name:'', rel:'', phone:'', email:'',
    invited:false, color: window.WI.PEOPLE_COLORS[0], initials:'',
  });
  const [confirmDel, setConfirmDel] = useState(false);

  const set = (k, v) => setDraft(d => {
    const next = {...d, [k]:v};
    if (k === 'name') next.initials = computeInitials(v);
    return next;
  });

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

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

      <div style={{padding:24}}>

        {/* Live preview monogram */}
        <div className="row" style={{gap:14, marginBottom:24, alignItems:'center'}}>
          <Monogram color={draft.color} initials={draft.initials || computeInitials(draft.name) || '·'} size="lg"/>
          <div>
            <div style={{fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:20}}>{draft.name || 'Nome cognome'}</div>
            <div className="muted" style={{fontSize:13}}>{draft.rel || 'relazione'}</div>
          </div>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
          <Field label="Nome e cognome">
            <input className="input" placeholder="Es. Laura Rossi"
                   value={draft.name} onChange={e=>set('name', e.target.value)}/>
          </Field>

          <Field label="Relazione">
            <input className="input" placeholder="moglie, figlio, socio, avvocata…"
                   value={draft.rel || ''} onChange={e=>set('rel', e.target.value)}/>
          </Field>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
          <Field label="Email">
            <input className="input" type="email" placeholder="laura@rossi.it"
                   value={draft.email || ''} onChange={e=>set('email', e.target.value)}/>
          </Field>

          <Field label="Telefono">
            <input className="input" type="tel" placeholder="+39 333 412 7785"
                   value={draft.phone || ''} onChange={e=>set('phone', e.target.value)}/>
          </Field>
        </div>

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

        <Field label="Stato invito" help='Se attivo, alla persona è già stato comunicato il suo ruolo.'>
          <div className="row" style={{gap:10}}>
            <label className="toggle">
              <button className={draft.invited?'on':''} onClick={()=>set('invited', true)}>{t.trustworthy.invited}</button>
              <button className={!draft.invited?'on':''} onClick={()=>set('invited', false)}>{t.trustworthy.not_invited}</button>
            </label>
          </div>
        </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}}>Eliminare questa persona?</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, { TrustworthyPage, PersonDetailDrawer, PersonEditor });
