/* NGIPL PLM: Special price list view (one price list, shared by every customer on it) */
const { useState, useEffect, useMemo, useRef } = React;

function specialPlural(n, one, many) { return n === 1 ? one : many; }
function SpecialView({ nav, toast }) {
  const state = PLM.useStore();
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState("all");
  const [addOpen, setAddOpen] = useState(false);
  const [incOpen, setIncOpen] = useState(false);
  const [printOpen, setPrintOpen] = useState(false);
  const list = PLM.specialList();
  const st = PLM.specialStats();
  const pb = PLM.productsById();
  const grouped = PLM.specialGrouped();
  const q = search.trim().toLowerCase();

  function nameOf(it) {
    const p = it.productId ? pb[it.productId] : null;
    return p ? p.name : (it.customName || "");
  }
  function visible(it) {
    if (q && nameOf(it).toLowerCase().indexOf(q) === -1) return false;
    if (filter === "special") {
      const p = it.productId && pb[it.productId];
      return p ? Math.abs(p.rate - it.rate) > 0.00005 : true;
    }
    if (filter === "review") return PLM.itemStale(it);
    return true;
  }

  function printList() {
    if (list.customers.length === 1) nav.goPrint("special:" + list.customers[0].id);
    else setPrintOpen(true);
  }

  let no = 0;
  let shownCount = 0;
  const rows = grouped.map((band) => {
    const start = no;
    no += band.items.length;
    const items = band.items.filter(visible);
    if (!items.length) return null;
    let seq = start;
    return (
      <React.Fragment key={band.cat.id}>
        <tr className="cat-band"><td colSpan={9}><span className="band-cell"><CatIcon catId={band.cat.id} size={18}></CatIcon><span>{band.cat.name}</span></span></td></tr>
        {band.items.map((it) => {
          seq++;
          if (!visible(it)) return null;
          shownCount++;
          return <SpecialItemRow key={it.id} it={it} no={seq} toast={toast}></SpecialItemRow>;
        })}
      </React.Fragment>
    );
  });

  return (
    <div data-screen-label="Special Price List">
      <div className="toolbar">
        <div className="search-box sp-search-box">
          <ISearch size={15}></ISearch>
          <input className="f-input" placeholder="Search items…" value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        <span className="caption">{shownCount} of {st.items} items · {st.customers} customer{st.customers === 1 ? "" : "s"}</span>
        <div className="spacer"></div>
        <Btn variant="secondary" size="sm" disabled={!st.items} onClick={() => setIncOpen(true)}><IPercent size={13}></IPercent> Increase prices</Btn>
        <Btn variant="secondary" size="sm" disabled={!st.items} onClick={printList}><IPrinter size={13}></IPrinter> Print list</Btn>
        <Btn size="sm" onClick={() => setAddOpen(true)}><IPlus size={13}></IPlus> Add items</Btn>
      </div>

      <div className="parties-grid">
        <div className="sp-main">
          <div className="panel panel--strong sp-stats">
            <div className="stat-strip">
              <div className="stat-cell"><div className="stat-num tnum">{st.items}</div><div className="stat-lbl">Items</div></div>
              <div className="stat-cell"><div className="stat-num tnum">{st.special}</div><div className="stat-lbl">Differ from master</div></div>
              <div className="stat-cell">
                <div className={"stat-num tnum" + (st.stale ? " sp-stat-warn" : "")}>{st.stale}</div>
                <div className="stat-lbl">To review</div>
              </div>
              {st.custom ? <div className="stat-cell"><div className="stat-num tnum">{st.custom}</div><div className="stat-lbl">Custom items</div></div> : null}
            </div>
          </div>

          {st.stale ? (
            <div className="review-banner sp-banner">
              <span className="sp-banner-icon"><IAlert size={15}></IAlert></span>
              <span className="sp-banner-text">The master price has changed on {st.stale} item{st.stale === 1 ? "" : "s"} since the special price was set. Keep the special price or match the master.</span>
              <Btn variant="ghost" size="sm" onClick={() => setFilter("review")}>Show items</Btn>
            </div>
          ) : null}

          <div className="toolbar">
            <div className="filter-chips">
              <button type="button" className={"fchip" + (filter === "all" ? " fchip--on" : "")} onClick={() => setFilter("all")}>All ({st.items})</button>
              <button type="button" className={"fchip" + (filter === "special" ? " fchip--on" : "")} onClick={() => setFilter("special")}>Differ from master ({st.special + st.custom})</button>
              <button type="button" className={"fchip" + (filter === "review" ? " fchip--on" : "")} onClick={() => setFilter("review")}>To review ({st.stale})</button>
            </div>
            {st.missing ? <span className="caption">{st.missing} master {st.missing === 1 ? "item is" : "items are"} not on this list.</span> : null}
          </div>

          {list.items.length ? (
            <div className="panel panel--strong plm-table-wrap sp-rows">
              <table className="plm-table">
                <thead>
                  <tr>
                    <th className="col-no">#</th>
                    <th>Item</th>
                    <th className="num sp-th-rate">Special ₹</th>
                    <th className="num col-master sp-th-master">Master ₹</th>
                    <th className="num sp-th-diff">Diff</th>
                    <th className="num col-gst sp-th-gst">GST</th>
                    <th className="num col-pack sp-th-pack">Pack</th>
                    <th className="num col-outer sp-th-outer">Outer pack</th>
                    <th className="sp-th-act"></th>
                  </tr>
                </thead>
                <tbody>{rows}</tbody>
              </table>
              {shownCount === 0 ? <div className="caption sp-empty">No items in this view.</div> : null}
            </div>
          ) : (
            <div className="panel sp-empty">
              <div className="caption">The special price list is empty. Use Add items to bring items in from the master list, then raise them with Increase prices.</div>
            </div>
          )}
        </div>

        <SpecialCustomers nav={nav} toast={toast}></SpecialCustomers>
      </div>

      {addOpen ? <SpecialAddItemsDialog onClose={() => setAddOpen(false)} toast={toast}></SpecialAddItemsDialog> : null}
      {incOpen ? <SpecialIncreaseDialog onClose={() => setIncOpen(false)} toast={toast}></SpecialIncreaseDialog> : null}
      {printOpen ? <SpecialPrintDialog nav={nav} onClose={() => setPrintOpen(false)}></SpecialPrintDialog> : null}
    </div>
  );
}

