/* =============================================================
   CoreIQ Office — Stock Line Editor
   Replaces the old "New stock line" form with a comprehensive
   tabbed editor that doubles as the Edit view for existing lines.
   Tabs: Details · Pricing · Suppliers (PDEs) · Barcodes · Promotions
         · Printing · History · Movements · Notes · Multi-store
   ============================================================= */
const { useState: sleUseState, useMemo: sleUseMemo } = React;

const SLE_TABS = [
  { id: "details",     label: "Details" },
  { id: "pricing",     label: "Pricing" },
  { id: "suppliers",   label: "Suppliers (PDEs)" },
  { id: "barcodes",    label: "Barcodes" },
  { id: "promos",      label: "Promotions & Clubs" },
  { id: "printing",    label: "Printing" },
  { id: "multistore",  label: "Multi-store" },
  { id: "movements",   label: "Movements" },
  { id: "history",     label: "History" },
  { id: "notes",       label: "Notes" },
];

function StockLineEditor() {
  const { setScreen, screenState, pushToast } = window.useOffice();
  const editing = screenState.activeProductId
    ? OD.PRODUCTS.find(p => p.id === screenState.activeProductId)
    : null;
  const isNew = !editing;

  // ---------------------------------------------------------------
  // Form state — seed from an existing product or sensible defaults.
  // Field names mirror Minfos/FRED conventions where reasonable so
  // the model maps cleanly to migration.
  // ---------------------------------------------------------------
  const [form, setForm] = sleUseState(() => sleSeedForm(editing));
  const [tab, setTab] = sleUseState("details");
  const [dirty, setDirty] = sleUseState(false);

  function set(patch) { setForm(f => ({ ...f, ...patch })); setDirty(true); }
  function setField(k, v) { set({ [k]: v }); }

  // Derived pricing
  const costEx     = parseFloat(form.costEx)     || 0;
  const supplierEx = parseFloat(form.supplierEx) || 0;
  const taxRate    = form.taxRate || 0;
  const costInc    = costEx * (1 + taxRate);
  const sellEx     = parseFloat(form.sellEx)  || 0;
  const sellInc    = sellEx * (1 + taxRate);
  const gstAmount  = sellInc - sellEx;
  const markup     = costEx > 0 ? ((sellEx - costEx) / costEx) * 100 : 0;
  const gp         = sellEx > 0 ? ((sellEx - costEx) / sellEx) * 100 : 0;

  // Validation
  const valid =
    !!form.name &&
    !!form.sku &&
    !!form.dept &&
    !!form.sub &&
    sellEx > 0;

  function save() {
    pushToast({
      kind: "paid",
      icon: "check-circle",
      title: `${isNew ? "Stock line created" : "Stock line saved"} · ${form.name}`,
      meta: `SKU ${form.sku} · ${oMoney(sellEx)} ex GST`,
    });
    setDirty(false);
    setScreen(isNew ? "stockOverview" : "productDetail");
  }
  function cancel() {
    setScreen(isNew ? "stockOverview" : "productDetail");
  }

  return (
    <div className="off-screen sle-screen">
      <header className="off-screen-header sle-header">
        <div className="off-screen-header-meta">
          <button className="pd-back" onClick={() => setScreen(isNew ? "stockOverview" : "productDetail")}>
            <OIcon name="chevron-right" width={11} height={11} style={{transform:'rotate(180deg)'}}/>
            {isNew ? "Stock overview" : (editing?.name || "Product")}
          </button>
          <h2 className="off-screen-title sle-title">
            {isNew ? "New stock line" : "Edit stock line details"}
          </h2>
          <div className="sle-subtitle">
            {form.name ? <span>{form.name}</span> : <span style={{color:'var(--text-subtle)'}}>Untitled</span>}
            {form.sku && <><span className="sle-dot">·</span><span className="sle-sku">{form.sku}</span></>}
            {dirty && <span className="sle-dirty">Unsaved changes</span>}
          </div>
        </div>
        <div className="off-screen-actions">
          {!isNew && <button className="btn btn--ghost btn--sm"><OIcon name="printer"/> Print labels</button>}
          <button className="btn btn--ghost btn--sm" onClick={cancel}>Close</button>
          <button className="btn btn--primary btn--sm" onClick={save} disabled={!valid}>
            <OIcon name="check"/> Save
          </button>
        </div>
      </header>

      {/* Tab strip */}
      <nav className="sle-tabs" role="tablist">
        {SLE_TABS.map(t => (
          <button
            key={t.id}
            role="tab"
            aria-selected={tab === t.id}
            className={"sle-tab" + (tab === t.id ? " is-active" : "")}
            onClick={() => setTab(t.id)}
            disabled={isNew && ["history","movements"].includes(t.id)}
            title={isNew && ["history","movements"].includes(t.id) ? "Available after the line is created" : undefined}
          >
            {t.label}
          </button>
        ))}
      </nav>

      <div className="off-screen-body sle-body">
        {tab === "details"    && <DetailsTab form={form} set={set} setField={setField}/>}
        {tab === "pricing"    && <PricingTab form={form} set={set} setField={setField}
                                  costEx={costEx} costInc={costInc} sellEx={sellEx} sellInc={sellInc}
                                  gstAmount={gstAmount} markup={markup} gp={gp} supplierEx={supplierEx}/>}
        {tab === "suppliers"  && <SuppliersTab form={form} set={set}/>}
        {tab === "barcodes"   && <BarcodesTab form={form} set={set}/>}
        {tab === "promos"     && <PromosTab form={form} set={set}/>}
        {tab === "printing"   && <PrintingTab form={form} setField={setField}/>}
        {tab === "multistore" && <MultiStoreTab form={form} set={set}/>}
        {tab === "movements"  && <MovementsTab editing={editing}/>}
        {tab === "history"    && <HistoryTab editing={editing}/>}
        {tab === "notes"      && <NotesTab form={form} setField={setField}/>}
      </div>
    </div>
  );
}

