// WealthIntelligence — Inventory page (unified list) + ItemDetailDrawer
const InventoryPage = ({state, t, setRoute, openItemDetail, openItemEditor}) => {
  const [cat, setCat] = useState('all');
  const [coverage, setCoverage] = useState('all'); // all | in | out
  const [q, setQ] = useState('');

  const cassetteByItem = useMemo(() => {
    const map = {};
    state.cassette.forEach(c => c.itemIds.forEach(iid => {
      (map[iid] = map[iid] || []).push(c);
    }));
    return map;
  }, [state.cassette]);

  const filtered = state.inventory.filter(it => {
    if (cat !== 'all' && it.category !== cat) return false;
    const inAny = (cassetteByItem[it.id] || []).length > 0;
    if (coverage === 'in' && !inAny) return false;
    if (coverage === 'out' && inAny) return false;
    if (q) {
      const s = q.toLowerCase();
      const hay = `${it.name||''} ${it.value||''} ${it.note||''}`.toLowerCase();
      if (!hay.includes(s)) return false;
    }
    return true;
  });

  const counts = {
    all: state.inventory.length,
    in: state.inventory.filter(it => (cassetteByItem[it.id]||[]).length > 0).length,
    out: state.inventory.filter(it => (cassetteByItem[it.id]||[]).length === 0).length,
  };

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

    {/* Coverage filter chips */}
    <div className="row" style={{gap:8, marginBottom:24, flexWrap:'wrap'}}>
      <button onClick={()=>setCoverage('all')} className={`chip ${coverage==='all'?'chip-solid':''}`} style={{cursor:'pointer', border:0, fontFamily:'inherit'}}>
        {t.inventory.all} <span style={{opacity:.55, marginLeft:4}}>{counts.all}</span>
      </button>
      <button onClick={()=>setCoverage('in')} className={`chip ${coverage==='in'?'chip-accent':''}`} style={{cursor:'pointer', border:0, fontFamily:'inherit'}}>
        <span style={{width:7, height:7, borderRadius:'50%', background:'var(--olive-500)'}}/>
        {t.inventory.in_cassetta} <span style={{opacity:.65, marginLeft:4}}>{counts.in}</span>
      </button>
      <button onClick={()=>setCoverage('out')} className={`chip ${coverage==='out'?'chip-warn':''}`} style={{cursor:'pointer', border:0, fontFamily:'inherit'}}>
        <span style={{width:7, height:7, borderRadius:'50%', background:'var(--red-400)'}}/>
        {t.inventory.not_in_cassetta} <span style={{opacity:.65, marginLeft:4}}>{counts.out}</span>
      </button>
    </div>

    <div style={{display:'grid', gridTemplateColumns:'240px 1fr', gap:32}}>
      {/* Sidebar filters */}
      <div>
        <div className="t-eyebrow" style={{marginBottom:10}}>{t.inventory.categories}</div>
        <div style={{display:'flex', flexDirection:'column'}}>
          <button onClick={()=>setCat('all')} style={filterBtn(cat==='all')}>
            <span style={{width:8}}/>
            <span className="grow">{t.inventory.all}</span>
            <span className="muted" style={{fontSize:12}}>{state.inventory.length}</span>
          </button>
          {window.WI.CATEGORIES.map(k => {
            const n = state.inventory.filter(it => it.category===k).length;
            if (!n) return null;
            return <button key={k} onClick={()=>setCat(k)} style={filterBtn(cat===k)}>
              <span style={{width:8}}/>
              <span className="grow">{t.inventory.cat[k]||k}</span>
              <span className="muted" style={{fontSize:12}}>{n}</span>
            </button>;
          })}
        </div>
      </div>

      {/* Main list */}
      <div>
        <div style={{position:'relative', marginBottom:16}}>
          <Icon name="search" size={16} style={{position:'absolute', left:14, top:12, color:'var(--ink-muted)'}}/>
          <input className="input input-search" placeholder={t.inventory.search} value={q} onChange={e=>setQ(e.target.value)}/>
        </div>

        {filtered.length === 0 ? (
          <div className="empty-state">
            <Icon name="inventory" size={28} style={{marginBottom:10, opacity:.5}}/>
            <p style={{margin:0, fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:18}}>{t.inventory.empty}</p>
          </div>
        ) : (
          <div className="card" style={{padding:0, overflow:'hidden'}}>
            <table className="tbl">
              <thead><tr>
                <th>Voce</th>
                <th>Categoria</th>
                <th style={{textAlign:'right'}}>Valore</th>
                <th>Coperta da cassette</th>
                <th style={{width:40}}></th>
              </tr></thead>
              <tbody>
                {filtered.map(it => {
                  const inCass = cassetteByItem[it.id] || [];
                  return <tr key={it.id} onClick={()=>openItemDetail(it)}>
                    <td>
                      <div className="row" style={{gap:12}}>
                        <ItemBadge icon={it.icon} color={it.color} size={32}/>
                        <div>
                          <div style={{fontWeight:500}}>{it.name}</div>
                          <div className="muted" style={{fontSize:12}}>{it.value}</div>
                        </div>
                      </div>
                    </td>
                    <td><span className="chip">{t.inventory.cat[it.category]||it.category}</span></td>
                    <td style={{textAlign:'right'}}>
                      {typeof it.valueEur === 'number'
                        ? <span className="t-num" style={{fontSize:15}}>{fmtEur(it.valueEur)}</span>
                        : <span className="muted" style={{fontSize:12}}>—</span>}
                    </td>
                    <td>
                      {inCass.length === 0 ? (
                        <span className="chip chip-warn">{t.inventory.not_yet}</span>
                      ) : (
                        <div className="row" style={{gap:6, flexWrap:'wrap'}}>
                          {inCass.slice(0,3).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>
                          ))}
                          {inCass.length > 3 && <span className="chip chip-muted">+{inCass.length - 3}</span>}
                        </div>
                      )}
                    </td>
                    <td><Icon name="chevron_right" size={16} style={{color:'var(--ink-muted)'}}/></td>
                  </tr>;
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  </div>;
};

function filterBtn(active){
  return {
    display:'flex', alignItems:'center', gap:10, padding:'8px 10px', borderRadius:8,
    border:0, background: active?'var(--paper-2)':'transparent',
    cursor:'pointer', fontFamily:'inherit', fontSize:13, color:'var(--ink)', textAlign:'left',
  };
}

// ------- Item detail drawer -------
const ItemDetailDrawer = ({item, state, t, onClose, onOpenCassetta, onEdit}) => {
  const cassette = state.cassette.filter(c => c.itemIds.includes(item.id));
  const peopleSet = new Set();
  cassette.forEach(c => c.assignees.forEach(pid => peopleSet.add(pid)));
  const accessible = [...peopleSet].map(pid => state.people.find(p=>p.id===pid)).filter(Boolean);

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

      <div style={{padding:24}}>
        <div className="row" style={{gap:16, marginBottom:24, alignItems:'flex-start'}}>
          <ItemBadge icon={item.icon} color={item.color} size={56}/>
          <div className="grow">
            <span className="chip" style={{marginBottom:6}}>{t.inventory.cat[item.category] || item.category}</span>
            <div className="muted" style={{fontSize:13, marginTop:6}}>{item.value || '—'}</div>
          </div>
        </div>

        {/* Estimated value */}
        <div className="card-paper" style={{padding:18, background:'var(--paper-2)', borderRadius:12, border:'1px solid var(--line)', marginBottom:20}}>
          <div className="t-eyebrow" style={{marginBottom:6}}>{t.inventory.detail.value_eur}</div>
          {typeof item.valueEur === 'number' ? (
            <div className="t-display" style={{fontSize:34, lineHeight:1}}>{fmtEur(item.valueEur)}</div>
          ) : (
            <div className="muted" style={{fontSize:14, fontStyle:'italic'}}>{t.inventory.detail.no_value_eur}</div>
          )}
        </div>

        {/* Note */}
        <div style={{marginBottom:24}}>
          <div className="t-eyebrow" style={{marginBottom:8}}>{t.inventory.detail.note}</div>
          <p style={{margin:0, fontSize:14, lineHeight:1.5, color: item.note ? 'var(--ink)' : 'var(--ink-muted)', fontStyle: item.note ? 'normal' : 'italic'}}>
            {item.note || t.inventory.detail.no_note}
          </p>
        </div>

        {/* In cassette */}
        <div style={{marginBottom:24}}>
          <div className="t-eyebrow" style={{marginBottom:8}}>{t.inventory.detail.in_cassette}</div>
          {cassette.length === 0 ? (
            <p className="muted" style={{margin:0, fontSize:13, fontStyle:'italic'}}>{t.inventory.detail.not_in_any}</p>
          ) : (
            <div style={{display:'flex', flexWrap:'wrap', gap:8}}>
              {cassette.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}
                  <TriggerBadge trigger={c.trigger} t={t} short/>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Accessible to */}
        <div style={{marginBottom:24}}>
          <div className="t-eyebrow" style={{marginBottom:8}}>{t.inventory.detail.accessible_to}</div>
          <div className="muted" style={{fontSize:12, marginBottom:10}}>{t.inventory.detail.accessible_to_help}</div>
          {accessible.length === 0 ? (
            <p className="muted" style={{margin:0, fontSize:13, fontStyle:'italic'}}>{t.inventory.detail.accessible_nobody}</p>
          ) : (
            <div style={{display:'flex', flexWrap:'wrap', gap:8}}>
              {accessible.map(p => (
                <span key={p.id} className="chip" style={{padding:'4px 12px 4px 4px'}}>
                  <Monogram color={p.color} initials={p.initials} size="sm"/>
                  {p.name}
                </span>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="row" style={{
        position:'sticky', bottom:0, padding:'16px 24px', background:'var(--paper)',
        borderTop:'1px solid var(--line)', justifyContent:'flex-end', 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.inventory.detail.edit}</button>
      </div>
    </div>
  </>;
};

// ------- Item editor (drawer) -------
const ItemEditor = ({item, isNew, t, onClose, onSave, onDelete}) => {
  const [draft, setDraft] = useState(() => item || {
    id:null, name:'', category:'altri', icon:'◇', color:'#27666D',
    value:'', valueEur:null, note:'',
  });
  const [confirmDel, setConfirmDel] = useState(false);

  const valid = draft.name.trim().length > 0;
  const set = (k, v) => setDraft(d => ({...d, [k]:v}));

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

      <div style={{padding:24}}>
        <Field label="Nome">
          <input className="input" placeholder='Es. "Casa di Milano"'
                 value={draft.name} onChange={e=>set('name', e.target.value)}/>
        </Field>

        <Field label="Categoria">
          <select className="input" value={draft.category} onChange={e=>set('category', e.target.value)}>
            {window.WI.CATEGORIES.map(k => (
              <option key={k} value={k}>{t.inventory.cat[k]||k}</option>
            ))}
          </select>
        </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={()=>set('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={()=>set('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="Dettaglio (testo libero)" help='IBAN, indirizzo, codice polizza, qualunque cosa identifichi univocamente la voce.'>
          <input className="input" placeholder='Es. "IBAN IT60 X030 6909..." oppure "Via Brera 22, 4 locali"'
                 value={draft.value || ''} onChange={e=>set('value', e.target.value)}/>
        </Field>

        <Field label={t.inventory.detail.value_eur} help='Stima in euro. Lascia vuoto se non applicabile (es. account servizi).'>
          <input className="input" type="number" min="0" step="100" placeholder="0"
                 value={draft.valueEur ?? ''}
                 onChange={e => set('valueEur', e.target.value === '' ? null : Number(e.target.value))}/>
        </Field>

        <Field label={t.inventory.detail.note}>
          <textarea className="input" rows={3} placeholder='Indicazioni utili, dove sono i documenti, contatti…'
                    value={draft.note || ''} onChange={e=>set('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}}>Eliminare questa voce?</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, { InventoryPage, ItemDetailDrawer, ItemEditor });