/* One heading per route: the route in bold, its places beside it in a lighter line that is cut short
   with an ellipsis if the panel is too narrow (the full text is the tooltip). */
function SpecialRouteHeading({ route, count, className }) {
  const r = PLM.SPECIAL_ROUTES.find((x) => x.id === route);
  const hint = r ? r.hint : "";
  return (
    <div className={"sp-cust-group" + (route ? "" : " sp-cust-group--warn") + (className ? " " + className : "")} title={route ? route + " · " + hint : "Route not set"}>
      <span className="sp-cust-group-name">{route || "Route not set"}</span>
      {hint ? <span className="sp-cust-group-hint">{hint}</span> : null}
      <span className="tnum sp-cust-group-count">{count}</span>
    </div>
  );
}

/* The route choice, used when adding and when editing. The view never decides what is valid. */
function SpecialRouteSelect({ value, onChange, className }) {
  return (
    <select className={"f-select" + (className ? " " + className : "")} value={value} onChange={(e) => onChange(e.target.value)}>
      <option value="">Route (required)</option>
      {PLM.SPECIAL_ROUTES.map((r) => <option key={r.id} value={r.id}>{r.id + " · " + r.hint}</option>)}
    </select>
  );
}

function SpecialCustomers({ nav, toast }) {
  const state = PLM.useStore();
  const list = PLM.specialList();
  const [draft, setDraft] = useState("");
  const [route, setRoute] = useState("");
  const [msg, setMsg] = useState("");
  const [filter, setFilter] = useState("all");
  const [editId, setEditId] = useState(null);
  const [editName, setEditName] = useState("");
  const [editRoute, setEditRoute] = useState("");
  const [editMsg, setEditMsg] = useState("");
  const addRef = useRef(null);
  /* On a phone the panel sits above the price list, folded to its heading until opened.
     On a desktop it is always open and the Show / Hide chip is not drawn (see app.css). */
  const [open, setOpen] = useState(false);
  const counts = PLM.specialRouteCounts();
  const groups = PLM.specialCustomerGroups();
  /* the Not set chip goes away once the last such customer is fixed, so a filter on it falls back to All */
  const active = filter === "none" && !counts.notSet ? "all" : filter;
  const shownGroups = active === "all" ? groups : groups.filter((g) => (active === "none" ? g.route === "" : g.route === active));
  const canAdd = !!draft.trim() && PLM.specialRouteOk(route);

  function add() {
    if (!draft.trim()) return;
    if (!PLM.specialRouteOk(route)) { setMsg("Choose a route. A customer cannot be added without one."); return; }
    const c = PLM.specialAddCustomer(draft, route);
    if (!c) { setMsg("Already on the list."); return; }
    toast("Added " + c.name + " to " + c.route);
    /* a filter on another route would hide the name just added */
    if (active !== "all" && active !== c.route) setFilter("all");
    setDraft("");
    setRoute("");
    setMsg("");
    if (addRef.current) addRef.current.focus();
  }
  function startEdit(c) {
    setEditName(c.name);
    setEditRoute(PLM.specialRouteOk(c.route) ? c.route : "");
    setEditMsg("");
    setEditId(c.id);
  }
  function cancelEdit() { setEditId(null); setEditMsg(""); }
  const canSave = !!editName.trim() && PLM.specialRouteOk(editRoute);
  function saveEdit(c) {
    /* Save is off without a name and a route; Enter in the name box comes here too, so say why */
    if (!editName.trim()) return;
    if (!PLM.specialRouteOk(editRoute)) { setEditMsg("Choose a route."); return; }
    const nm = editName.trim();
    if (nm === c.name && editRoute === c.route) { cancelEdit(); return; }
    if (PLM.specialUpdateCustomer(c.id, nm, editRoute)) {
      toast("Saved " + nm);
      cancelEdit();
    } else {
      setEditMsg("Another customer already has this name.");
    }
  }
  function chip(value, label) {
    return <button type="button" key={value} className={"fchip" + (active === value ? " fchip--on" : "")} onClick={() => setFilter(value)}>{label}</button>;
  }

  return (
    <div className={"panel panel--strong sp-customers" + (open ? " sp-customers--open" : "")}>
      <div className="sp-cust-head">
        <span className="sp-cust-title">Customers on this list</span>
        <span className="caption tnum sp-cust-count">{list.customers.length}</span>
        <button type="button" className="fchip sp-cust-toggle" aria-expanded={open} onClick={() => setOpen(!open)}>{open ? "Hide" : "Show"}</button>
      </div>
      <div className="sp-cust-body">
      <div className="caption sp-cust-note">They all get the prices in this list.</div>
      <div className="sp-cust-add">
        <input className="f-input" ref={addRef} placeholder="Customer name" value={draft}
          onChange={(e) => { setDraft(e.target.value); setMsg(""); }}
          onKeyDown={(e) => { if (e.key === "Enter") add(); }} />
        <div className="sp-cust-add2">
          <SpecialRouteSelect value={route} onChange={(v) => { setRoute(v); setMsg(""); }} className="sp-route-select"></SpecialRouteSelect>
          <Btn size="sm" disabled={!canAdd} onClick={add}>Add</Btn>
        </div>
      </div>
      {msg ? <div className="caption sp-cust-msg">{msg}</div> : null}
      {counts.notSet ? (
        <div className="caption sp-cust-warn">{counts.notSet === 1 ? "1 customer has no route yet. Set it." : counts.notSet + " customers have no route yet. Set one for each."}</div>
      ) : null}
      {list.customers.length ? (
        <div className="sp-route-chips">
          {chip("all", "All (" + counts.total + ")")}
          {PLM.SPECIAL_ROUTES.map((r) => chip(r.id, r.id + " (" + counts.byRoute[r.id] + ")"))}
          {counts.notSet ? chip("none", "Not set (" + counts.notSet + ")") : null}
        </div>
      ) : null}
      {list.customers.length ? (
        shownGroups.length ? (
          <div className="sp-cust-list">
            {shownGroups.map((g) => (
              <React.Fragment key={g.route || "none"}>
                <SpecialRouteHeading route={g.route} count={g.customers.length}></SpecialRouteHeading>
                {g.customers.map((c) => (
                  editId === c.id ? (
                    <div className="sp-cust-row sp-cust-row--edit" key={c.id}>
                      <input className="f-input sp-cust-edit" autoFocus value={editName}
                        onChange={(e) => { setEditName(e.target.value); setEditMsg(""); }}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") saveEdit(c);
                          if (e.key === "Escape") cancelEdit();
                        }} />
                      <SpecialRouteSelect value={editRoute} onChange={(v) => { setEditRoute(v); setEditMsg(""); }} className="sp-route-select"></SpecialRouteSelect>
                      {editMsg ? <div className="caption sp-cust-msg">{editMsg}</div> : null}
                      <div className="sp-cust-edit-btns">
                        <Btn size="sm" disabled={!canSave} onClick={() => saveEdit(c)}>Save</Btn>
                        <Btn variant="ghost" size="sm" onClick={cancelEdit}>Cancel</Btn>
                      </div>
                    </div>
                  ) : (
                    <div className="sp-cust-row" key={c.id}>
                      {/* Set route sits under the name: beside it, it left the name 56px of a 300px panel */}
                      <span className="sp-cust-main">
                        <span className="sp-cust-name">{c.name}</span>
                        {!PLM.specialRouteOk(c.route) ? <button type="button" className="fchip sp-setroute" onClick={() => startEdit(c)}>Set route</button> : null}
                      </span>
                      <span className="sp-cust-acts">
                        <IconBtn title="Edit" onClick={() => startEdit(c)}><IPencil size={14}></IPencil></IconBtn>
                        <IconBtn title={"Print the list for " + c.name} disabled={!list.items.length} onClick={() => nav.goPrint("special:" + c.id)}><IPrinter size={14}></IPrinter></IconBtn>
                        <IconBtn title="Remove from this list" onClick={() => { PLM.specialRemoveCustomer(c.id); toast("Removed " + c.name); }}><IX size={14}></IX></IconBtn>
                      </span>
                    </div>
                  )
                ))}
              </React.Fragment>
            ))}
          </div>
        ) : (
          <div className="caption sp-cust-empty">No customers on this route.</div>
        )
      ) : (
        <div className="caption sp-cust-empty">No customers yet. Add the customers who are given this price list.</div>
      )}
      </div>
    </div>
  );
}