// =================================================================
// SEED — turn an existing product into a full editor form, or
// produce sensible defaults for a new line.
// =================================================================
function sleSeedForm(p) {
  if (!p) {
    return {
      // Identity
      name: "", fullName: "", sku: "",
      strength: "", pack: "",
      // Classification
      dept: "", cat: "", sub: "", manufacturer: "",
      schedule: "—", stockGroups: [], locations: [],
      // Stock rules
      cartonSize: 1, minOrdCartons: 1, minStock: 0, maxStock: 0,
      // Flags
      active: true, autoOrder: true, orderOnlyBelowMin: false,
      ethical: false, discountable: true, authRequired: false,
      bulkFood: false, custDisplay: true, inRobot: false, online: false,
      controlled: false, coldChain: false, ndss: false, ageVerify: false, counsel: false,
      // Pricing
      costEx: "", supplierEx: "", avgCost: "", prevCost: "",
      sellEx: "", rrp: "",
      taxRate: 0.10, gstFlag: "Y - Taxable",
      pricingPolicy: "Standard", roundingPolicy: "Rounding None",
      expectedDiscount: 0,
      // Lists
      suppliers: [],
      barcodes: [],
      clubs: [],
      promos: [],
      // Multi-store
      storeStock: OD.STORES.reduce((a, s) => ({...a, [s.id]: { onHand:0, min:0, max:0, location:"", active:true }}), {}),
      // Printing
      labelTemplate: "shelf-50x30",
      printPrice: true, printBarcode: true, printStrength: true,
      // Notes
      internalNote: "", customerNote: "", clinicalNote: "",
    };
  }
  // From a real product (synthetic but plausible PDEs / barcodes)
  const seed = (p.id || "").split("").reduce((a, c) => a + c.charCodeAt(0), 0);
  const taxRate = p.taxRate || 0;
  const supplierEx = +(p.cost * 1.08).toFixed(2);
  return {
    name: p.name,
    fullName: `${p.name} ${p.strength !== "—" ? p.strength : ""} ${p.pack}`.trim(),
    sku: p.sku,
    strength: p.strength === "—" ? "" : p.strength,
    pack: p.pack,
    dept: p.dept, cat: p.cat, sub: p.sub,
    manufacturer: ["GSK","Pfizer","Sanofi","Bayer","AstraZeneca","Mylan","Sandoz","Apotex"][seed % 8],
    schedule: p.schedule,
    stockGroups: p.controlled ? ["S8 register"] : p.pbs ? ["PBS"] : [],
    locations: p.controlled ? ["S8 Safe"] : ["Main shelf"],
    cartonSize: [1,1,6,12][seed % 4],
    minOrdCartons: 1,
    minStock: 0, maxStock: 0,
    active: true, autoOrder: true, orderOnlyBelowMin: false,
    ethical: false, discountable: !p.pbs, authRequired: !!p.controlled || !!p.ageVerify,
    bulkFood: false, custDisplay: true, inRobot: false, online: !p.controlled,
    controlled: !!p.controlled, coldChain: !!p.coldChain, ndss: !!p.ndss,
    ageVerify: !!p.ageVerify, counsel: !!p.controlled,
    costEx: p.cost.toFixed(2),
    supplierEx: supplierEx.toFixed(2),
    avgCost: p.cost.toFixed(2),
    prevCost: (p.cost * 0.96).toFixed(2),
    sellEx: p.price.toFixed(2),
    rrp: (p.price * 1.05).toFixed(2),
    taxRate,
    gstFlag: taxRate > 0 ? "Y - Taxable" : "N - Free to Customers",
    pricingPolicy: p.pbs ? "PBS" : "Standard",
    roundingPolicy: "Rounding None",
    expectedDiscount: 0,
    suppliers: sleSeedSuppliers(p, seed),
    barcodes: [{ code: p.sku, default: true, type: "EAN-13" }],
    clubs: p.pbs ? [{ name: "Concession", ratio: "1.0", fixed: "" }] : [],
    promos: [],
    storeStock: OD.STORES.reduce((a, s) => {
      const st = OD.STOCK[s.id]?.[p.id];
      return { ...a, [s.id]: {
        onHand: st?.onHand || 0,
        min: st?.min || 0,
        max: st?.max || 0,
        location: st?.location || "",
        active: !!st,
      }};
    }, {}),
    labelTemplate: "shelf-50x30",
    printPrice: true, printBarcode: true, printStrength: p.strength !== "—",
    internalNote: "", customerNote: "", clinicalNote: "",
  };
}
function sleSeedSuppliers(p, seed) {
  const sups = OD.SUPPLIERS.slice(0, 4);
  return sups.map((s, i) => ({
    pde: (1000000 + (seed * 31 + i * 117) % 9000000).toString(),
    supplierId: s.id,
    description: p.name.toUpperCase().slice(0, 32),
    moq: i === 0 ? "" : "1",
    cart: i === 0 ? "" : "1",
    ws1: (p.cost * (0.95 + i * 0.05)).toFixed(2),
    default: i === Math.min(1, sups.length - 1),
  }));
}

