// OrderingScreen.jsx — Truck order generator based on par levels.
// Auto-suggests qty = par - last_count - onOrder, editable.
// Exports PDF (mocked preview). Lets staff override and add notes.

const { useState: useOrd, useMemo: useMemoOrd } = React;

const OrderingScreen = ({ onBack, invState, orderState, setOrderState, currentStaff, showToast }) => {
  const items = window.SAMPLE_INVENTORY;
  const [vendor, setVendor] = useOrd('All');
  const [pdfOpen, setPdfOpen] = useOrd(false);

  // Compute suggested qty per item: par - current - onOrder, floored at 0, rounded up
  const withSuggestions = useMemoOrd(() => items.map(it => {
    const current = invState[it.id] ?? it.last;
    const suggested = Math.max(0, Math.ceil(it.par - current - it.onOrder));
    const qty = orderState[it.id] !== undefined ? orderState[it.id] : suggested;
    return { ...it, current, suggested, qty };
  }), [invState, orderState]);

  const filtered = vendor === 'All' ? withSuggestions : withSuggestions.filter(it => it.vendor === vendor);
  const vendors = Array.from(new Set(items.map(it => it.vendor)));

  const toOrder = filtered.filter(it => it.qty > 0);
  const totalLines = toOrder.length;
  const totalCost = toOrder.reduce((s, it) => s + it.qty * it.price, 0);

  const setQty = (id, q) => {
    setOrderState(prev => ({ ...prev, [id]: q }));
  };

  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' }}>Truck Order · {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}</div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--fg-1)', marginTop: 2 }}>Generate Order</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
            <Stat label="Lines" value={totalLines} />
            <div style={{ width: 1, height: 36, background: 'var(--border-1)' }} />
            <Stat label="Est." value={`$${totalCost.toFixed(0)}`} />
            <Btn variant="secondary" size="md" icon="eye" onClick={() => setPdfOpen(true)}>Preview</Btn>
            <Btn variant="primary" size="md" icon="download" onClick={() => { setPdfOpen(true); showToast({ message: 'Order generated', icon: 'pdf' }); }}>Generate</Btn>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            height: 30, padding: '0 12px',
            background: 'var(--bg-sunken)', borderRadius: 999,
            color: 'var(--fg-2)', fontSize: 12, fontWeight: 500,
          }}>
            <Icon name="sparkle" size={13} color="var(--fg-2)" strokeWidth={1.6} />
            Auto-suggested: par − current − on-order · tap to edit
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ display: 'flex', gap: 6 }}>
            {['All', ...vendors].map(v => (
              <button key={v} onClick={() => setVendor(v)} style={{
                height: 30, padding: '0 12px', borderRadius: 999,
                background: vendor === v ? 'var(--fg-1)' : 'transparent',
                color: vendor === v ? '#FFFFFF' : 'var(--fg-2)',
                fontSize: 12, fontWeight: 500,
                border: vendor === v ? '1px solid var(--fg-1)' : '1px solid var(--border-1)',
              }}>{v}</button>
            ))}
          </div>
        </div>
      </div>
      <div className="scroll-soft" style={{ flex: 1, overflowY: 'auto', padding: '20px 24px 40px' }}>
        <div style={{
          background: 'var(--bg-surface)', borderRadius: 12,
          border: '1px solid var(--border-1)', overflow: 'hidden',
        }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: '2fr 1fr 1fr 1fr 1.4fr 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' }}>Current</div>
            <div style={{ textAlign: 'right' }}>On order</div>
            <div style={{ textAlign: 'center' }}>Qty</div>
            <div style={{ textAlign: 'right' }}>Total</div>
          </div>
          {filtered.map((it, idx) => {
            const belowPar = it.current < it.par * 0.5;
            return (
              <div key={it.id} style={{
                display: 'grid',
                gridTemplateColumns: '2fr 1fr 1fr 1fr 1.4fr 1fr',
                alignItems: 'center',
                padding: '12px 18px',
                borderTop: idx === 0 ? 0 : '1px solid var(--border-2)',
                background: it.qty > 0 ? 'var(--bg-sunken)' : 'var(--bg-surface)',
              }}>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg-1)' }}>{it.name}</div>
                    {belowPar && (
                      <span className="pill" style={{ background: 'var(--danger-bg)', color: 'var(--danger)', fontSize: 10, fontWeight: 500, letterSpacing: '0.04em' }}>
                        Low
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{it.vendor} · ${it.price.toFixed(2)}/{it.unit}</div>
                </div>
                <div style={{ textAlign: 'right', fontSize: 13, color: 'var(--fg-2)', fontFamily: 'var(--font-num)' }}>{it.par} {it.unit}</div>
                <div style={{ textAlign: 'right', fontSize: 13, color: belowPar ? 'var(--danger)' : 'var(--fg-2)', fontFamily: 'var(--font-num)' }}>
                  {it.current}
                </div>
                <div style={{ textAlign: 'right', fontSize: 13, color: 'var(--fg-3)', fontFamily: 'var(--font-num)' }}>
                  {it.onOrder > 0 ? `+${it.onOrder}` : '—'}
                </div>
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 4 }}>
                  <button onClick={() => setQty(it.id, Math.max(0, it.qty - 1))} className="tap" style={{
                    width: 30, height: 34, borderRadius: 8,
                    background: 'var(--bg-surface)', border: '1px solid var(--border-1)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon name="minus" size={13} strokeWidth={1.8} color="var(--fg-1)" />
                  </button>
                  <div style={{ position: 'relative' }}>
                    <input
                      type="number"
                      value={it.qty}
                      onChange={e => setQty(it.id, Math.max(0, parseInt(e.target.value) || 0))}
                      style={{
                        width: 64, height: 34, textAlign: 'center',
                        fontSize: 14, fontWeight: 500, fontFamily: 'var(--font-num)',
                        color: it.qty > 0 ? 'var(--fg-1)' : 'var(--fg-3)',
                        background: 'var(--bg-surface)',
                        border: `1px solid ${it.qty > 0 ? 'var(--fg-1)' : 'var(--border-1)'}`,
                        borderRadius: 8, outline: 'none',
                      }}
                    />
                    {orderState[it.id] === undefined && it.suggested > 0 && (
                      <div style={{
                        position: 'absolute', top: -6, right: -4,
                        background: 'var(--fg-1)', color: '#FFFFFF',
                        fontSize: 8, fontWeight: 500, letterSpacing: '0.04em',
                        padding: '1px 4px', borderRadius: 3,
                      }}>AUTO</div>
                    )}
                  </div>
                  <button onClick={() => setQty(it.id, it.qty + 1)} className="tap" style={{
                    width: 30, height: 34, borderRadius: 8,
                    background: 'var(--bg-surface)', border: '1px solid var(--border-1)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon name="plus" size={13} strokeWidth={1.8} color="var(--fg-1)" />
                  </button>
                </div>
                <div style={{ textAlign: 'right', fontSize: 14, fontWeight: 500, fontFamily: 'var(--font-num)', color: it.qty > 0 ? 'var(--fg-1)' : 'var(--fg-3)' }}>
                  {it.qty > 0 ? `$${(it.qty * it.price).toFixed(0)}` : '—'}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <Modal open={pdfOpen} onClose={() => setPdfOpen(false)} width={600} title="Order PDF preview">
        <div style={{ padding: 24, background: 'var(--bg-sunken)' }}>
          <div style={{
            background: '#fff', padding: '32px 28px',
            boxShadow: 'var(--shadow-2)', borderRadius: 4,
            fontFamily: 'var(--font-num)',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', paddingBottom: 16, borderBottom: '2px solid var(--fg-1)' }}>
              <div>
                <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Snap-a-Box</div>
                <div style={{ fontSize: 11, color: 'var(--fg-2)' }}>29807 Jordan Crossing Blvd, Katy TX</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 14, fontWeight: 700 }}>TRUCK ORDER</div>
                <div style={{ fontSize: 11, color: 'var(--fg-2)' }}>{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric', year: 'numeric' })}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-2)' }}>Prepared by {currentStaff.name}</div>
              </div>
            </div>
            <div style={{ marginTop: 16 }}>
              {toOrder.map(it => (
                <div key={it.id} style={{
                  display: 'grid', gridTemplateColumns: '1fr 60px 80px 80px',
                  padding: '6px 0', borderBottom: '1px dashed var(--border-1)',
                  fontSize: 12,
                }}>
                  <div style={{ fontWeight: 600 }}>{it.name} <span style={{ color: 'var(--fg-3)' }}>· {it.vendor}</span></div>
                  <div style={{ textAlign: 'right' }}>{it.qty}</div>
                  <div style={{ textAlign: 'right' }}>{it.unit}</div>
                  <div style={{ textAlign: 'right' }}>${(it.qty * it.price).toFixed(2)}</div>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16, paddingTop: 10, borderTop: '2px solid var(--fg-1)', fontWeight: 800 }}>
              <div>TOTAL · {totalLines} lines</div>
              <div>${totalCost.toFixed(2)}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <Btn variant="secondary" fullWidth icon="pdf">Download PDF</Btn>
            <Btn variant="primary" fullWidth icon="check" onClick={() => { setPdfOpen(false); showToast({ message: 'Order sent to Ryan', staff: currentStaff }); }}>Send to owner</Btn>
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { OrderingScreen });