/* Like RateCell in ui.jsx, but a typed price is read by PLM.specialParse (2 decimals, half up) */
function SpecialRateCell({ value, onCommit }) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState("");
  const ref = useRef(null);
  useEffect(() => { if (editing && ref.current) { ref.current.focus(); ref.current.select(); } }, [editing]);
  function start() { setDraft(PLM.fmtRate(value)); setEditing(true); }
  function commit() {
    setEditing(false);
    const r = PLM.specialParse(draft);
    if (r === null) return;
    if (Math.abs(r - value) < 0.00005) return;
    onCommit(r);
  }
  if (editing) {
    return (
      <input className="rate-input" inputMode="decimal" ref={ref} value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={(e) => { if (e.key === "Enter") commit(); if (e.key === "Escape") setEditing(false); }} />
    );
  }
  return (
    <span className="rate-view tnum" title="Click to edit. Special prices stop at 2 decimals" onClick={start}>
      {PLM.fmtRate(value)}
    </span>
  );
}

function SpecialItemRow({ it, no, toast }) {
  const pb = PLM.productsById();
  const p = it.productId ? pb[it.productId] : null;
  const name = p ? p.name : it.customName;
  const stale = PLM.itemStale(it);
  const d = p ? PLM.deltaPct(it.rate, p.rate) : null;
  const gst = p ? p.gst : it.gst;
  const pack = p ? p.packSize : it.packSize;

  function reviewChips() {
    return (
      <React.Fragment>
        <span className="chip chip--warn" title={"Master was ₹" + PLM.fmtRate(it.baseRate) + " when this price was set, now ₹" + PLM.fmtRate(p.rate)}>
          <IAlert size={10}></IAlert> ₹{PLM.fmtRate(it.baseRate)} → ₹{PLM.fmtRate(p.rate)}
        </span>
        <button type="button" className="fchip" title="Keep this special price"
          onClick={() => { PLM.specialKeep(it.id); toast("Kept ₹" + PLM.fmtRate(it.rate) + " for " + name); }}>Keep</button>
        <button type="button" className="fchip" title="Set the special price to the master price"
          onClick={() => { PLM.specialMatch(it.id); toast(name + " matched to the master price"); }}>Match</button>
      </React.Fragment>
    );
  }

  return (
    <tr className={"item-row" + (stale ? " sp-row-stale" : "")}>
      <td className="col-no">{no}</td>
      <td>
        <div className="sp-item-line">
          <span>{name}</span>
          {!p ? <span className="chip sp-chip-sm">Custom</span> : null}
        </div>
        <div className="row-meta">{p ? "Master ₹" + PLM.fmtRate(p.rate) + " · " : ""}GST {PLM.fmtGst(gst)} · Pack {PLM.fmtPack(pack)}</div>
        {stale && p ? <div className="sp-review">{reviewChips()}</div> : null}
      </td>
      <td className="num rate">
        <SpecialRateCell value={it.rate} onCommit={(r) => {
          PLM.specialSetRate(it.id, r);
          toast(name + " now ₹" + PLM.fmtRate(r));
        }}></SpecialRateCell>
      </td>
      <td className="num col-master tnum sp-faint">{p ? "₹" + PLM.fmtRate(p.rate) : "-"}</td>
      <td className={"num tnum" + (p && d ? (d.charAt(0) === "+" ? " sp-diff-up" : " sp-diff-down") : "")}>{p ? (d || "=") : ""}</td>
      <td className="num col-gst">{PLM.fmtGst(gst)}</td>
      <td className="num col-pack">{PLM.fmtPack(pack)}</td>
      <td className="num col-outer">{PLM.fmtPack(p ? p.outerPack : null)}</td>
      <td>
        <span className="row-actions">
          <IconBtn title="Remove from the special price list" onClick={() => PLM.specialRemoveItem(it.id)}><IX size={14}></IX></IconBtn>
        </span>
      </td>
    </tr>
  );
}

