// Shop tab: Services | Stock segmented. Services are what the shop sells (priced, addable,
// variants link to stock). Stock is parts-on-shelf (cost, supplier, qty, auto-consumed by services).
const { useState: useState3, useMemo: useMemo3 } = React;

// ---- STOCK LOOKUP ----
const stockBySku = (stock) => Object.fromEntries(stock.map(s => [s.sku, s]));

// ==========================================================
// SERVICES TAB
// ==========================================================
const ServicesList = ({ services, stock, onAddService, onAddVariant, onEditVariant, onEditService }) => {
  const [expanded, setExpanded] = useState3(new Set(['screen']));
  const bySku = useMemo3(() => stockBySku(stock), [stock]);
  const toggle = (id) => setExpanded(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });

  // insight: how many variants are blocked by OOS stock?
  const blocked = useMemo3(() => {
    let n = 0;
    services.forEach(s => {
      if (s.kind !== 'variant') return;
      s.variants.forEach(v => { if (bySku[v.sku]?.qty === 0) n++; });
    });
    return n;
  }, [services, bySku]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {/* Insight strip */}
      {blocked > 0 && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
          background: 'rgba(255,69,58,0.08)', border: '1px solid rgba(255,69,58,0.25)', borderRadius: 12,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#ff453a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>
          <div style={{ flex: 1, fontSize: 12.5, color: 'rgba(255,255,255,0.88)' }}>
            <strong style={{ color: '#ff453a' }}>{blocked}</strong> service{blocked > 1 ? 's' : ''} blocked by out-of-stock parts
          </div>
        </div>
      )}

      {services.map(s => {
        const open = expanded.has(s.id);
        const variantCount = s.kind === 'variant' ? s.variants.length : 1;
        const priceRange = s.kind === 'flat'
          ? `£${s.price}`
          : (() => {
              const prices = s.variants.map(v => v.price);
              const min = Math.min(...prices), max = Math.max(...prices);
              return min === max ? `£${min}` : `£${min}–${max}`;
            })();
        const lowVariants = s.kind === 'variant'
          ? s.variants.filter(v => (bySku[v.sku]?.qty ?? 0) <= (bySku[v.sku]?.min ?? 0)).length
          : 0;

        return (
          <article key={s.id} style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 14, overflow: 'hidden' }}>
            <button onClick={() => toggle(s.id)} style={{
              width: '100%', padding: 14,
              background: 'transparent', border: 0, color: 'inherit', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 10,
                background: 'rgba(255,107,26,0.08)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <ServiceIcon kind={s.icon} size={20} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.011em' }}>{s.name}</div>
                <div style={{ marginTop: 3, fontSize: 12, color: '#86868b' }}>
                  {s.kind === 'flat' ? 'Flat price' : `${variantCount} device${variantCount > 1 ? 's' : ''}`}
                  {lowVariants > 0 && (
                    <span style={{ color: '#ff9f0a', marginLeft: 8 }}>· {lowVariants} low stock</span>
                  )}
                </div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <Mono style={{ fontSize: 15, fontWeight: 600 }}>{priceRange}</Mono>
                <div style={{ marginTop: 3, fontSize: 10, color: '#3a3a3c' }}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 200ms' }}><path d="m6 9 6 6 6-6"/></svg>
                </div>
              </div>
            </button>

            <div style={{
              overflow: 'hidden',
              maxHeight: open ? 2000 : 0,
              transition: 'max-height 380ms cubic-bezier(0.25,0.1,0.25,1)',
            }}>
              <div style={{ padding: '0 14px 14px', borderTop: '1px solid #1a1a1a' }}>
                <div style={{ padding: '12px 0', fontSize: 13, color: '#86868b', lineHeight: 1.5 }}>
                  {s.description}
                </div>
                {s.kind === 'flat' ? (
                  <button onClick={() => onEditService(s)} style={{
                    width: '100%', padding: '12px 14px', borderRadius: 10,
                    background: '#1d1d1f', border: 0, color: '#fff', cursor: 'pointer',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  }}>
                    <span style={{ fontSize: 13 }}>{s.durationMin} min · Redeemable against repair</span>
                    <Mono style={{ fontSize: 15, fontWeight: 600 }}>£{s.price}</Mono>
                  </button>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    {s.variants.map(v => {
                      const stk = bySku[v.sku];
                      const qty = stk?.qty ?? 0;
                      const min = stk?.min ?? 0;
                      return (
                        <button key={v.id} onClick={() => onEditVariant(s, v)} style={{
                          display: 'grid', gridTemplateColumns: '1fr auto', gap: 10,
                          padding: '10px 12px', background: '#000',
                          border: '1px solid #1a1a1a', borderRadius: 10,
                          cursor: 'pointer', textAlign: 'left', color: 'inherit',
                        }}>
                          <div style={{ minWidth: 0 }}>
                            <div style={{ fontSize: 14, fontWeight: 500 }}>{v.device}</div>
                            <div style={{ marginTop: 3, display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
                              <Mono style={{ fontSize: 10, color: '#3a3a3c' }}>{v.sku}</Mono>
                              {stk && <StockBadge qty={qty} min={min} />}
                            </div>
                          </div>
                          <div style={{ textAlign: 'right' }}>
                            <Mono style={{ fontSize: 15, fontWeight: 600 }}>£{v.price}</Mono>
                            <div style={{ marginTop: 2, fontSize: 10, color: '#86868b' }}>{v.durationMin} min</div>
                          </div>
                        </button>
                      );
                    })}
                    <button onClick={() => onAddVariant(s)} style={{
                      padding: '11px 12px', background: 'transparent',
                      border: '1px dashed #2c2c2e', borderRadius: 10,
                      color: '#86868b', font: '500 13px Inter', cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                    }}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
                      Add device
                    </button>
                  </div>
                )}
              </div>
            </div>
          </article>
        );
      })}

      <button onClick={onAddService} style={{
        marginTop: 4, padding: '14px 12px',
        background: 'transparent', border: '1px dashed #2c2c2e', borderRadius: 12,
        color: '#FF6B1A', font: '600 14px Inter', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
        New service type
      </button>
    </div>
  );
};

