// inventory.jsx — InventoryPage
function InventoryPage({ data, onOpenDestiny }) {
  const seed = data || DOPO.SEED;
  const [typeFilter, setTypeFilter] = useState('all');
  const [destinyFilter, setDestinyFilter] = useState('all');
  const [search, setSearch] = useState('');

  const allItems = useMemo(() => [
    ...seed.services.map(s => ({ ...s, _type: 'digital' })),
    ...seed.assets.map(a => ({ ...a, _type: 'real' })),
  ], [seed.services, seed.assets]);

  const filtered = useMemo(() => {
    let list = allItems;
    if (typeFilter !== 'all') list = list.filter(i => i._type === typeFilter);
    if (destinyFilter === 'none') list = list.filter(i => !i.destiny);
    else if (destinyFilter !== 'all') list = list.filter(i => i.destiny === destinyFilter);
    if (search.trim()) {
      const q = search.toLowerCase();
      list = list.filter(i =>
        (i.name || '').toLowerCase().includes(q) ||
        (i.email || '').toLowerCase().includes(q) ||
        (i.category || '').toLowerCase().includes(q)
      );
    }
    return list;
  }, [allItems, typeFilter, destinyFilter, search]);

  const catLabel = Object.fromEntries(
    [...DOPO.CATEGORIES.digital, ...DOPO.CATEGORIES.real].map(c => [c.id, c.label])
  );

  const destinyOptions = [
    { id: 'all', label: 'Tutti' },
    { id: 'people', label: 'Persone', color: 'var(--destiny-people)' },
    { id: 'oblio', label: t.inventory.oblio, color: 'var(--destiny-oblio)' },
    { id: 'hidden', label: t.inventory.hidden, color: 'var(--destiny-hidden)' },
    { id: 'none', label: t.inventory.unassigned, color: 'var(--red-400)' },
  ];

  const destinyCounts = useMemo(() => ({
    all: allItems.length,
    people: allItems.filter(i => i.destiny === 'people').length,
    oblio: allItems.filter(i => i.destiny === 'oblio').length,
    hidden: allItems.filter(i => i.destiny === 'hidden').length,
    none: allItems.filter(i => !i.destiny).length,
  }), [allItems]);

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

      {/* Type tabs */}
      <div className="inv-type-tabs">
        {[
          { id: 'all', label: 'Tutti', n: allItems.length },
          { id: 'digital', label: t.inventory.tab_digital, n: seed.services.length },
          { id: 'real', label: t.inventory.tab_real, n: seed.assets.length },
        ].map(tab => (
          <button
            key={tab.id}
            className={`inv-tab${typeFilter === tab.id ? ' active' : ''}`}
            onClick={() => setTypeFilter(tab.id)}
          >
            {tab.label}
            <span className="inv-tab-count">{tab.n}</span>
          </button>
        ))}
      </div>

      {/* Destiny chips */}
      <div className="row" style={{ gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
        {destinyOptions.map(opt => (
          <button
            key={opt.id}
            onClick={() => setDestinyFilter(opt.id)}
            className={destinyFilter === opt.id ? 'chip chip-solid' : 'chip'}
            style={{ cursor: 'pointer', border: 'none' }}
          >
            {opt.color && (
              <span style={{
                width: 7, height: 7, borderRadius: '50%',
                background: opt.color, flexShrink: 0,
              }} />
            )}
            {opt.label}
            <span style={{ opacity: 0.55, fontSize: 11 }}>{destinyCounts[opt.id]}</span>
          </button>
        ))}
      </div>

      {/* Search */}
      <div className="search-wrap" style={{ marginBottom: 16 }}>
        <Icon name="search" size={16} color="var(--ink-muted)" />
        <input
          type="text"
          className="input input-search"
          placeholder={t.inventory.search}
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>

      {/* Table */}
      <div className="card" style={{ overflow: 'hidden' }}>
        {filtered.length === 0 ? (
          <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--ink-muted)', fontSize: 14 }}>
            Nessun risultato per questa ricerca.
          </div>
        ) : (
          <table className="tbl">
            <thead>
              <tr>
                <th>Voce</th>
                <th>Tipo</th>
                <th>Categoria</th>
                <th>Destino</th>
                <th>Persone</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(item => {
                const { _type, ...cleanItem } = item;
                const itemType = _type === 'digital' ? 'service' : 'asset';
                return (
                  <tr key={item.id} onClick={() => onOpenDestiny(cleanItem, itemType)}>
                    <td>
                      <div className="row" style={{ gap: 12 }}>
                        {_type === 'digital' ? (
                          <ServiceBadge icon={item.icon} color={item.color} size={34} />
                        ) : (
                          <div style={{
                            width: 34, height: 34, borderRadius: 8,
                            background: 'var(--paper-2)', border: '1px solid var(--line)',
                            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
                          }}>
                            {item.icon}
                          </div>
                        )}
                        <div>
                          <div style={{ fontWeight: 500, color: 'var(--ink)', fontSize: 14 }}>
                            {item.name}
                          </div>
                          {item.email && (
                            <div className="t-mono" style={{ marginTop: 2 }}>{item.email}</div>
                          )}
                        </div>
                      </div>
                    </td>
                    <td>
                      <span className="chip chip-muted">
                        {_type === 'real' ? 'Reale' : 'Digitale'}
                      </span>
                    </td>
                    <td>
                      <span className="chip chip-muted">{catLabel[item.category] || item.category}</span>
                    </td>
                    <td>
                      <DestinyPill destiny={item.destiny} />
                    </td>
                    <td>
                      {item.assignees && item.assignees.length > 0
                        ? <MonoStack ids={item.assignees} people={seed.people} />
                        : <span style={{ color: 'var(--gr-300)', fontSize: 13 }}>—</span>
                      }
                    </td>
                    <td style={{ textAlign: 'right' }}>
                      <button
                        className="btn btn-ghost btn-sm"
                        onClick={e => { e.stopPropagation(); onOpenDestiny(cleanItem, itemType); }}
                      >
                        <Icon name="edit" size={14} />
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { InventoryPage });