function SpecialAddItemsDialog({ onClose, toast }) {
  const state = PLM.useStore();
  const [q, setQ] = useState("");
  const [sel, setSel] = useState({});
  const existing = new Set(PLM.specialList().items.map((it) => it.productId).filter(Boolean));
  const nums = PLM.numberMap();
  const list = state.products
    .filter((p) => !existing.has(p.id))
    .filter((p) => !q.trim() || p.name.toLowerCase().includes(q.trim().toLowerCase()));
  const selIds = Object.keys(sel).filter((k) => sel[k]);

  function selectShown() {
    const next = { ...sel };
    list.forEach((p) => { next[p.id] = true; });
    setSel(next);
  }
  function add() {
    const n = PLM.specialAddItems(selIds);
    toast("Added " + n + " item" + (n === 1 ? "" : "s") + " to the special price list");
    onClose();
  }
  return (
    <Dialog title="Add items to the special price list" onClose={onClose} width={640}
      footer={
        <React.Fragment>
          <span className="caption sp-foot-note">Added at the master price, rounded to 2 decimals. Adjust after adding.</span>
          <Btn variant="ghost" size="sm" onClick={onClose}>Cancel</Btn>
          <Btn size="sm" disabled={!selIds.length} onClick={add}>
            Add {selIds.length || ""} item{selIds.length === 1 ? "" : "s"}
          </Btn>
        </React.Fragment>
      }>
      <div className="search-box" style={{ marginBottom: 12 }}>
        <ISearch size={15}></ISearch>
        <input className="f-input" style={{ width: "100%" }} placeholder="Search master list…" value={q} onChange={(e) => setQ(e.target.value)} autoFocus />
      </div>
      <div className="sp-add-bar">
        <button type="button" className="fchip" onClick={selectShown}>Select all shown ({list.length})</button>
        <button type="button" className="fchip" onClick={() => setSel({})}>Clear</button>
      </div>
      <div className="panel sp-add-list">
        <table className="plm-table">
          <tbody>
            {list.map((p) => {
              const rounded = PLM.specialRound(p.rate);
              const fine = rounded !== null && Math.abs(rounded - p.rate) > 0.00005;
              return (
                <tr key={p.id} className="item-row" style={{ cursor: "pointer" }} onClick={() => setSel({ ...sel, [p.id]: !sel[p.id] })}>
                  <td style={{ width: 36 }}>
                    <input type="checkbox" checked={!!sel[p.id]} readOnly style={{ accentColor: "#000000" }} />
                  </td>
                  <td className="col-no">{nums[p.id]}</td>
                  <td>{p.name}</td>
                  <td className="num tnum">₹{PLM.fmtRate(p.rate)}{fine ? ", added as ₹" + PLM.fmtRate(rounded) : ""}</td>
                  <td className="num col-gst" style={{ width: 60 }}>{PLM.fmtGst(p.gst)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {!list.length ? <div className="caption" style={{ padding: 16 }}>Nothing to add{q ? " for “" + q + "”" : ""}.</div> : null}
      </div>
    </Dialog>
  );
}

const SPECIAL_STEP_OPTIONS = [
  { value: "1", label: "₹0.01" },
  { value: "5", label: "₹0.05" },
  { value: "10", label: "₹0.10" },
  { value: "50", label: "₹0.50" },
  { value: "100", label: "₹1" },
];

function SpecialIncreaseDialog({ onClose, toast }) {
  const state = PLM.useStore();
  const [scope, setScope] = useState("all");
  const [pctText, setPctText] = useState("");
  const [step, setStep] = useState("1");
  const [note, setNote] = useState("");

  const scopeOptions = [{ value: "all", label: "All items" }];
  state.categories.forEach((c) => {
    scopeOptions.push({ value: "cat:" + c.id, label: c.name });
    c.subs.forEach((s) => scopeOptions.push({ value: "sub:" + c.id + ":" + s.id, label: "· " + c.name + " · " + s.name }));
  });

  const p4 = PLM.specialPct(pctText);
  const stepPaise = parseInt(step, 10);
  const plan = p4 === null ? null : PLM.specialPlan({ scope: scope, p4: p4, stepPaise: stepPaise });
  const n = plan ? plan.lines.length : 0;
  const downCount = plan ? plan.lines.filter((l) => l.down).length : 0;
  const LIMIT = 300;
  const shown = plan ? plan.lines.slice(0, LIMIT) : [];

  function apply() {
    const r = PLM.specialApply({ scope: scope, p4: p4, stepPaise: stepPaise, note: note.trim() });
    if (!r.count) { toast("Nothing was changed"); onClose(); return; }
    toast("Changed " + r.count + " special " + specialPlural(r.count, "price", "prices") + " by " + PLM.specialPctLabel(p4) + ". Undo from History if needed.");
    onClose();
  }

  return (
    <Dialog title="Increase special prices" onClose={onClose} width={640}
      footer={
        <React.Fragment>
          <Btn variant="ghost" size="sm" onClick={onClose}>Cancel</Btn>
          <Btn size="sm" disabled={!n} onClick={apply}>Apply to {n} {specialPlural(n, "price", "prices")}</Btn>
        </React.Fragment>
      }>
      <div className="f-stack">
        <div className="f-row">
          <Field label="Items">
            <select className="f-select" value={scope} onChange={(e) => setScope(e.target.value)}>
              {scopeOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </Field>
          <Field label="Change by %">
            <input className="f-input" inputMode="decimal" placeholder="e.g. 5" value={pctText} onChange={(e) => setPctText(e.target.value)} autoFocus />
          </Field>
          <Field label="Round to">
            <select className="f-select" value={step} onChange={(e) => setStep(e.target.value)}>
              {SPECIAL_STEP_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </Field>
        </div>
        <div className="caption sp-hint">Use a minus sign to reduce, for example -2.5.</div>

        <Field label="Note (shown in history)">
          <input className="f-input" placeholder="e.g. Annual revision, November 2026" value={note} onChange={(e) => setNote(e.target.value)} />
        </Field>

        <div>
          <div className="f-label">Preview{plan ? " (" + n + " " + specialPlural(n, "price changes", "prices change") + ")" : ""}</div>
          <div className="panel sp-preview">
            {!plan ? (
              <div className="caption" style={{ padding: 16 }}>Enter a percentage to preview the changes, for example 5 or 7.5.</div>
            ) : !n ? (
              <div className="caption" style={{ padding: 16 }}>Nothing would change with these settings.</div>
            ) : (
              <table className="plm-table">
                <tbody>
                  {shown.map((l) => (
                    <tr key={l.itemId}>
                      <td>
                        {l.itemName}
                        {l.down ? <div className="sp-prev-flag"><span className="chip chip--warn sp-chip-sm">moves the other way</span></div> : null}
                      </td>
                      <td className="num tnum sp-prev-old">₹{PLM.fmtRate(l.old)}</td>
                      <td className="sp-prev-arrow"><IArrowR size={12}></IArrowR></td>
                      <td className="num tnum rate sp-prev-new">₹{PLM.fmtRate(l.new)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
            {plan && n > LIMIT ? <div className="caption" style={{ padding: "8px 12px" }}>Showing the first {LIMIT} of {n}.</div> : null}
          </div>
        </div>

        {plan && plan.zero > 0 ? <div className="caption">{plan.zero} {specialPlural(plan.zero, "price", "prices")} left alone, because this rounding step would take {plan.zero === 1 ? "it" : "them"} to zero.</div> : null}
        {downCount > 0 ? <div className="caption">{downCount} {specialPlural(downCount, "price moves", "prices move")} the other way because of the rounding step. Check them in the preview.</div> : null}
        <div className="caption">Special prices stop at 2 decimals, and half a paisa rounds up. Every run is recorded under History and can be undone from there.</div>
      </div>
    </Dialog>
  );
}

function SpecialPrintDialog({ nav, onClose }) {
  const state = PLM.useStore();
  const list = PLM.specialList();
  const groups = PLM.specialCustomerGroups();
  if (!list.customers.length) {
    return (
      <Dialog title="Print the special price list" onClose={onClose} width={480}
        footer={<Btn variant="ghost" size="sm" onClick={onClose}>Close</Btn>}>
        <div className="caption">Add a customer first. The list prints with the customer's name on it.</div>
      </Dialog>
    );
  }
  return (
    <Dialog title="Print the special price list" onClose={onClose} width={480}
      footer={<Btn variant="ghost" size="sm" onClick={onClose}>Cancel</Btn>}>
      <div className="caption" style={{ marginBottom: 12 }}>Choose the customer whose name goes on the sheet.</div>
      <div className="sp-print-list">
        {groups.map((g) => (
          <React.Fragment key={g.route || "none"}>
            <SpecialRouteHeading route={g.route} count={g.customers.length} className="sp-print-group"></SpecialRouteHeading>
            {g.customers.map((c) => (
              <Btn key={c.id} variant="secondary" size="sm" className="sp-print-btn" onClick={() => { onClose(); nav.goPrint("special:" + c.id); }}>{c.name}</Btn>
            ))}
          </React.Fragment>
        ))}
      </div>
    </Dialog>
  );
}

Object.assign(window, { SpecialView });