// Edit variant sheet (also used for "add variant" with blank)
const VariantSheet = ({ service, variant, stock, onClose, onSave, onDelete }) => {
  const [device, setDevice] = useState3('');
  const [price, setPrice] = useState3('');
  const [sku, setSku] = useState3('');
  const [dur, setDur] = useState3('');
  React.useEffect(() => {
    if (!service) return;
    setDevice(variant?.device ?? '');
    setPrice(variant?.price != null ? String(variant.price) : '');
    setSku(variant?.sku ?? '');
    setDur(variant?.durationMin != null ? String(variant.durationMin) : '45');
  }, [service, variant]);
  if (!service) return null;
  const isNew = !variant;
  const stk = stock.find(s => s.sku === sku);
  return (
    <Sheet open={!!service} onClose={onClose}
      subtitle={`${service.name.toUpperCase()} · ${isNew ? 'NEW DEVICE' : 'EDIT'}`}
      title={isNew ? 'Add device variant' : variant.device}
      actions={[
        <PrimaryButton key="save" onClick={() => onSave({ device, price: Number(price) || 0, sku, durationMin: Number(dur) || 45 })}>
          {isNew ? 'Add variant' : 'Save changes'}
        </PrimaryButton>,
        !isNew && <GhostButton key="del" onClick={() => onDelete(variant)}>Delete</GhostButton>,
        <GhostButton key="cancel" onClick={onClose}>Cancel</GhostButton>,
      ].filter(Boolean)}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Field label="DEVICE"><input value={device} onChange={e => setDevice(e.target.value)} style={fieldInput} placeholder="e.g. iPhone 15 Pro Max" /></Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Field label="PRICE £">
            <Mono><input value={price} onChange={e => setPrice(e.target.value.replace(/[^\d.]/g, ''))} style={fieldInput} placeholder="0.00" inputMode="decimal" /></Mono>
          </Field>
          <Field label="DURATION (MIN)">
            <Mono><input value={dur} onChange={e => setDur(e.target.value.replace(/\D/g, ''))} style={fieldInput} inputMode="numeric" /></Mono>
          </Field>
        </div>
        <Field label="STOCK LINK (SKU)">
          <Mono><input value={sku} onChange={e => setSku(e.target.value.toUpperCase())} style={fieldInput} placeholder="SCR-IP15PM-TI" /></Mono>
        </Field>
        {stk ? (
          <div style={{ padding: '10px 12px', background: 'rgba(48,209,88,0.06)', border: '1px solid rgba(48,209,88,0.2)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
            <StockBadge qty={stk.qty} min={stk.min} />
            <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.85)' }}>{stk.name} · £{stk.cost} cost</span>
          </div>
        ) : sku ? (
          <div style={{ padding: '10px 12px', background: 'rgba(255,159,10,0.06)', border: '1px solid rgba(255,159,10,0.2)', borderRadius: 10, fontSize: 12.5, color: '#ff9f0a' }}>
            No stock item with that SKU. Add one in Stock tab.
          </div>
        ) : null}
      </div>
    </Sheet>
  );
};

// ==========================================================
// STOCK TAB
// ==========================================================
const StockList = ({ stock, onEdit, onAdd, onAdjust }) => {
  const [q, setQ] = useState3('');
  const [filter, setFilter] = useState3('all');
  const filtered = useMemo3(() => stock.filter(s => {
    if (filter === 'low' && s.qty > s.min) return false;
    if (filter === 'out' && s.qty > 0) return false;
    if (q) {
      const hay = (s.name + ' ' + s.sku + ' ' + s.supplier).toLowerCase();
      if (!hay.includes(q.toLowerCase())) return false;
    }
    return true;
  }), [stock, q, filter]);

  const totalValue = stock.reduce((a, s) => a + s.cost * s.qty, 0);
  const outCount = stock.filter(s => s.qty === 0).length;
  const lowCount = stock.filter(s => s.qty > 0 && s.qty <= s.min).length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {/* Inventory summary */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr 1fr', gap: 8 }}>
        <div style={{ padding: '10px 12px', background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 12 }}>
          <div style={{ fontSize: 10, color: '#86868b', letterSpacing: '0.15em' }}>ON HAND</div>
          <Mono style={{ fontSize: 20, fontWeight: 600, marginTop: 2, display: 'block' }}>£{totalValue.toLocaleString('en-GB')}</Mono>
        </div>
        <div style={{ padding: '10px 12px', background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 12 }}>
          <div style={{ fontSize: 10, color: '#86868b', letterSpacing: '0.15em' }}>LOW</div>
          <Mono style={{ fontSize: 20, fontWeight: 600, marginTop: 2, color: lowCount ? '#ff9f0a' : '#fff', display: 'block' }}>{lowCount}</Mono>
        </div>
        <div style={{ padding: '10px 12px', background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 12 }}>
          <div style={{ fontSize: 10, color: '#86868b', letterSpacing: '0.15em' }}>OUT</div>
          <Mono style={{ fontSize: 20, fontWeight: 600, marginTop: 2, color: outCount ? '#ff453a' : '#fff', display: 'block' }}>{outCount}</Mono>
        </div>
      </div>

      {/* Search + filters */}
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <div style={{ flex: 1, position: 'relative' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#3a3a3c" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)' }}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search SKU, name, supplier"
            style={{ width: '100%', height: 38, padding: '0 12px 0 34px', background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 10, color: '#fff', font: '13px Inter', outline: 'none' }} />
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6 }}>
        {[['all', 'All', stock.length], ['low', 'Low', lowCount], ['out', 'Out', outCount]].map(([k, lbl, n]) => (
          <button key={k} onClick={() => setFilter(k)} style={{
            height: 30, padding: '0 12px',
            background: filter === k ? '#1d1d1f' : 'transparent',
            color: filter === k ? '#fff' : '#86868b',
            border: 0, borderRadius: 980,
            boxShadow: filter === k ? 'none' : 'inset 0 0 0 1px #1a1a1a',
            font: '500 12px Inter', cursor: 'pointer',
          }}>{lbl} · {n}</button>
        ))}
      </div>

      {/* Stock rows */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.map(s => (
          <article key={s.sku} style={{ padding: 12, background: '#0a0a0a', border: '1px solid #1a1a1a', borderRadius: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <button onClick={() => onEdit(s)} style={{ flex: 1, minWidth: 0, background: 'transparent', border: 0, padding: 0, textAlign: 'left', cursor: 'pointer', color: 'inherit' }}>
                <div style={{ fontSize: 14, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
                <div style={{ marginTop: 4, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  <Mono style={{ fontSize: 10, color: '#3a3a3c' }}>{s.sku}</Mono>
                  <span style={{ fontSize: 11, color: '#86868b' }}>· {s.supplier}</span>
                  <span style={{ fontSize: 11, color: '#86868b' }}>· £{s.cost} cost</span>
                </div>
              </button>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <button onClick={() => onAdjust(s, -1)} style={qbtn(s.qty <= 0)} disabled={s.qty <= 0}>−</button>
                <Mono style={{
                  minWidth: 36, textAlign: 'center', fontSize: 17, fontWeight: 600,
                  color: s.qty === 0 ? '#ff453a' : s.qty <= s.min ? '#ff9f0a' : '#fff',
                }}>{s.qty}</Mono>
                <button onClick={() => onAdjust(s, +1)} style={qbtn(false)}>+</button>
              </div>
            </div>
            {(s.qty === 0 || s.qty <= s.min) && (
              <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid #1a1a1a', display: 'flex', alignItems: 'center', gap: 8 }}>
                <StockBadge qty={s.qty} min={s.min} />
                <span style={{ fontSize: 11.5, color: '#86868b' }}>Min {s.min} · turns {s.turn}/mo · last in {s.lastIn}</span>
              </div>
            )}
          </article>
        ))}
      </div>

      <button onClick={onAdd} style={{
        marginTop: 2, padding: '14px 12px',
        background: 'transparent', border: '1px dashed #2c2c2e', borderRadius: 12,
        color: '#FF6B1A', font: '600 14px Inter', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
        New stock item
      </button>
    </div>
  );
};

const StockSheet = ({ item, onClose, onSave, onDelete, isNew }) => {
  const [sku, setSku] = useState3('');
  const [name, setName] = useState3('');
  const [cost, setCost] = useState3('');
  const [qty, setQty] = useState3('');
  const [min, setMin] = useState3('');
  const [supplier, setSupplier] = useState3('');
  React.useEffect(() => {
    if (!item) return;
    setSku(item.sku ?? '');
    setName(item.name ?? '');
    setCost(item.cost != null ? String(item.cost) : '');
    setQty(item.qty != null ? String(item.qty) : '0');
    setMin(item.min != null ? String(item.min) : '1');
    setSupplier(item.supplier ?? '');
  }, [item]);
  if (!item) return null;
  return (
    <Sheet open={!!item} onClose={onClose}
      subtitle={isNew ? 'NEW STOCK ITEM' : 'STOCK ITEM'}
      title={isNew ? 'Add part' : item.name}
      actions={[
        <PrimaryButton key="save" onClick={() => onSave({
          sku, name, cost: Number(cost) || 0,
          qty: Number(qty) || 0, min: Number(min) || 0, supplier,
        })}>{isNew ? 'Add item' : 'Save changes'}</PrimaryButton>,
        !isNew && <GhostButton key="del" onClick={() => onDelete(item)}>Delete</GhostButton>,
        <GhostButton key="cancel" onClick={onClose}>Cancel</GhostButton>,
      ].filter(Boolean)}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Field label="SKU"><Mono><input value={sku} onChange={e => setSku(e.target.value.toUpperCase())} style={fieldInput} placeholder="SCR-IP15PM-TI" /></Mono></Field>
        <Field label="NAME"><input value={name} onChange={e => setName(e.target.value)} style={fieldInput} placeholder="iPhone 15 Pro Max screen" /></Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
          <Field label="COST £"><Mono><input value={cost} onChange={e => setCost(e.target.value.replace(/[^\d.]/g, ''))} style={fieldInput} inputMode="decimal" /></Mono></Field>
          <Field label="QTY"><Mono><input value={qty} onChange={e => setQty(e.target.value.replace(/\D/g, ''))} style={fieldInput} inputMode="numeric" /></Mono></Field>
          <Field label="MIN"><Mono><input value={min} onChange={e => setMin(e.target.value.replace(/\D/g, ''))} style={fieldInput} inputMode="numeric" /></Mono></Field>
        </div>
        <Field label="SUPPLIER"><input value={supplier} onChange={e => setSupplier(e.target.value)} style={fieldInput} placeholder="MobileSentrix" /></Field>
      </div>
    </Sheet>
  );
};

// ==========================================================
// CSV IMPORT (shared)
// ==========================================================
const CSVImportSheet = ({ open, target, onClose, onApply }) => {
  const [text, setText] = useState3('');
  const [parsed, setParsed] = useState3(null);
  React.useEffect(() => {
    if (!open) { setText(''); setParsed(null); }
  }, [open]);

  const sample = target === 'stock'
    ? `sku,name,cost,qty,min,supplier\nSCR-IP15PM-TI,iPhone 15 Pro Max screen,110,3,1,MobileSentrix\nBAT-IP14,iPhone 14 battery,22,4,2,MobileSentrix`
    : `service,device,price,sku,durationMin\nScreen repair,iPhone 15,149,SCR-IP15-BLK,45\nBattery swap,iPhone 14,55,BAT-IP14,30`;

  const parse = () => {
    const lines = text.trim().split(/\r?\n/).filter(Boolean);
    if (lines.length < 2) { setParsed({ error: 'No rows found' }); return; }
    const header = lines[0].split(',').map(s => s.trim());
    const rows = lines.slice(1).map(l => {
      const cells = l.split(',').map(s => s.trim());
      return Object.fromEntries(header.map((h, i) => [h, cells[i]]));
    });
    setParsed({ rows, header });
  };

  return (
    <Sheet open={open} onClose={onClose}
      subtitle={`CSV IMPORT · ${target === 'stock' ? 'STOCK' : 'SERVICES'}`}
      title={`Bulk update ${target}`}
      actions={[
        parsed && !parsed.error
          ? <PrimaryButton key="apply" onClick={() => onApply(parsed.rows)}>Apply {parsed.rows.length} row{parsed.rows.length > 1 ? 's' : ''}</PrimaryButton>
          : <PrimaryButton key="parse" onClick={parse} disabled={!text.trim()}>Preview changes</PrimaryButton>,
        <GhostButton key="cancel" onClick={onClose}>Cancel</GhostButton>,
      ]}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ fontSize: 12, color: '#86868b', lineHeight: 1.5 }}>
          Paste CSV. First row = headers. <button onClick={() => setText(sample)} style={{ background: 'transparent', border: 0, color: '#FF6B1A', cursor: 'pointer', font: '600 12px Inter', padding: 0 }}>Use sample</button>
        </div>
        <Field label="CSV">
          <Mono><textarea value={text} onChange={e => setText(e.target.value)} rows={6} style={{ ...fieldInput, resize: 'none', lineHeight: 1.5, fontSize: 11 }} placeholder={sample} /></Mono>
        </Field>
        {parsed?.error && <div style={{ color: '#ff453a', fontSize: 13 }}>{parsed.error}</div>}
        {parsed?.rows && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <Eyebrow>{parsed.rows.length} ROWS PARSED</Eyebrow>
            {parsed.rows.slice(0, 4).map((r, i) => (
              <div key={i} style={{ padding: '8px 10px', background: '#000', border: '1px solid #1a1a1a', borderRadius: 8, fontSize: 11 }}>
                <Mono>{parsed.header.map(h => `${h}=${r[h] ?? '—'}`).join('  ')}</Mono>
              </div>
            ))}
            {parsed.rows.length > 4 && <div style={{ fontSize: 11, color: '#86868b', textAlign: 'center' }}>+{parsed.rows.length - 4} more</div>}
          </div>
        )}
      </div>
    </Sheet>
  );
};

// ==========================================================
// SHOP TAB (wraps Services/Stock with segmented control)
// ==========================================================
const ShopTab = () => {
  const [seg, setSeg] = useState3('services');
  const [services, setServices] = useState3(SERVICES_SEED);
  const [stock, setStock] = useState3(STOCK_SEED);

  // sheet state
  const [variantSheet, setVariantSheet] = useState3(null);   // { service, variant? }
  const [stockSheet, setStockSheet] = useState3(null);       // item or {new:true}
  const [csvTarget, setCsvTarget] = useState3(null);         // 'services'|'stock'|null
  const [serviceAdd, setServiceAdd] = useState3(false);

  const bySku = useMemo3(() => stockBySku(stock), [stock]);
  const outCount = stock.filter(s => s.qty === 0).length;
  const lowCount = stock.filter(s => s.qty > 0 && s.qty <= s.min).length;

  // VARIANT save/delete
  const saveVariant = (payload) => {
    const { service, variant } = variantSheet;
    setServices(prev => prev.map(s => {
      if (s.id !== service.id) return s;
      if (variant) {
        return { ...s, variants: s.variants.map(v => v.id === variant.id ? { ...v, ...payload } : v) };
      }
      return { ...s, variants: [...s.variants, { id: 'v-' + Date.now(), ...payload }] };
    }));
    setVariantSheet(null);
  };
  const deleteVariant = (variant) => {
    const { service } = variantSheet;
    setServices(prev => prev.map(s => s.id === service.id ? { ...s, variants: s.variants.filter(v => v.id !== variant.id) } : s));
    setVariantSheet(null);
  };

  // STOCK save/delete/adjust
  const saveStock = (payload) => {
    const isNew = !stock.find(s => s.sku === stockSheet.sku);
    setStock(prev => isNew
      ? [...prev, { ...payload, lastIn: 'today', turn: 0 }]
      : prev.map(s => s.sku === stockSheet.sku ? { ...s, ...payload } : s));
    setStockSheet(null);
  };
  const deleteStock = (item) => {
    setStock(prev => prev.filter(s => s.sku !== item.sku));
    setStockSheet(null);
  };
  const adjustStock = (item, delta) => {
    setStock(prev => prev.map(s => s.sku === item.sku ? { ...s, qty: Math.max(0, s.qty + delta) } : s));
  };

  // Services: add flat service placeholder
  const addFlatService = (name) => {
    const id = name.toLowerCase().replace(/\s+/g, '-').slice(0, 16) + '-' + Date.now().toString(36).slice(-3);
    setServices(prev => [...prev, { id, name, kind: 'variant', icon: 'diag', description: 'Add a description.', variants: [] }]);
    setServiceAdd(false);
  };

  // CSV apply
  const applyCSV = (rows) => {
    if (csvTarget === 'stock') {
      setStock(prev => {
        const map = new Map(prev.map(s => [s.sku, s]));
        rows.forEach(r => {
          if (!r.sku) return;
          map.set(r.sku, {
            ...(map.get(r.sku) || { turn: 0, lastIn: 'today' }),
            sku: r.sku, name: r.name ?? map.get(r.sku)?.name ?? r.sku,
            cost: Number(r.cost) || 0, qty: Number(r.qty) || 0,
            min: Number(r.min) || 0, supplier: r.supplier ?? '',
          });
        });
        return Array.from(map.values());
      });
    } else {
      // simplified: add each row as variant under a matching service, creating service if missing
      setServices(prev => {
        const out = [...prev];
        rows.forEach(r => {
          if (!r.service || !r.device) return;
          let s = out.find(x => x.name.toLowerCase() === r.service.toLowerCase());
          if (!s) {
            s = { id: 'svc-' + Date.now() + Math.random().toString(36).slice(-3), name: r.service, kind: 'variant', icon: 'diag', description: '', variants: [] };
            out.push(s);
          }
          s.variants = [...s.variants, { id: 'v-' + Date.now() + Math.random().toString(36).slice(-3), device: r.device, price: Number(r.price) || 0, sku: r.sku || '', durationMin: Number(r.durationMin) || 45 }];
        });
        return out;
      });
    }
    setCsvTarget(null);
  };

  return (
    <div>
      <SegmentedControl
        value={seg}
        onChange={setSeg}
        options={[
          { value: 'services', label: 'Services', badge: services.length },
          { value: 'stock',    label: 'Stock',    badge: outCount > 0 ? outCount : lowCount > 0 ? lowCount : stock.length },
        ]}
      />
      {/* CSV row */}
      <div style={{ marginTop: 10, marginBottom: 12, display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
        <button onClick={() => setCsvTarget(seg)} style={{
          height: 32, padding: '0 12px',
          background: 'transparent', color: '#86868b',
          border: 0, borderRadius: 8, boxShadow: 'inset 0 0 0 1px #1a1a1a',
          font: '500 12px Inter', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8l-5-5-5 5"/><path d="M12 3v12"/></svg>
          Import CSV
        </button>
      </div>

      {seg === 'services' ? (
        <ServicesList
          services={services}
          stock={stock}
          onAddService={() => setServiceAdd(true)}
          onAddVariant={(service) => setVariantSheet({ service, variant: null })}
          onEditVariant={(service, variant) => setVariantSheet({ service, variant })}
          onEditService={(s) => setVariantSheet({ service: s, variant: null })}
        />
      ) : (
        <StockList
          stock={stock}
          onAdd={() => setStockSheet({ sku: '', name: '', cost: 0, qty: 0, min: 1, supplier: '' })}
          onEdit={(s) => setStockSheet(s)}
          onAdjust={adjustStock}
        />
      )}

      <VariantSheet
        service={variantSheet?.service}
        variant={variantSheet?.variant}
        stock={stock}
        onClose={() => setVariantSheet(null)}
        onSave={saveVariant}
        onDelete={deleteVariant}
      />
      <StockSheet
        item={stockSheet}
        isNew={stockSheet && !stock.find(s => s.sku === stockSheet.sku)}
        onClose={() => setStockSheet(null)}
        onSave={saveStock}
        onDelete={deleteStock}
      />
      <CSVImportSheet
        open={!!csvTarget}
        target={csvTarget}
        onClose={() => setCsvTarget(null)}
        onApply={applyCSV}
      />
      {serviceAdd && <AddServiceSheet onClose={() => setServiceAdd(false)} onCreate={addFlatService} />}
    </div>
  );
};

const AddServiceSheet = ({ onClose, onCreate }) => {
  const [name, setName] = useState3('');
  return (
    <Sheet open onClose={onClose} subtitle="NEW SERVICE TYPE" title="What do you want to add?"
      actions={[
        <PrimaryButton key="c" onClick={() => onCreate(name)} disabled={!name.trim()}>Create</PrimaryButton>,
        <GhostButton key="x" onClick={onClose}>Cancel</GhostButton>,
      ]}>
      <Field label="NAME">
        <input autoFocus value={name} onChange={e => setName(e.target.value)} style={fieldInput} placeholder="e.g. Charge port repair" />
      </Field>
      <div style={{ marginTop: 10, fontSize: 12, color: '#86868b', lineHeight: 1.5 }}>
        You'll add device variants & prices next. Each variant links to a stock SKU so completing a booking auto-decrements inventory.
      </div>
    </Sheet>
  );
};

Object.assign(window, { ShopTab });