// =================================================================
// DETAILS TAB — identity, classification, stock rules, flags
// =================================================================
function DetailsTab({ form, set, setField }) {
  return (
    <div className="sle-grid">
      <div className="sle-col">
        {/* Basic details */}
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Basic details</div>
          </header>
          <div className="sle-form-grid">
            <Field label="Stock name" required full>
              <input className="input" value={form.name} onChange={e => setField("name", e.target.value)} placeholder="e.g. Panadol Liquid Caps 16s"/>
            </Field>
            <Field label="Full stock name" hint="As printed on labels / receipts" full>
              <input className="input" value={form.fullName} onChange={e => setField("fullName", e.target.value)} placeholder="Long form including strength + pack"/>
            </Field>
            <Field label="Strength">
              <input className="input" value={form.strength} onChange={e => setField("strength", e.target.value)} placeholder="500mg"/>
            </Field>
            <Field label="Pack size">
              <input className="input" value={form.pack} onChange={e => setField("pack", e.target.value)} placeholder="16 capsules"/>
            </Field>
            <Field label="SKU / GTIN" required>
              <input className="input tabular" value={form.sku} onChange={e => setField("sku", e.target.value)} placeholder="13-digit barcode"/>
            </Field>
            <Field label="Schedule">
              <select className="input select" value={form.schedule} onChange={e => setField("schedule", e.target.value)}>
                {["—","S2","S3","S4","S8"].map(s => <option key={s}>{s}</option>)}
              </select>
            </Field>
            <Field label="Manufacturer" full>
              <input className="input" value={form.manufacturer} onChange={e => setField("manufacturer", e.target.value)} placeholder="e.g. GSK"/>
            </Field>
          </div>
        </section>

        {/* Classification */}
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Classification</div>
            <div className="sle-card-sub">Where this line sits in the merchandising hierarchy</div>
          </header>
          <div className="sle-form-grid">
            <Field label="Department" required>
              <select className="input select" value={form.dept}
                onChange={e => set({ dept: e.target.value, cat: "", sub: "" })}>
                <option value="">Select…</option>
                {OD.CATEGORIES.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </select>
            </Field>
            <Field label="Category">
              <select className="input select" value={form.cat} disabled={!form.dept}
                onChange={e => set({ cat: e.target.value, sub: "" })}>
                <option value="">{form.dept ? "Select…" : "Pick department first"}</option>
                {form.dept && OD.DEPT_BY_ID[form.dept].cats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="Subcategory" required>
              <select className="input select" value={form.sub} disabled={!form.cat}
                onChange={e => setField("sub", e.target.value)}>
                <option value="">{form.cat ? "Select…" : "Pick category first"}</option>
                {form.cat && OD.CAT_BY_ID[form.cat].subs.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </Field>
            <Field label="Stock groups" hint="Comma-separated tags · used for bulk pricing & reports" full>
              <input className="input" value={form.stockGroups.join(", ")} onChange={e => setField("stockGroups", e.target.value.split(",").map(x => x.trim()).filter(Boolean))} placeholder="e.g. PBS, Webster eligible"/>
            </Field>
            <Field label="Storage locations" hint="Where physical stock lives in-store" full>
              <input className="input" value={form.locations.join(", ")} onChange={e => setField("locations", e.target.value.split(",").map(x => x.trim()).filter(Boolean))} placeholder="e.g. Main shelf, S8 Safe"/>
            </Field>
          </div>
          {form.dept && form.cat && form.sub && (
            <div className="sle-crumb">
              {OD.DEPT_BY_ID[form.dept]?.name} <span>›</span> {OD.CAT_BY_ID[form.cat]?.name} <span>›</span> {OD.SUB_BY_ID[form.sub]?.name}
            </div>
          )}
        </section>

        {/* Stock rules */}
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Stock rules</div>
            <div className="sle-card-sub">Group defaults · override per store in the Multi-store tab</div>
          </header>
          <div className="sle-form-grid">
            <Field label="Carton size (units)">
              <input className="input tabular" type="number" min="1" value={form.cartonSize} onChange={e => setField("cartonSize", parseInt(e.target.value)||1)}/>
            </Field>
            <Field label="Min order qty (cartons)">
              <input className="input tabular" type="number" min="0" value={form.minOrdCartons} onChange={e => setField("minOrdCartons", parseInt(e.target.value)||0)}/>
            </Field>
            <Field label="Min stock level (units)">
              <input className="input tabular" type="number" min="0" value={form.minStock} onChange={e => setField("minStock", parseInt(e.target.value)||0)}/>
            </Field>
            <Field label="Max stock level (units)">
              <input className="input tabular" type="number" min="0" value={form.maxStock} onChange={e => setField("maxStock", parseInt(e.target.value)||0)}/>
            </Field>
            <div className="sle-derived" style={{gridColumn:'span 2'}}>
              <span>1 carton</span><span>=</span><strong>{form.cartonSize || 1} unit{form.cartonSize !== 1 ? "s" : ""}</strong>
              <span style={{marginLeft:20}}>Min order</span><span>=</span><strong>{(form.minOrdCartons||0) * (form.cartonSize||1)} units</strong>
            </div>
          </div>
        </section>
      </div>

      <div className="sle-col">
        {/* Behaviour toggles */}
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Behaviour</div>
            <div className="sle-card-sub">How this line behaves in POS, ordering, and online</div>
          </header>
          <div className="sle-toggles">
            <Toggle k="active"            label="Stock line active"        hint="Available for sale" form={form} setField={setField}/>
            <Toggle k="autoOrder"         label="Auto orders"               hint="Include in scheduled reorder runs" form={form} setField={setField}/>
            <Toggle k="orderOnlyBelowMin" label="Order only if SOH < Min"   hint="Skip in PO unless stock is below minimum" form={form} setField={setField}/>
            <Toggle k="ethical"           label="Ethical line"              hint="Hide cost from sale screen" form={form} setField={setField}/>
            <Toggle k="discountable"      label="Discountable"              hint="Allows POS discount on this line" form={form} setField={setField}/>
            <Toggle k="authRequired"      label="Auth. required to sell"    hint="Pharmacist must authorise at register" form={form} setField={setField}/>
            <Toggle k="bulkFood"          label="Bulk food pricing"         hint="Charge by weight at counter" form={form} setField={setField}/>
            <Toggle k="custDisplay"       label="Show on customer display"  hint="Description visible on PFD" form={form} setField={setField}/>
            <Toggle k="inRobot"           label="Stored in robot"           hint="Picked from dispensing robot" form={form} setField={setField}/>
            <Toggle k="online"            label="Marked for online"         hint="Listed on web store" form={form} setField={setField}/>
          </div>
        </section>

        {/* Clinical flags */}
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Clinical & compliance</div>
            <div className="sle-card-sub">Workflow prompts shown to staff</div>
          </header>
          <div className="sle-toggles">
            <Toggle k="controlled"  label="S8 controlled drug"  hint="DD register entry on every dispense" tone="void"  form={form} setField={setField}/>
            <Toggle k="coldChain"   label="Cold chain · 2–8°C"  hint="Verify fridge log; cold-chain bag" tone="brand" form={form} setField={setField}/>
            <Toggle k="counsel"     label="Counsel required"    hint="Force pharmacist counsel" form={form} setField={setField}/>
            <Toggle k="ageVerify"   label="Age verification"    hint="Photo ID, Project STOP if pseudo" tone="hold"  form={form} setField={setField}/>
            <Toggle k="ndss"        label="NDSS subsidised"     hint="Diabetes services scheme item" form={form} setField={setField}/>
          </div>
        </section>
      </div>
    </div>
  );
}

// =================================================================
// PRICING TAB — full cost ladder + sell prices + GST + policies
// =================================================================
function PricingTab({ form, set, setField, costEx, costInc, sellEx, sellInc, gstAmount, markup, gp, supplierEx }) {
  return (
    <div className="sle-grid">
      <div className="sle-col">
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Cost ladder</div>
            <div className="sle-card-sub">Tracked from supplier invoices · drives margin reporting</div>
          </header>
          <div className="sle-form-grid">
            <Field label="Previous Cost ex GST" hint="Cost on the prior invoice">
              <input className="input tabular" value={form.prevCost} onChange={e => setField("prevCost", e.target.value)}/>
            </Field>
            <Field label="Supplier list price" hint="Catalogue / contract price">
              <input className="input tabular" value={form.supplierEx} onChange={e => setField("supplierEx", e.target.value)}/>
            </Field>
            <Field label="Average cost ex GST" hint="Weighted moving average">
              <input className="input tabular" value={form.avgCost} onChange={e => setField("avgCost", e.target.value)}/>
            </Field>
            <Field label="Last invoice ex (carton)" hint="Auto-filled from receipts">
              <input className="input tabular" value={form.avgCost} disabled/>
            </Field>
            <Field label="Last invoice ex (unit)">
              <input className="input tabular" value={form.avgCost} disabled/>
            </Field>
            <Field label="Last invoice inc (unit)">
              <input className="input tabular" value={(parseFloat(form.avgCost||0) * (1 + form.taxRate)).toFixed(2)} disabled/>
            </Field>
            <Field label="Cost ex GST" required>
              <input className="input tabular sle-emph" value={form.costEx} onChange={e => setField("costEx", e.target.value)} placeholder="0.00"/>
            </Field>
            <Field label="Cost inc GST">
              <input className="input tabular sle-emph" value={costInc.toFixed(2)} disabled/>
            </Field>
            <Field label="Expected discount %" hint="Off supplier list">
              <input className="input tabular" type="number" min="0" max="100" step="0.01" value={form.expectedDiscount} onChange={e => setField("expectedDiscount", parseFloat(e.target.value)||0)}/>
            </Field>
            <Field label="Expected cost ex">
              <input className="input tabular" value={(supplierEx * (1 - (form.expectedDiscount||0)/100)).toFixed(2)} disabled/>
            </Field>
          </div>
        </section>

        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Sell prices</div>
          </header>
          <div className="sle-form-grid">
            <Field label="GST flag">
              <select className="input select" value={form.gstFlag} onChange={e => {
                const v = e.target.value;
                set({ gstFlag: v, taxRate: v.startsWith("Y") ? 0.10 : 0 });
              }}>
                <option>Y - Taxable</option>
                <option>N - Free to Customers</option>
                <option>X - GST Exempt</option>
              </select>
            </Field>
            <Field label="Tax rate">
              <input className="input tabular" value={(form.taxRate * 100).toFixed(0) + "%"} disabled/>
            </Field>
            <Field label="Sell ex GST" required>
              <input className="input tabular sle-emph" value={form.sellEx} onChange={e => setField("sellEx", e.target.value)} placeholder="0.00"/>
            </Field>
            <Field label="GST amount">
              <input className="input tabular" value={gstAmount.toFixed(2)} disabled/>
            </Field>
            <Field label="Retail sell price (inc)">
              <input className="input tabular sle-emph" value={sellInc.toFixed(2)} disabled/>
            </Field>
            <Field label="RRP">
              <input className="input tabular" value={form.rrp} onChange={e => setField("rrp", e.target.value)}/>
            </Field>
            <Field label="Pricing policy">
              <select className="input select" value={form.pricingPolicy} onChange={e => setField("pricingPolicy", e.target.value)}>
                <option>Standard</option>
                <option>PBS</option>
                <option>NDSS</option>
                <option>Cost-plus (locked)</option>
                <option>Match supplier RRP</option>
              </select>
            </Field>
            <Field label="Rounding policy">
              <select className="input select" value={form.roundingPolicy} onChange={e => setField("roundingPolicy", e.target.value)}>
                <option>Rounding None</option>
                <option>Round to nearest $0.05</option>
                <option>Round to nearest $0.10</option>
                <option>Always round up</option>
                <option>Charm pricing (.95 / .99)</option>
              </select>
            </Field>
          </div>
        </section>
      </div>

      <div className="sle-col">
        <section className="off-card sle-card">
          <div className="off-card-title">Margin summary</div>
          <div className="sle-margin-summary">
            <SleStat label="Markup"        value={markup.toFixed(2) + "%"} tone={markup < 20 ? "warn" : markup > 60 ? "good" : null}/>
            <SleStat label="Gross profit"  value={gp.toFixed(2) + "%"} tone={gp < 15 ? "warn" : gp > 40 ? "good" : null}/>
            <SleStat label="Margin $"      value={oMoney(sellEx - costEx)}/>
            <SleStat label="Sell vs RRP"   value={form.rrp ? Math.round((sellInc / (parseFloat(form.rrp)||sellInc)) * 100) + "%" : "—"}/>
          </div>
          <div className="sle-ladder">
            <SleLadderRow label="Supplier list ex" value={supplierEx}/>
            <SleLadderRow label="Cost ex GST"      value={costEx}    emph/>
            <SleLadderRow label="Cost inc GST"     value={costInc}/>
            <SleLadderRow label="Sell ex GST"      value={sellEx}    emph/>
            <SleLadderRow label="GST"              value={gstAmount} muted/>
            <SleLadderRow label="Sell inc GST"     value={sellInc}   emph/>
          </div>
        </section>

        <section className="off-card sle-card">
          <div className="off-card-title">PBS / claim</div>
          <div className="sle-form-grid">
            <Field label="On PBS" full>
              <label className="checkbox" style={{padding:'2px 0'}}>
                <input type="checkbox" checked={form.pricingPolicy === "PBS"} onChange={e => setField("pricingPolicy", e.target.checked ? "PBS" : "Standard")}/>
                <span className="checkbox-box"><OIcon name="check" width={14} height={14}/></span>
                <span>PBS-listed item</span>
              </label>
            </Field>
            {form.pricingPolicy === "PBS" && (
              <>
                <Field label="General co-pay">
                  <input className="input tabular" defaultValue="31.60"/>
                </Field>
                <Field label="Concession co-pay">
                  <input className="input tabular" defaultValue="7.70"/>
                </Field>
              </>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}

// =================================================================
// SUPPLIERS / PDEs TAB
// Pharmacy Data Exchange codes — multiple per stock line
// =================================================================
function SuppliersTab({ form, set }) {
  function update(i, patch) {
    const next = form.suppliers.map((s, j) => j === i ? { ...s, ...patch } : (patch.default ? { ...s, default: false } : s));
    set({ suppliers: next });
  }
  function add() {
    set({ suppliers: [...form.suppliers, { pde: "", supplierId: OD.SUPPLIERS[0]?.id, description: form.name, moq: "", cart: "", ws1: "", default: form.suppliers.length === 0 }] });
  }
  function remove(i) {
    set({ suppliers: form.suppliers.filter((_, j) => j !== i) });
  }
  return (
    <div className="sle-grid sle-grid--single">
      <section className="off-card sle-card">
        <header className="sle-card-head">
          <div>
            <div className="off-card-title">Supplier codes (PDEs)</div>
            <div className="sle-card-sub">{form.suppliers.length} supplier{form.suppliers.length === 1 ? "" : "s"} · the default is used for auto-orders</div>
          </div>
          <button className="btn btn--ghost btn--sm" onClick={add}><OIcon name="plus"/> Add supplier</button>
        </header>
        <div className="off-grid" style={{gridTemplateColumns:'130px 1.4fr 1.6fr 80px 80px 110px 90px 40px'}}>
          <div className="off-grid-headcell">PDE #</div>
          <div className="off-grid-headcell">Supplier</div>
          <div className="off-grid-headcell">Description</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>MOQ</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Cart</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>WS1 ($)</div>
          <div className="off-grid-headcell">Default</div>
          <div className="off-grid-headcell"></div>
          {form.suppliers.map((s, i) => (
            <div key={i} className="off-grid-row">
              <div className="off-grid-cell off-cell-edit off-cell-mono"><input value={s.pde} onChange={e => update(i, { pde: e.target.value })}/></div>
              <div className="off-grid-cell off-cell-edit">
                <select value={s.supplierId} onChange={e => update(i, { supplierId: e.target.value })}>
                  {OD.SUPPLIERS.map(sup => <option key={sup.id} value={sup.id}>{sup.name}</option>)}
                </select>
              </div>
              <div className="off-grid-cell off-cell-edit"><input value={s.description} onChange={e => update(i, { description: e.target.value })}/></div>
              <div className="off-grid-cell off-cell-edit off-cell-num"><input value={s.moq} onChange={e => update(i, { moq: e.target.value })}/></div>
              <div className="off-grid-cell off-cell-edit off-cell-num"><input value={s.cart} onChange={e => update(i, { cart: e.target.value })}/></div>
              <div className="off-grid-cell off-cell-edit off-cell-num"><input value={s.ws1} onChange={e => update(i, { ws1: e.target.value })}/></div>
              <div className="off-grid-cell">
                <label className="sle-default-radio">
                  <input type="radio" name="default-pde" checked={!!s.default} onChange={() => update(i, { default: true })}/>
                  <span>{s.default ? "Default" : "Set"}</span>
                </label>
              </div>
              <div className="off-grid-cell">
                <button className="off-topbar-btn" onClick={() => remove(i)} aria-label="Remove"><OIcon name="trash"/></button>
              </div>
            </div>
          ))}
          {form.suppliers.length === 0 && (
            <div className="sle-empty-row">No supplier codes yet. Add one to enable ordering.</div>
          )}
        </div>
      </section>
    </div>
  );
}

// =================================================================
// BARCODES TAB
// =================================================================
function BarcodesTab({ form, set }) {
  function update(i, patch) {
    const next = form.barcodes.map((b, j) => j === i ? { ...b, ...patch } : (patch.default ? { ...b, default: false } : b));
    set({ barcodes: next });
  }
  function add() {
    set({ barcodes: [...form.barcodes, { code: "", default: form.barcodes.length === 0, type: "EAN-13" }] });
  }
  function remove(i) {
    set({ barcodes: form.barcodes.filter((_, j) => j !== i) });
  }
  return (
    <div className="sle-grid sle-grid--single">
      <section className="off-card sle-card">
        <header className="sle-card-head">
          <div>
            <div className="off-card-title">Barcodes</div>
            <div className="sle-card-sub">A line can have multiple scannable codes · the default prints on labels</div>
          </div>
          <button className="btn btn--ghost btn--sm" onClick={add}><OIcon name="plus"/> Add barcode</button>
        </header>
        <div className="off-grid" style={{gridTemplateColumns:'1.8fr 140px 110px 50px'}}>
          <div className="off-grid-headcell">Barcode</div>
          <div className="off-grid-headcell">Type</div>
          <div className="off-grid-headcell">Default</div>
          <div className="off-grid-headcell"></div>
          {form.barcodes.map((b, i) => (
            <div key={i} className="off-grid-row">
              <div className="off-grid-cell off-cell-edit off-cell-mono"><input value={b.code} onChange={e => update(i, { code: e.target.value })} placeholder="Scan or type…"/></div>
              <div className="off-grid-cell off-cell-edit">
                <select value={b.type} onChange={e => update(i, { type: e.target.value })}>
                  <option>EAN-13</option><option>EAN-8</option>
                  <option>UPC-A</option><option>Code 128</option>
                  <option>QR</option><option>Internal</option>
                </select>
              </div>
              <div className="off-grid-cell">
                <label className="sle-default-radio">
                  <input type="radio" name="default-bc" checked={!!b.default} onChange={() => update(i, { default: true })}/>
                  <span>{b.default ? "Default" : "Set"}</span>
                </label>
              </div>
              <div className="off-grid-cell">
                <button className="off-topbar-btn" onClick={() => remove(i)} aria-label="Remove"><OIcon name="trash"/></button>
              </div>
            </div>
          ))}
          {form.barcodes.length === 0 && <div className="sle-empty-row">No barcodes registered.</div>}
        </div>
      </section>
    </div>
  );
}

// =================================================================
// PROMOTIONS & CLUBS TAB
// =================================================================
function PromosTab({ form, set }) {
  function addClub() { set({ clubs: [...form.clubs, { name: "", ratio: "1.0", fixed: "" }] }); }
  function updateClub(i, patch) { set({ clubs: form.clubs.map((c, j) => j === i ? { ...c, ...patch } : c) }); }
  function removeClub(i) { set({ clubs: form.clubs.filter((_, j) => j !== i) }); }

  function addPromo() {
    const today = "28/05/2026";
    set({ promos: [...form.promos, { description: "", type: "% off", start: today, end: "" }] });
  }
  function updatePromo(i, patch) { set({ promos: form.promos.map((p, j) => j === i ? { ...p, ...patch } : p) }); }
  function removePromo(i) { set({ promos: form.promos.filter((_, j) => j !== i) }); }

  return (
    <div className="sle-grid">
      <div className="sle-col">
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div>
              <div className="off-card-title">Loyalty clubs</div>
              <div className="sle-card-sub">Override pricing for club / concession members</div>
            </div>
            <button className="btn btn--ghost btn--sm" onClick={addClub}><OIcon name="plus"/> Add club</button>
          </header>
          <div className="off-grid" style={{gridTemplateColumns:'1fr 100px 100px 50px'}}>
            <div className="off-grid-headcell">Club name</div>
            <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Ratio</div>
            <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Fixed $</div>
            <div className="off-grid-headcell"></div>
            {form.clubs.map((c, i) => (
              <div key={i} className="off-grid-row">
                <div className="off-grid-cell off-cell-edit"><input value={c.name} onChange={e => updateClub(i, { name: e.target.value })} placeholder="e.g. Seniors"/></div>
                <div className="off-grid-cell off-cell-edit off-cell-num"><input value={c.ratio} onChange={e => updateClub(i, { ratio: e.target.value })}/></div>
                <div className="off-grid-cell off-cell-edit off-cell-num"><input value={c.fixed} onChange={e => updateClub(i, { fixed: e.target.value })} placeholder="—"/></div>
                <div className="off-grid-cell"><button className="off-topbar-btn" onClick={() => removeClub(i)}><OIcon name="trash"/></button></div>
              </div>
            ))}
            {form.clubs.length === 0 && <div className="sle-empty-row">No club pricing rules.</div>}
          </div>
        </section>
      </div>

      <div className="sle-col">
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div>
              <div className="off-card-title">Active promotions</div>
              <div className="sle-card-sub">Scheduled discounts & deal mechanics</div>
            </div>
            <button className="btn btn--ghost btn--sm" onClick={addPromo}><OIcon name="plus"/> Add promo</button>
          </header>
          <div className="off-grid" style={{gridTemplateColumns:'1.6fr 100px 100px 100px 50px'}}>
            <div className="off-grid-headcell">Description</div>
            <div className="off-grid-headcell">Type</div>
            <div className="off-grid-headcell">Start</div>
            <div className="off-grid-headcell">End</div>
            <div className="off-grid-headcell"></div>
            {form.promos.map((p, i) => (
              <div key={i} className="off-grid-row">
                <div className="off-grid-cell off-cell-edit"><input value={p.description} onChange={e => updatePromo(i, { description: e.target.value })} placeholder="e.g. 2 for $20"/></div>
                <div className="off-grid-cell off-cell-edit">
                  <select value={p.type} onChange={e => updatePromo(i, { type: e.target.value })}>
                    <option>% off</option><option>$ off</option>
                    <option>Multi-buy</option><option>Set price</option><option>Loyalty mult.</option>
                  </select>
                </div>
                <div className="off-grid-cell off-cell-edit off-cell-mono"><input value={p.start} onChange={e => updatePromo(i, { start: e.target.value })} placeholder="dd/mm/yyyy"/></div>
                <div className="off-grid-cell off-cell-edit off-cell-mono"><input value={p.end} onChange={e => updatePromo(i, { end: e.target.value })} placeholder="dd/mm/yyyy"/></div>
                <div className="off-grid-cell"><button className="off-topbar-btn" onClick={() => removePromo(i)}><OIcon name="trash"/></button></div>
              </div>
            ))}
            {form.promos.length === 0 && <div className="sle-empty-row">No active promotions.</div>}
          </div>
        </section>
      </div>
    </div>
  );
}

// =================================================================
// PRINTING TAB
// =================================================================
function PrintingTab({ form, setField }) {
  return (
    <div className="sle-grid">
      <div className="sle-col">
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div className="off-card-title">Label template</div>
            <div className="sle-card-sub">Default used when printing from POS or PDE scan</div>
          </header>
          <div className="sle-form-grid">
            <Field label="Template" full>
              <select className="input select" value={form.labelTemplate} onChange={e => setField("labelTemplate", e.target.value)}>
                <option value="shelf-50x30">Shelf · 50×30mm</option>
                <option value="shelf-60x40">Shelf · 60×40mm</option>
                <option value="dispense-S2">Dispense label · S2/S3</option>
                <option value="dispense-S8">Dispense label · S8</option>
                <option value="webster">Webster pack</option>
              </select>
            </Field>
          </div>
          <div className="sle-toggles">
            <Toggle k="printPrice"    label="Print price"     hint="Show retail $ on label" form={form} setField={setField}/>
            <Toggle k="printBarcode"  label="Print barcode"   hint="Print default barcode" form={form} setField={setField}/>
            <Toggle k="printStrength" label="Print strength"  hint="Include strength under name" form={form} setField={setField}/>
          </div>
        </section>
      </div>

      <div className="sle-col">
        <section className="off-card sle-card">
          <div className="off-card-title">Label preview</div>
          <div className="sle-label-preview">
            <div className="sle-label-name">{form.name || "Product name"}</div>
            {form.printStrength && form.strength && <div className="sle-label-sub">{form.strength} · {form.pack}</div>}
            {!form.printStrength && form.pack && <div className="sle-label-sub">{form.pack}</div>}
            <div className="sle-label-foot">
              {form.printBarcode && <div className="sle-label-barcode" aria-hidden></div>}
              {form.printPrice && <div className="sle-label-price">${(parseFloat(form.sellEx) * (1 + form.taxRate) || 0).toFixed(2)}</div>}
            </div>
            {form.printBarcode && form.sku && <div className="sle-label-sku">{form.sku}</div>}
          </div>
        </section>
      </div>
    </div>
  );
}

// =================================================================
// MULTI-STORE TAB
// =================================================================
function MultiStoreTab({ form, set }) {
  function updateStore(id, patch) {
    set({ storeStock: { ...form.storeStock, [id]: { ...form.storeStock[id], ...patch } } });
  }
  return (
    <div className="sle-grid sle-grid--single">
      <section className="off-card sle-card">
        <header className="sle-card-head">
          <div>
            <div className="off-card-title">Multi-store stock & overrides</div>
            <div className="sle-card-sub">Override the group defaults · uncheck Active to hide from a store</div>
          </div>
        </header>
        <div className="off-grid" style={{gridTemplateColumns:'1.4fr 80px 90px 90px 90px 1fr'}}>
          <div className="off-grid-headcell">Store</div>
          <div className="off-grid-headcell">Active</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>On hand</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Min</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Max</div>
          <div className="off-grid-headcell">Location</div>
          {OD.STORES.map(s => {
            const v = form.storeStock[s.id];
            return (
              <div key={s.id} className="off-grid-row">
                <div className="off-grid-cell">
                  <div className="off-cell-strong">{s.name}</div>
                  <div className="off-cell-mono" style={{color:'var(--text-subtle)', marginTop:2}}>{s.code}</div>
                </div>
                <div className="off-grid-cell">
                  <label className="checkbox" style={{padding:0}}>
                    <input type="checkbox" checked={v.active} onChange={e => updateStore(s.id, { active: e.target.checked })}/>
                    <span className="checkbox-box" style={{width:18, height:18}}><OIcon name="check" width={12} height={12}/></span>
                  </label>
                </div>
                <div className="off-grid-cell off-cell-edit off-cell-num"><input type="number" value={v.onHand} disabled={!v.active} onChange={e => updateStore(s.id, { onHand: parseInt(e.target.value)||0 })}/></div>
                <div className="off-grid-cell off-cell-edit off-cell-num"><input type="number" value={v.min} disabled={!v.active} onChange={e => updateStore(s.id, { min: parseInt(e.target.value)||0 })}/></div>
                <div className="off-grid-cell off-cell-edit off-cell-num"><input type="number" value={v.max} disabled={!v.active} onChange={e => updateStore(s.id, { max: parseInt(e.target.value)||0 })}/></div>
                <div className="off-grid-cell off-cell-edit"><input value={v.location} disabled={!v.active} onChange={e => updateStore(s.id, { location: e.target.value })} placeholder="Shelf code"/></div>
              </div>
            );
          })}
        </div>
      </section>
    </div>
  );
}

// =================================================================
// MOVEMENTS TAB — read-only ledger
// =================================================================
function MovementsTab({ editing }) {
  const items = [
    { date: "28/05/2026 14:32", kind: "Sale",       qty: -1,  bal: 8,  ref: "Sale 1042831", user: "Sarah K." },
    { date: "28/05/2026 09:01", kind: "Receipt",    qty: +30, bal: 9,  ref: "PO 4421",      user: "Auto" },
    { date: "27/05/2026 17:48", kind: "Sale",       qty: -2,  bal: -21, ref: "Rx 80442",     user: "Mark T." },
    { date: "26/05/2026 11:15", kind: "Transfer",   qty: -6,  bal: -19, ref: "TX-2026-088",  user: "Alex J." },
    { date: "24/05/2026 16:30", kind: "Adjustment", qty: -1,  bal: -13, ref: "Damaged · disposed", user: "Sarah K." },
    { date: "20/05/2026 10:05", kind: "Stocktake",  qty: 0,   bal: -12, ref: "Cycle count",   user: "Alex J." },
  ];
  return (
    <div className="sle-grid sle-grid--single">
      <section className="off-card sle-card">
        <header className="sle-card-head">
          <div>
            <div className="off-card-title">Stock movements</div>
            <div className="sle-card-sub">All inventory changes for {editing?.name || "this line"}</div>
          </div>
          <button className="btn btn--ghost btn--sm"><OIcon name="printer"/> Export ledger</button>
        </header>
        <div className="off-grid" style={{gridTemplateColumns:'150px 120px 80px 80px 1fr 110px'}}>
          <div className="off-grid-headcell">Date / time</div>
          <div className="off-grid-headcell">Kind</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Qty</div>
          <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Balance</div>
          <div className="off-grid-headcell">Reference</div>
          <div className="off-grid-headcell">User</div>
          {items.map((m, i) => (
            <div key={i} className="off-grid-row">
              <div className="off-grid-cell off-cell-mono">{m.date}</div>
              <div className="off-grid-cell">
                <span className={"sle-mv-pill sle-mv-pill--" + m.kind.toLowerCase()}>{m.kind}</span>
              </div>
              <div className="off-grid-cell off-cell-num off-cell-strong" style={{color: m.qty < 0 ? 'var(--void)' : m.qty > 0 ? 'var(--paid-text)' : 'var(--text-subtle)'}}>
                {m.qty > 0 ? "+" : ""}{m.qty}
              </div>
              <div className="off-grid-cell off-cell-num">{m.bal}</div>
              <div className="off-grid-cell">{m.ref}</div>
              <div className="off-grid-cell off-muted">{m.user}</div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

// =================================================================
// HISTORY TAB — audit log
// =================================================================
function HistoryTab({ editing }) {
  const items = [
    { date: "28/05/2026 09:00", user: "Auto", action: "Cost price updated",    detail: "$4.20 → $4.42 (from PO 4421)" },
    { date: "21/05/2026 14:21", user: "Sarah K.", action: "Retail price changed", detail: "$4.65 → $4.99" },
    { date: "18/05/2026 11:10", user: "Mark T.",  action: "Min stock raised",     detail: "0 → 5 (Boronia store)" },
    { date: "10/05/2026 08:42", user: "Alex J.",  action: "Barcode added",        detail: "9300673893680" },
    { date: "02/05/2026 16:30", user: "Sarah K.", action: "Stock line created",   detail: editing?.name || "" },
  ];
  return (
    <div className="sle-grid sle-grid--single">
      <section className="off-card sle-card">
        <header className="sle-card-head">
          <div>
            <div className="off-card-title">Edit history</div>
            <div className="sle-card-sub">Every change to this stock line, with the user who made it</div>
          </div>
        </header>
        <div className="sle-history">
          {items.map((h, i) => (
            <div key={i} className="sle-history-row">
              <div className="sle-history-when">{h.date}</div>
              <div className="sle-history-body">
                <div className="sle-history-action">{h.action}</div>
                <div className="sle-history-detail">{h.detail}</div>
              </div>
              <div className="sle-history-user">{h.user}</div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

// =================================================================
// NOTES TAB
// =================================================================
function NotesTab({ form, setField }) {
  return (
    <div className="sle-grid">
      <div className="sle-col">
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div>
              <div className="off-card-title">Internal note</div>
              <div className="sle-card-sub">Staff-only · shown in dispense queue and on POS</div>
            </div>
          </header>
          <textarea className="input sle-textarea" rows={5} value={form.internalNote} onChange={e => setField("internalNote", e.target.value)} placeholder="e.g. Reorder from API only — pricing locked under HB contract."/>
        </section>
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div>
              <div className="off-card-title">Clinical note</div>
              <div className="sle-card-sub">Prompts the pharmacist on dispense</div>
            </div>
          </header>
          <textarea className="input sle-textarea" rows={5} value={form.clinicalNote} onChange={e => setField("clinicalNote", e.target.value)} placeholder="e.g. Cold chain — confirm fridge log within last 60 minutes."/>
        </section>
      </div>
      <div className="sle-col">
        <section className="off-card sle-card">
          <header className="sle-card-head">
            <div>
              <div className="off-card-title">Customer-facing description</div>
              <div className="sle-card-sub">Shown on PFD, receipts, online store</div>
            </div>
          </header>
          <textarea className="input sle-textarea" rows={12} value={form.customerNote} onChange={e => setField("customerNote", e.target.value)} placeholder="Plain-English product description for customers"/>
        </section>
      </div>
    </div>
  );
}

// =================================================================
// SHARED ATOMS
// =================================================================
function Field({ label, hint, required, full, children }) {
  return (
    <div className={"field sle-field" + (full ? " sle-field--full" : "")}>
      <label className="field-label">
        {label}
        {required && <span className="field-required"> *</span>}
        {hint && <span className="sle-hint">{hint}</span>}
      </label>
      {children}
    </div>
  );
}

function Toggle({ k, label, hint, tone, form, setField }) {
  return (
    <label className={"sle-toggle" + (form[k] ? " is-on" : "") + (tone ? " sle-toggle--" + tone : "")}>
      <input type="checkbox" checked={!!form[k]} onChange={e => setField(k, e.target.checked)}/>
      <div className="sle-toggle-pill"><span/></div>
      <div className="sle-toggle-text">
        <div className="sle-toggle-label">{label}</div>
        <div className="sle-toggle-hint">{hint}</div>
      </div>
    </label>
  );
}

function SleStat({ label, value, tone }) {
  return (
    <div className="sle-stat">
      <div className="sle-stat-label">{label}</div>
      <div className={"sle-stat-value" + (tone === "warn" ? " is-warn" : "") + (tone === "good" ? " is-good" : "")}>{value}</div>
    </div>
  );
}
function SleLadderRow({ label, value, emph, muted }) {
  return (
    <div className={"sle-ladder-row" + (emph ? " is-emph" : "") + (muted ? " is-muted" : "")}>
      <span>{label}</span>
      <span className="sle-ladder-value">{oMoney(value)}</span>
    </div>
  );
}

// =================================================================
// REGISTER
// =================================================================
window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  newStock: StockLineEditor,
  editStock: StockLineEditor,
});
