// InventoryScreen.jsx — Bi-weekly inventory count.
// Scrollable list with inline number input per item, grouped by category.
// Shows last count so staff can spot wild deltas. Running summary at top.

const { useState: useInv, useMemo: useMemoInv } = React;

const InventoryScreen = ({ onBack, invState, setInvState, currentStaff, showToast }) => {
  const items = window.SAMPLE_INVENTORY;
  const [filter, setFilter] = useInv('All');
  const [search, setSearch] = useInv('');

  const visible = useMemoInv(() => {
    return items.filter(it => {
      if (filter !== 'All' && it.category !== filter) return false;
      if (search && !it.name.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [filter, search]);

  const grouped = useMemoInv(() => {
    const by = {};
    visible.forEach(it => {
      if (!by[it.category]) by[it.category] = [];
      by[it.category].push(it);
    });
    return ['Meat','Vegetable','Sauce','Dry','Other'].filter(c => by[c]).map(c => ({ category: c, items: by[c] }));
  }, [visible]);

  const countedCount = items.filter(it => invState[it.id] !== undefined).length;
  const lowCount = items.filter(it => {
    const v = invState[it.id] ?? it.last;
    return v < it.par * 0.3;
  }).length;

  const updateCount = (id, val) => {
    setInvState(prev => ({ ...prev, [id]: val }));
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        padding: '20px 24px 16px', background: 'var(--bg-surface)',
        borderBottom: '1px solid var(--border-1)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 14 }}>
          
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Bi-weekly · Apr 20, 2026</div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--fg-1)', marginTop: 2 }}>Inventory Count</div>
          </div>
          <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
            <Stat label="Counted" value={`${countedCount}/${items.length}`} />
            <div style={{ width: 1, height: 36, background: 'var(--border-1)' }} />
            <Stat label="Low" value={lowCount} color={lowCount > 0 ? 'var(--danger)' : 'var(--fg-3)'} />
            <div style={{ width: 1, height: 36, background: 'var(--border-1)' }} />
            <Btn variant="primary" size="md" icon="check" onClick={() => showToast({ message: 'Count submitted', staff: currentStaff })}>
              Submit
            </Btn>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            height: 32, padding: '0 12px',
            background: 'var(--bg-sunken)', borderRadius: 999, flex: '0 0 260px',
          }}>
            <Icon name="search" size={14} color="var(--fg-3)" />
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search inventory…"
              style={{ flex: 1, border: 0, outline: 0, background: 'transparent', fontSize: 13, color: 'var(--fg-1)' }}
            />
          </div>
          {['All','Meat','Vegetable','Sauce','Dry','Other'].map(f => (
            <button key={f} onClick={() => setFilter(f)} style={{
              height: 30, padding: '0 12px', borderRadius: 999,
              background: filter === f ? 'var(--fg-1)' : 'transparent',
              color: filter === f ? '#FFFFFF' : 'var(--fg-2)',
              fontSize: 12, fontWeight: 500,
              border: filter === f ? '1px solid var(--fg-1)' : '1px solid var(--border-1)',
            }}>{f}</button>
          ))}
        </div>
      </div>
      <div className="scroll-soft" style={{ flex: 1, overflowY: 'auto', padding: '20px 24px 40px' }}>
        {grouped.map(g => (
          <div key={g.category} style={{ marginBottom: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <CategoryChip category={g.category} />
              <div style={{ fontSize: 12, color: 'var(--fg-3)', fontWeight: 500 }}>{g.items.length} items</div>
              <div style={{ flex: 1, height: 1, background: 'var(--border-1)', marginLeft: 8 }} />
            </div>
            <div style={{
              background: 'var(--bg-surface)', borderRadius: 12,
              border: '1px solid var(--border-1)', overflow: 'hidden',
            }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '2fr 1fr 1fr 1.5fr 1fr',
                padding: '10px 18px',
                background: 'var(--bg-sunken)',
                fontSize: 11, fontWeight: 500, letterSpacing: '0.06em',
                color: 'var(--fg-3)', textTransform: 'uppercase',
              }}>
                <div>Item</div>
                <div style={{ textAlign: 'right' }}>Par</div>
                <div style={{ textAlign: 'right' }}>Last</div>
                <div style={{ textAlign: 'center' }}>Current</div>
                <div style={{ textAlign: 'right' }}>Status</div>
              </div>
              {g.items.map((it, idx) => {
                const val = invState[it.id];
                const isSet = val !== undefined;
                const counted = isSet ? val : it.last;
                const low = counted < it.par * 0.3;
                return (
                  <div key={it.id} style={{
                    display: 'grid',
                    gridTemplateColumns: '2fr 1fr 1fr 1.5fr 1fr',
                    alignItems: 'center',
                    padding: '12px 18px',
                    borderTop: idx === 0 ? 0 : '1px solid var(--border-2)',
                    background: isSet ? 'var(--bg-sunken)' : 'var(--bg-surface)',
                  }}>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg-1)' }}>{it.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{it.vendor} · ${it.price.toFixed(2)}/{it.unit}</div>
                    </div>
                    <div style={{ textAlign: 'right', fontSize: 14, fontWeight: 500, color: 'var(--fg-2)', fontFamily: 'var(--font-num)' }}>
                      {it.par} {it.unit}
                    </div>
                    <div style={{ textAlign: 'right', fontSize: 13, color: 'var(--fg-3)', fontFamily: 'var(--font-num)' }}>
                      {it.last} {it.unit}
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'center', gap: 4 }}>
                      <button onClick={() => updateCount(it.id, Math.max(0, (val ?? it.last) - 0.5))} className="tap" style={{
                        width: 32, height: 36, borderRadius: 8,
                        background: 'var(--bg-surface)', border: '1px solid var(--border-1)',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <Icon name="minus" size={14} strokeWidth={1.8} color="var(--fg-1)" />
                      </button>
                      <input
                        type="number"
                        value={val ?? ''}
                        placeholder={it.last}
                        onChange={e => updateCount(it.id, e.target.value === '' ? undefined : parseFloat(e.target.value))}
                        style={{
                          width: 80, height: 36, textAlign: 'center',
                          fontSize: 15, fontWeight: 500, fontFamily: 'var(--font-num)',
                          color: isSet ? 'var(--fg-1)' : 'var(--fg-3)',
                          background: 'var(--bg-surface)', border: `1px solid ${isSet ? 'var(--fg-1)' : 'var(--border-1)'}`,
                          borderRadius: 8, outline: 'none',
                        }}
                      />
                      <button onClick={() => updateCount(it.id, (val ?? it.last) + 0.5)} className="tap" style={{
                        width: 32, height: 36, borderRadius: 8,
                        background: 'var(--bg-surface)', border: '1px solid var(--border-1)',
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <Icon name="plus" size={14} strokeWidth={1.8} color="var(--fg-1)" />
                      </button>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      {low ? (
                        <span className="pill" style={{ background: 'var(--danger-bg)', color: 'var(--danger)', fontSize: 11, fontWeight: 500, letterSpacing: '0.04em' }}>
                          Low
                        </span>
                      ) : isSet ? (
                        <span className="pill" style={{ background: 'var(--bg-sunken)', color: 'var(--fg-2)', fontSize: 11, fontWeight: 500, letterSpacing: '0.04em' }}>
                          Counted
                        </span>
                      ) : (
                        <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>—</span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

const Stat = ({ label, value, color }) => (
  <div style={{ textAlign: 'right' }}>
    <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: '0.06em', color: 'var(--fg-3)', textTransform: 'uppercase' }}>{label}</div>
    <div style={{ fontSize: 18, fontWeight: 600, fontFamily: 'var(--font-num)', letterSpacing: '-0.02em', marginTop: 1, color: color || 'var(--fg-1)' }}>{value}</div>
  </div>
);

Object.assign(window, { InventoryScreen, Stat });
