// ---------- Production ----------

function Production({ role }) {
  const [rev, setRev] = React.useState(0);
  React.useEffect(() => {
    const h = () => setRev((x) => x + 1);
    window.addEventListener('gh-admin-data', h);
    return () => window.removeEventListener('gh-admin-data', h);
  }, []);

  const [flavorFilter, setFlavorFilter] = React.useState('all');
  const [showLog, setShowLog] = React.useState(false);
  const [lgFlavor, setLgFlavor] = React.useState(FLAVORS[0]?.name || '');
  const [lgQty, setLgQty] = React.useState('15');
  const [lgDate, setLgDate] = React.useState(() => new Date().toISOString().slice(0, 10));
  const [lgStatus, setLgStatus] = React.useState('completed');
  const [lgNotes, setLgNotes] = React.useState('');
  const [lgBy, setLgBy] = React.useState((EMPLOYEES[1] && EMPLOYEES[1].full_name) || '');

  const canEdit = role === 'boss' || role === 'production_manager';

  const batches = window.BATCHES || [];
  const filtered = batches.filter(b => flavorFilter === 'all' || b.flavor === flavorFilter);
  const byStatus = batches.reduce((m,b)=>{ m[b.status]=(m[b.status]||0)+1; return m; }, {});

  return (
    <div style={{display:'flex',flexDirection:'column',gap:20}}>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:14}}>
        <MiniKpi label="Batches · on file" value={batches.length} delta="live" color="var(--accent)"/>
        <MiniKpi label="In progress" value={byStatus.in_progress||0} delta="now" color="var(--gold)"/>
        <MiniKpi label="Planned" value={byStatus.planned||0} delta="next 7d" color="var(--blue)"/>
        <MiniKpi label="Avg batch" value="14 kg" delta="+1.4kg" color="var(--green)"/>
      </div>

      <div style={{display:'flex',justifyContent:'space-between',gap:12,flexWrap:'wrap'}}>
        <select value={flavorFilter} onChange={e=>setFlavorFilter(e.target.value)} style={{padding:'8px 14px',background:'var(--card)',border:'1px solid var(--border)',borderRadius:999,fontSize:13}}>
          <option value="all">All flavors</option>
          {FLAVORS.map(f => <option key={f.id} value={f.name}>{f.name}</option>)}
        </select>
        {canEdit && <button className="btn btn-primary btn-sm" onClick={()=>setShowLog(true)}><Icon.Plus size={13}/> Log batch</button>}
      </div>

      <TablePanel>
        <table style={{width:'100%',borderCollapse:'collapse'}}>
          <thead><tr>
            <Th>Batch</Th><Th>Flavor</Th><Th align="end">Quantity</Th><Th>Date</Th><Th>Produced by</Th><Th>Status</Th><Th>Notes</Th>
          </tr></thead>
          <tbody>
            {filtered.map((b,i) => {
              const flavor = FLAVORS.find(f => f.name === b.flavor);
              return (
                <tr key={b.id + '-' + rev}>
                  <Td><span className="mono" style={{color:'var(--text-dim)',fontSize:11}}>B{String(200-i).padStart(4,'0')}</span></Td>
                  <Td>
                    <div style={{display:'flex',alignItems:'center',gap:10}}>
                      <div style={{width:28,height:28,borderRadius:8,background:flavor?`radial-gradient(circle at 30% 30%, ${flavor.color2}, ${flavor.color})`:'var(--accent)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:14}}>{flavor?.emoji}</div>
                      <span style={{fontWeight:500}}>{b.flavor}</span>
                    </div>
                  </Td>
                  <Td align="end"><span className="mono">{b.quantity_kg} kg</span></Td>
                  <Td><span className="mono" style={{color:'var(--text-dim)',fontSize:11}}>{fmtDate(b.batch_date)}</span></Td>
                  <Td><span style={{color:'var(--text-dim)'}}>{b.produced_by}</span></Td>
                  <Td><StatusBadge status={b.status}/></Td>
                  <Td><span style={{color:'var(--text-dim)',fontSize:12}}>{b.notes || '—'}</span></Td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </TablePanel>

      {showLog && (
        <div className="modal-backdrop" onClick={()=>setShowLog(false)}>
          <div className="modal" onClick={e=>e.stopPropagation()}>
            <h3 style={{fontSize:24,marginBottom:20}}>Log production batch</h3>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Flavor</label><select value={lgFlavor} onChange={e=>setLgFlavor(e.target.value)}>{FLAVORS.map(f=><option key={f.id} value={f.name}>{f.name}</option>)}</select></div>
              <div className="field"><label>Quantity (kg)</label><input type="number" min="0.1" step="0.1" value={lgQty} onChange={e=>setLgQty(e.target.value)}/></div>
              <div className="field"><label>Date</label><input type="date" value={lgDate} onChange={e=>setLgDate(e.target.value)}/></div>
              <div className="field"><label>Status</label><select value={lgStatus} onChange={e=>setLgStatus(e.target.value)}><option value="completed">completed</option><option value="in_progress">in_progress</option><option value="planned">planned</option></select></div>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Produced by</label><input value={lgBy} onChange={e=>setLgBy(e.target.value)} placeholder="Name"/></div>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Notes</label><textarea rows="3" placeholder="Optional notes..." value={lgNotes} onChange={e=>setLgNotes(e.target.value)}/></div>
            </div>
            <div style={{display:'flex',gap:10,justifyContent:'flex-end',marginTop:24}}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setShowLog(false)}>Cancel</button>
              <button className="btn btn-primary btn-sm" onClick={()=>{
                const q = parseFloat(String(lgQty).replace(',', '.'));
                if (!Number.isFinite(q) || q <= 0) return;
                const id = 'bu' + Date.now().toString(36);
                const batch = { id, flavor: lgFlavor, quantity_kg: q, batch_date: lgDate, produced_by: lgBy.trim()||'—', status: lgStatus, notes: lgNotes.trim() };
                if (window.__addProductionBatch) window.__addProductionBatch(batch);
                setShowLog(false);
                setRev(x=>x+1);
              }}>Log batch</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Production });
