// hydor-forms.jsx — modal forms for products, transactions, costs, contacts.
// Depends on hydor-engine.js + hydor-ui.jsx. Exports product/tx/cost/party form openers.
const Hf = window.Hydor;

const todayStr = () => new Date().toISOString().slice(0, 10);

/* ============================ PRODUCT FORM ============================ */
function ProductForm({ editing, onClose }) {
  const push = useToast();
  const cats = ["Point-of-Use Drinking", "Whole-House Filtration", "Water Softeners", "Pool Treatment", "Pool Heating", "Pumps", "Consumables & Spares", "Other"];
  const [f, setF] = React.useState(editing
    ? { code: editing.code, name: editing.name, category: editing.category || "", minPct: editing.minPct, reorder: editing.reorder, warrantyMonths: editing.warrantyMonths || 0, serviceMonths: editing.serviceMonths || 0 }
    : { code: "", name: "", category: cats[0], minPct: 150, reorder: 0, warrantyMonths: 12, serviceMonths: 6 });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = () => {
    if (!f.name.trim()) return push("Product name is required.", "err");
    try {
      if (editing) { Hf.updateProduct(editing.id, f); push("Product updated."); }
      else { const p = Hf.addProduct(f); push(`Product ${p.code} added.`); }
      onClose();
    } catch (err) { push(err.message, "err"); }
  };
  return (
    <Modal title={editing ? "Edit product" : "New product"} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>{editing ? "Save changes" : "Add product"}</Btn>
    </>}>
      <div className="form-grid">
        <Field label="Product code" hint="Leave blank to auto-generate">
          <input className="inp" value={f.code} onChange={set("code")} placeholder="HX-RO-700" />
        </Field>
        <Field label="Category">
          <select className="sel" value={f.category} onChange={set("category")}>
            {cats.map((c) => <option key={c} value={c}>{c}</option>)}
          </select>
        </Field>
        <Field label="Product name" span2>
          <input className="inp" value={f.name} onChange={set("name")} placeholder="e.g. 5-Stage Reverse Osmosis Drinking System" autoFocus />
        </Field>
        <Field label="Min. price markup %" span2
          hint={`Recommended sell price = unit cost × ${(Hydor.num(f.minPct, 0) / 100).toFixed(2)}. Staff are blocked from selling below this floor; managers can override with a flag.`} hintWarn={Hydor.num(f.minPct, 0) < 100}>
          <Affix affix="%"><input className="inp num" type="number" value={f.minPct} onChange={set("minPct")} style={{ paddingRight: 30 }} /></Affix>
        </Field>
        <Field label="Reorder point" hint="Alert when stock drops to this">
          <input className="inp num" type="number" value={f.reorder} onChange={set("reorder")} />
        </Field>
        <Field label="Warranty (months)" hint="0 = none">
          <input className="inp num" type="number" value={f.warrantyMonths} onChange={set("warrantyMonths")} />
        </Field>
        <Field label="Service / cartridge interval (months)" span2 hint="0 = none. Auto-creates a customer-service follow-up this many months after each sale (e.g. RO cartridge replacement).">
          <input className="inp num" type="number" value={f.serviceMonths} onChange={set("serviceMonths")} />
        </Field>
      </div>
    </Modal>
  );
}

/* ============================ TRANSACTION FORM ============================ */
function TxForm({ editing, presetType, defaultEmployee, onClose }) {
  const push = useToast();
  const s = Hydor.getState();
  const d = Hydor.derive();
  const me = Hydor.currentUser();
  const role = me ? me.role : s.meta.role;
  const canBelow = Hydor.can(role, "sellBelowFloor");
  const canPurchase = Hydor.can(role, "postPurchases");      // only owner/co-founder add purchases & adjustments
  const seeAllContacts = Hydor.can(role, "seeAllContacts");
  const txTypes = canPurchase ? ["purchase", "sale", "adjustment", "maintenance_contract"] : ["sale", "maintenance_contract"];
  const TX_LABELS = { sale: "Sale", purchase: "Purchase", adjustment: "Adjustment", maintenance_contract: "Maintenance Contract" };
  const [f, setF] = React.useState(() => editing ? {
    date: editing.date, type: editing.type, productId: editing.productId || "",
    unitCost: editing.unitCost ?? "", actualSell: editing.actualSell ?? "", qty: editing.qty,
    taxable: editing.taxable, employee: editing.employee || "", partyId: editing.partyId || "",
    paid: editing.paid, opening: editing.opening, notes: editing.notes || "",
    contractValue: editing.contractValue ?? "", contractStartDate: editing.contractStartDate || todayStr(),
    contractDurationYears: editing.contractDurationYears ?? 1, contractSignature: editing.contractSignature || "",
    contractSignedBy: editing.contractSignedBy || "", customerEmail: editing.customerEmail || "", _showContract: false,
  } : {
    date: todayStr(), type: presetType || (canPurchase ? "purchase" : "sale"), productId: s.products[0] ? s.products[0].id : "",
    unitCost: "", actualSell: "", qty: "", taxable: true, employee: defaultEmployee || "", partyId: "", paid: true, opening: false, notes: "",
    contractValue: "", contractStartDate: todayStr(), contractDurationYears: 1, contractSignature: "", contractSignedBy: "", customerEmail: "", _showContract: false,
  });
  // installment plan (sales only; not on edit for simplicity)
  const [inst, setInst] = React.useState({ enabled: false, downPayment: "", count: 3, frequency: "monthly", startDate: todayStr() });
  const setI = (k, v) => setInst((p) => ({ ...p, [k]: v }));
  const set = (k, val) => setF((p) => ({ ...p, [k]: val }));
  const prod = s.products.find((p) => p.id === f.productId);
  const pstat = prod && d.productStats[f.productId];
  const recPrice = pstat ? pstat.recPrice : 0;
  const errs = Hydor.validateTransaction({ ...f, qty: Hydor.num(f.qty, 0), role }, { editingId: editing && editing.id, role });
  // prices are tax-inclusive — compare the net (ex-tax) portion against the floor
  const netUnit = f.taxable ? Hydor.num(f.actualSell) / (1 + d.taxRate) : Hydor.num(f.actualSell);
  const belowRec = f.type === "sale" && f.actualSell !== "" && netUnit < recPrice - 1e-9 && recPrice > 0;

  const grandTotal = Hydor.num(f.actualSell) * Hydor.num(f.qty);   // tax already included in the price
  const contractGross = f.type === "maintenance_contract" ? Hydor.num(f.contractValue, 0) : 0;
  const instCheck = inst.enabled ? Hydor.validateInstallment(inst, grandTotal) : null;
  const save = () => {
    try {
      if (editing) { Hydor.updateTransaction(editing.id, f); push("Transaction updated."); }
      else {
        const payload = { ...f, role };
        if (f.type === "sale" && inst.enabled) {
          const chk = Hydor.validateInstallment(inst, grandTotal);
          if (!chk.ok) { push(chk.errors[0], "err"); return; }
          if (chk.belowMin && !canBelow) {
            push("Each instalment is below 50 JOD — this needs manager / founder approval. Use Quick add → Request price approval, or raise the instalment amount.", "err");
            return;
          }
          payload.installment = { ...inst, total: grandTotal };
          payload.installmentBelowMin = chk.belowMin;
        }
        Hydor.addTransaction(payload);
        const txLabel = TX_LABELS[f.type] || Hydor.cap(f.type);
        push(`${txLabel} posted.${belowRec ? " Flagged for owner review." : ""}${inst.enabled && instCheck && instCheck.belowMin ? " Low-instalment sale flagged." : ""}`);
      }
      onClose();
    } catch (err) { push(err.message, "err"); }
  };
  const customers = s.parties.filter((p) => p.type === "customer" && (seeAllContacts || !p.createdBy || (me && p.createdBy === me.id)));
  const suppliers = s.parties.filter((p) => p.type === "supplier");

  const lineTotal = f.type === "sale"
    ? Hydor.num(f.actualSell) * Hydor.num(f.qty)
    : f.type === "maintenance_contract" ? contractGross
    : f.type === "purchase" ? Hydor.num(f.unitCost) * Hydor.num(f.qty) : 0;
  // tax-inclusive breakdown for the sale line
  const lineTaxRate = d.taxRate || 0;
  const lineNet = f.taxable ? lineTotal / (1 + lineTaxRate) : lineTotal;
  const lineTax = lineTotal - lineNet;

  return (
    <Modal title={editing ? "Edit transaction" : "New transaction"} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save} disabled={errs.length > 0}>{editing ? "Save changes" : "Post transaction"}</Btn>
    </>}>
      {/* type selector */}
      {txTypes.length > 1 && (
      <div className="hx-seg" style={{ marginBottom: 18, width: "100%", display: "flex" }}>
        {txTypes.map((t) => (
          <button key={t} className={f.type === t ? "on" : ""} style={{ flex: 1 }}
            disabled={!!editing} onClick={() => set("type", t)}>{TX_LABELS[t] || Hydor.cap(t)}</button>
        ))}
      </div>
      )}
      <div className="form-grid">
        <Field label="Date"><input className="inp" type="date" value={f.date} onChange={(e) => set("date", e.target.value)} /></Field>

        {f.type !== "maintenance_contract" && (
          <Field label="Product">
            <select className="sel" value={f.productId} onChange={(e) => set("productId", e.target.value)}>
              {s.products.length === 0 && <option value="">No products yet</option>}
              {s.products.map((p) => <option key={p.id} value={p.id}>{p.code} · {p.name}</option>)}
            </select>
          </Field>
        )}

        {f.type !== "maintenance_contract" && prod && (
          <div className="span2" style={{ display: "flex", gap: 18, padding: "2px 2px 4px", fontSize: 12, color: "var(--text-3)" }}>
            <span>In stock: <b className="hx-num" style={{ color: "var(--text)" }}>{Hydor.fmtQty(pstat.remaining)}</b></span>
            {Hydor.can(role, "seeProductCost") && <span>Avg cost: <b className="hx-num" style={{ color: "var(--text)" }}>{Hydor.fmtMoney(pstat.avgCost)}</b></span>}
            {f.type === "sale" && recPrice > 0 && <span>Recommended price: <b className="hx-num" style={{ color: "var(--accent-2)" }}>{Hydor.fmtMoney(recPrice)}</b></span>}
          </div>
        )}

        {f.type !== "maintenance_contract" && (
          <Field label="Quantity"><input className="inp num" type="number" value={f.qty} onChange={(e) => set("qty", e.target.value)} placeholder="0" autoFocus /></Field>
        )}

        {/* ===== MAINTENANCE CONTRACT FIELDS ===== */}
        {f.type === "maintenance_contract" && (
          <>
            <Field label="Contract value (tax included)" span2>
              <Affix affix="JOD"><input className="inp num" type="number" step="0.001" value={f.contractValue} onChange={(e) => set("contractValue", e.target.value)} placeholder="100.000" style={{ paddingRight: 44 }} autoFocus /></Affix>
            </Field>
            <Field label="Contract start date">
              <input className="inp" type="date" value={f.contractStartDate} onChange={(e) => set("contractStartDate", e.target.value)} />
            </Field>
            <Field label="Duration (years)">
              <input className="inp num" type="number" min="1" step="1" value={f.contractDurationYears} onChange={(e) => set("contractDurationYears", e.target.value)} />
            </Field>
            <Field label="Sold by" span2 hint="Employee who closed this contract">
              <select className="sel" value={f.employee} onChange={(e) => set("employee", e.target.value)}>
                <option value="">— select —</option>
                {s.users.filter((u) => u.active && u.code).map((u) => <option key={u.id} value={u.code}>{u.code} · {u.name}</option>)}
              </select>
            </Field>
            <Field label="Customer" span2>
              <select className="sel" value={f.partyId} onChange={(e) => set("partyId", e.target.value)}>
                <option value="">— select customer —</option>
                {customers.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="Customer email" span2 hint="A copy of the signed contract will be sent here">
              <input className="inp" type="email" value={f.customerEmail} onChange={(e) => set("customerEmail", e.target.value)} placeholder="customer@email.com" />
            </Field>
            <div className="span2">
              {f.contractSignature ? (
                <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", background: "#34d3a01a", border: "1px solid var(--pos)", borderRadius: 12, flexWrap: "wrap" }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--pos)" strokeWidth="2.2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><path d="M22 4L12 14.01l-3-3"/></svg>
                  <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--pos)" }}>Contract signed electronically</span>
                  <img src={f.contractSignature} alt="signature" style={{ height: 36, borderRadius: 6, background: "#fff", padding: "2px 8px" }} />
                  <Btn sm variant="ghost" onClick={() => set("contractSignature", "")}>Re-sign</Btn>
                  {f.customerEmail && (
                    <Btn sm icon="mail" variant="ghost" onClick={() => {
                      const cust = customers.find(c => c.id === f.partyId);
                      const custName = cust ? cust.name : f.customerEmail;
                      const co = s.meta.company || "HYDOR";
                      const isAr = window.HydorI18n && window.HydorI18n.getLang() === "ar";
                      const subj = isAr ? `عقد صيانة — ${co}` : `Maintenance Contract — ${co}`;
                      const startFmt = new Date(f.contractStartDate).toLocaleDateString(isAr ? "ar-JO" : "en-GB", { day:"2-digit", month:"long", year:"numeric" });
                      const endDate = new Date(f.contractStartDate); endDate.setFullYear(endDate.getFullYear() + Number(f.contractDurationYears || 1));
                      const endFmt = endDate.toLocaleDateString(isAr ? "ar-JO" : "en-GB", { day:"2-digit", month:"long", year:"numeric" });
                      const body = isAr
                        ? `عزيزي ${custName}،\n\nيسعدنا إحاطتكم بأن عقد الصيانة الخاص بكم قد تم توقيعه إلكترونياً.\n\n` +
                          `قيمة العقد: ${Hydor.fmtMoney0(f.contractValue)} دينار أردني\n` +
                          `تاريخ البداية: ${startFmt}\nتاريخ الانتهاء: ${endFmt}\n` +
                          `المدة: ${f.contractDurationYears} ${Number(f.contractDurationYears) === 1 ? "سنة" : "سنوات"}\n\n` +
                          `يشمل العقد 3 زيارات صيانة دورية سنوياً (كل 4 أشهر)، وتغيير الفلاتر مرة سنوياً، والدعم الفني.\n\n` +
                          `شكراً لثقتكم بنا،\nفريق ${co}`
                        : `Dear ${custName},\n\nYour maintenance contract with ${co} has been signed electronically.\n\n` +
                          `Contract value: ${Hydor.fmtMoney0(f.contractValue)} JOD\n` +
                          `Start date: ${startFmt}\nEnd date: ${endFmt}\nDuration: ${f.contractDurationYears} year${Number(f.contractDurationYears) !== 1 ? "s" : ""}\n\n` +
                          `This contract includes 3 periodic maintenance visits per year (every 4 months), annual filter replacement, and technical support.\n\n` +
                          `Thank you for your trust,\n${co} Team`;
                      window.open(`mailto:${f.customerEmail}?subject=${encodeURIComponent(subj)}&body=${encodeURIComponent(body)}`);
                    }}>Send email copy</Btn>
                  )}
                </div>
              ) : (
                <div style={{ textAlign: "center" }}>
                  <Btn variant="primary" icon="edit" disabled={!f.partyId} onClick={() => set("_showContract", true)}>
                    View contract &amp; sign
                  </Btn>
                  {!f.partyId && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 6 }}>Select a customer first</div>}
                </div>
              )}
            </div>
            {f._showContract && (
              <DrawToSignContract
                value={f.contractValue} startDate={f.contractStartDate}
                durationYears={f.contractDurationYears}
                customerName={customers.find(c => c.id === f.partyId) ? customers.find(c => c.id === f.partyId).name : ""}
                company={s.meta.company}
                onSign={(sig) => { set("contractSignature", sig); set("_showContract", false); }}
                onCancel={() => set("_showContract", false)}
              />
            )}
          </>
        )}

        {f.type === "purchase" && (
          <Field label="Unit cost" hint="What you paid per unit">
            <Affix affix="JOD"><input className="inp num" type="number" step="0.001" value={f.unitCost} onChange={(e) => set("unitCost", e.target.value)} placeholder="0.000" style={{ paddingRight: 44 }} /></Affix>
          </Field>
        )}
        {f.type === "sale" && (
          <Field label="Actual sell price (tax included)"
            error={belowRec && !canBelow ? `Net ${Hydor.fmtMoney(netUnit)} ex-tax is below the ${Hydor.fmtMoney(recPrice)} floor — a manager or owner must post this sale` : null}
            hint={belowRec && canBelow ? `Net ${Hydor.fmtMoney(netUnit)} ex-tax is below the ${Hydor.fmtMoney(recPrice)} floor — will be flagged & the owner notified` : null} hintWarn={belowRec && canBelow}>
            <Affix affix="JOD"><input className={"inp num" + (belowRec ? " err" : "")} type="number" step="0.001" value={f.actualSell} onChange={(e) => set("actualSell", e.target.value)} placeholder="0.000" style={{ paddingRight: 44 }} /></Affix>
          </Field>
        )}
        {f.type === "adjustment" && (
          <Field label="Direction" hint="Use negative qty to remove stock (shrinkage, damage)">
            <div style={{ fontSize: 12, color: "var(--text-2)", paddingTop: 8 }}>Positive adds stock · negative removes</div>
          </Field>
        )}

        {f.type === "sale" && (
          <Field label="Sold by" hint="Employee code">
            <select className="sel" value={f.employee} onChange={(e) => set("employee", e.target.value)}>
              <option value="">— select —</option>
              {s.users.filter((u) => u.active && u.code).map((u) => <option key={u.id} value={u.code}>{u.code} · {u.name}</option>)}
            </select>
          </Field>
        )}
        {(f.type === "sale" || f.type === "purchase") && (
          <Field label={f.type === "sale" ? "Customer" : "Supplier"}>
            <select className="sel" value={f.partyId} onChange={(e) => set("partyId", e.target.value)}>
              <option value="">— none —</option>
              {(f.type === "sale" ? customers : suppliers).map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </Field>
        )}

        {f.type !== "adjustment" && (
          <Field label="Payment & tax" span2>
            <div style={{ display: "flex", gap: 18, flexWrap: "wrap", paddingTop: 4 }}>
              <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-2)", cursor: "pointer" }}>
                <input type="checkbox" checked={f.paid} onChange={(e) => set("paid", e.target.checked)} />
                {f.type === "sale" ? "Paid (uncheck = on credit / receivable)" : "Paid (uncheck = on credit / payable)"}
              </label>
              <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-2)", cursor: "pointer" }}>
                <input type="checkbox" checked={f.taxable} onChange={(e) => set("taxable", e.target.checked)} />
                Taxable — price includes {(d.taxRate * 100).toFixed(0)}% GST
              </label>
            </div>
          </Field>
        )}

        {f.type === "purchase" && (
          <label className="span2" style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-2)", cursor: "pointer" }}>
            <input type="checkbox" checked={f.opening} onChange={(e) => set("opening", e.target.checked)} />
            This is an opening balance (stock I already owned before using HYDOR)
          </label>
        )}

        {f.type === "sale" && !editing && (
          <div className="span2" style={{ border: "1px solid var(--border)", borderRadius: 11, padding: "12px 14px", background: "var(--bg-2)" }}>
            <label style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13.5, fontWeight: 500, cursor: "pointer" }}>
              <input type="checkbox" checked={inst.enabled} onChange={(e) => setI("enabled", e.target.checked)} />
              Customer pays in installments
            </label>
            {inst.enabled && (
              <>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginTop: 12 }}>
                  <Field label="Down payment">
                    <Affix affix="JOD"><input className="inp num" type="number" step="0.001" value={inst.downPayment} onChange={(e) => setI("downPayment", e.target.value)} placeholder="0.000" style={{ paddingRight: 44 }} /></Affix>
                  </Field>
                  <Field label="No. of installments" hint="Max 6-month plan">
                    <input className="inp num" type="number" min="1" max="6" value={inst.count} onChange={(e) => setI("count", e.target.value)} />
                  </Field>
                  <Field label="Frequency">
                    <select className="sel" value={inst.frequency} onChange={(e) => setI("frequency", e.target.value)}>
                      <option value="weekly">Weekly</option>
                      <option value="monthly">Monthly</option>
                      <option value="quarterly">Quarterly</option>
                    </select>
                  </Field>
                  <Field label="First installment due" span2>
                    <input className="inp" type="date" value={inst.startDate} onChange={(e) => setI("startDate", e.target.value)} />
                  </Field>
                </div>
                {grandTotal > 0 && Hydor.num(inst.count, 0) > 0 && instCheck && (
                  <div style={{ fontSize: 12, marginTop: 8, lineHeight: 1.5 }}>
                    <div style={{ color: "var(--text-2)" }}>
                      {Hydor.fmtMoney0(grandTotal)} JOD total · {Hydor.num(inst.downPayment) > 0 ? Hydor.fmtMoney0(inst.downPayment) + " down + " : ""}
                      {Hydor.num(inst.count)} × <b className="hx-num" style={{ color: "var(--text)" }}>{Hydor.fmtMoney(instCheck.perAmount)} JOD</b> · {instCheck.months}-month plan.
                    </div>
                    {!instCheck.ok && <div style={{ color: "var(--neg)", marginTop: 5, display: "flex", gap: 6 }}><Icon name="warn" size={13} style={{ flex: "none", marginTop: 1 }} />{instCheck.errors[0]}</div>}
                    {instCheck.ok && instCheck.belowMin && (
                      <div style={{ color: "var(--warn)", marginTop: 5, display: "flex", gap: 6 }}><Icon name="warn" size={13} style={{ flex: "none", marginTop: 1 }} />
                        Each instalment is below the 50 JOD minimum — {canBelow ? "this will be flagged for the founder." : "needs manager / founder approval before it can be posted."}</div>
                    )}
                  </div>
                )}
              </>
            )}
          </div>
        )}

        <Field label="Notes" span2><input className="inp" value={f.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Optional reference / memo" /></Field>

        {lineTotal > 0 && (
          <div className="span2" style={{ padding: "12px 14px", background: "var(--bg-2)", borderRadius: 10, border: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 7 }}>
            {f.type === "sale" && f.taxable && (
              <>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-3)" }}>
                  <span>Net (ex-tax)</span><span className="hx-num">{Hydor.fmtMoney(lineNet)} JOD</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-3)" }}>
                  <span>Tax ({(lineTaxRate * 100).toFixed(0)}% · {((lineTax / lineTotal) * 100).toFixed(1)}% of price)</span><span className="hx-num">{Hydor.fmtMoney(lineTax)} JOD</span>
                </div>
                <div style={{ borderTop: "1px solid var(--border)", margin: "1px 0" }}></div>
              </>
            )}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <span style={{ fontSize: 12.5, color: "var(--text-2)" }}>{f.type === "sale" ? "Price paid by customer (incl. tax)" : "Total cost"}</span>
              <Money v={lineTotal} unit cls="" />
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}

/* ============================ COST FORM ============================ */
function CostForm({ editing, onClose }) {
  const push = useToast();
  const s = Hydor.getState();
  const d = Hydor.derive();
  const [f, setF] = React.useState(editing ? {
    date: editing.date, item: editing.item, amount: editing.amount, costType: editing.costType, category: editing.category || "Other",
    taxable: editing.taxable, paid: editing.paid, partyId: editing.partyId || "", userId: editing.userId || "", notes: editing.notes || "",
  } : { date: todayStr(), item: "", amount: "", costType: "operational", category: "Other", taxable: false, paid: true, partyId: "", userId: "", notes: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const cats = (s.meta.costCategories || ["Other"]);
  const save = () => {
    try {
      if (editing) { Hydor.updateCost(editing.id, f); push("Cost updated."); }
      else { Hydor.addCost(f); push("Cost recorded."); }
      onClose();
    } catch (err) { push(err.message, "err"); }
  };
  const suppliers = s.parties.filter((p) => p.type === "supplier");
  return (
    <Modal title={editing ? "Edit cost" : "Record company cost"} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>{editing ? "Save changes" : "Record cost"}</Btn>
    </>}>
      <div className="form-grid">
        <Field label="Date"><input className="inp" type="date" value={f.date} onChange={(e) => set("date", e.target.value)} /></Field>
        <Field label="Amount"><Affix affix="JOD"><input className="inp num" type="number" step="0.001" value={f.amount} onChange={(e) => set("amount", e.target.value)} placeholder="0.000" style={{ paddingRight: 44 }} autoFocus /></Affix></Field>
        <Field label="Description" span2><input className="inp" value={f.item} onChange={(e) => set("item", e.target.value)} placeholder="e.g. Showroom rent" /></Field>
        <Field label="Category">
          <select className="sel" value={f.category} onChange={(e) => set("category", e.target.value)}>
            {cats.map((c) => <option key={c} value={c}>{c}</option>)}
          </select>
        </Field>
        <Field label="Cost type" hint="Fixed = recurring overhead · Operational = variable">
          <select className="sel" value={f.costType} onChange={(e) => set("costType", e.target.value)}>
            <option value="fixed">Fixed</option>
            <option value="operational">Operational</option>
          </select>
        </Field>
        <Field label="Supplier / payee">
          <select className="sel" value={f.partyId} onChange={(e) => set("partyId", e.target.value)}>
            <option value="">— none —</option>
            {suppliers.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
        </Field>
        <Field label="Linked employee" hint="For salary / payroll costs">
          <select className="sel" value={f.userId} onChange={(e) => set("userId", e.target.value)}>
            <option value="">— none —</option>
            {s.users.filter((u) => u.active).map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
          </select>
        </Field>
        <Field label="Payment & tax" span2>
          <div style={{ display: "flex", gap: 18, flexWrap: "wrap", paddingTop: 4 }}>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-2)", cursor: "pointer" }}>
              <input type="checkbox" checked={f.paid} onChange={(e) => set("paid", e.target.checked)} /> Paid (uncheck = payable)
            </label>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--text-2)", cursor: "pointer" }}>
              <input type="checkbox" checked={f.taxable} onChange={(e) => set("taxable", e.target.checked)} /> Tax-deductible ({(d.taxRate * 100).toFixed(0)}% input GST)
            </label>
          </div>
        </Field>
        <Field label="Notes" span2><input className="inp" value={f.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Optional" /></Field>
      </div>
    </Modal>
  );
}

/* ============================ PARTY FORM ============================ */
function PartyForm({ editing, presetType, onClose }) {
  const push = useToast();
  const canSupplier = Hydor.can(Hydor.currentUser() ? Hydor.currentUser().role : Hydor.getState().meta.role, "seeSuppliers");
  const [f, setF] = React.useState(editing
    ? { name: editing.name, type: editing.type, phone: editing.phone, notes: editing.notes }
    : { name: "", type: canSupplier ? (presetType || "customer") : "customer", phone: "", notes: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const save = () => {
    if (!f.name.trim()) return push("Name is required.", "err");
    if (editing) { Hydor.updateParty(editing.id, f); push("Contact updated."); }
    else { Hydor.addParty(f); push(`${Hydor.cap(f.type)} added.`); }
    onClose();
  };
  return (
    <Modal title={editing ? "Edit contact" : (canSupplier ? "New contact" : "New customer")} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>{editing ? "Save changes" : (canSupplier ? "Add contact" : "Add customer")}</Btn>
    </>}>
      <div className="form-grid">
        {canSupplier && (
          <Field label="Type" span2>
            <div className="hx-seg" style={{ width: "100%", display: "flex" }}>
              <button className={f.type === "customer" ? "on" : ""} style={{ flex: 1 }} onClick={() => set("type", "customer")}>Customer</button>
              <button className={f.type === "supplier" ? "on" : ""} style={{ flex: 1 }} onClick={() => set("type", "supplier")}>Supplier</button>
            </div>
          </Field>
        )}
        <Field label="Name" span2><input className="inp" value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="Company or person" autoFocus /></Field>
        <Field label="Phone"><input className="inp" value={f.phone} onChange={(e) => set("phone", e.target.value)} placeholder="Optional" /></Field>
        <Field label="Notes"><input className="inp" value={f.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Optional" /></Field>
      </div>
    </Modal>
  );
}

Object.assign(window, { ProductForm, TxForm, CostForm, PartyForm, ProspectForm, todayStr });

/* ============================ CONTRACT PHOTO INPUT ============================ */
function ContractPhotoInput({ value, onChange }) {
  const fileRef = React.useRef();
  const [preview, setPreview] = React.useState(value || "");
  const compress = (file) => new Promise((res) => {
    const img = new window.Image(); img.onload = () => {
      const maxW = 900, scale = Math.min(1, maxW / img.width);
      const c = document.createElement("canvas"); c.width = Math.round(img.width * scale); c.height = Math.round(img.height * scale);
      c.getContext("2d").drawImage(img, 0, 0, c.width, c.height);
      res(c.toDataURL("image/jpeg", 0.65));
    }; img.src = URL.createObjectURL(file);
  });
  const pick = async (e) => {
    const file = e.target.files && e.target.files[0]; if (!file) return;
    const url = await compress(file);
    setPreview(url); onChange(url);
    e.target.value = "";
  };
  const clear = () => { setPreview(""); onChange(""); };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {preview ? (
        <div style={{ position: "relative", display: "inline-flex" }}>
          <img src={preview} alt="contract" style={{ maxWidth: "100%", maxHeight: 220, borderRadius: 10, objectFit: "cover", border: "1px solid var(--border)" }} />
          <button onClick={clear} style={{ position: "absolute", top: 6, right: 6, width: 26, height: 26, borderRadius: "50%", background: "rgba(0,0,0,.55)", border: "none", color: "#fff", cursor: "pointer", display: "grid", placeItems: "center" }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>
      ) : (
        <div style={{ height: 110, border: "2px dashed var(--border)", borderRadius: 10, display: "grid", placeItems: "center", background: "var(--bg-2)", color: "var(--text-3)", fontSize: 13 }}>No photo yet</div>
      )}
      <div style={{ display: "flex", gap: 8 }}>
        <input ref={fileRef} type="file" accept="image/*" capture="environment" style={{ display: "none" }} onChange={pick} />
        <Btn sm icon="camera" onClick={() => { if (fileRef.current) { fileRef.current.setAttribute("capture", "environment"); fileRef.current.click(); } }}>Camera (rear)</Btn>
        <Btn sm icon="upload" onClick={() => { if (fileRef.current) { fileRef.current.removeAttribute("capture"); fileRef.current.click(); } }}>Upload file</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { ContractPhotoInput });

/* ============================ DRAW TO SIGN CONTRACT ============================ */
function DrawToSignContract({ value, startDate, durationYears, customerName, company, onSign, onCancel }) {
  const isAr = window.HydorI18n && window.HydorI18n.getLang() === "ar";
  const locale = isAr ? "ar-JO" : "en-GB";
  const dir = isAr ? "rtl" : "ltr";
  const canvasRef = React.useRef(null);
  const drawingRef = React.useRef(false);
  const [scrolled, setScrolled] = React.useState(false);
  const [hasStroke, setHasStroke] = React.useState(false);
  const bodyRef = React.useRef(null);
  const today = new Date().toLocaleDateString(locale, { day: "2-digit", month: "long", year: "numeric" });
  const endDate = new Date(startDate || new Date()); endDate.setFullYear(endDate.getFullYear() + Number(durationYears || 1));
  const endStr = endDate.toLocaleDateString(locale, { day: "2-digit", month: "long", year: "numeric" });
  const startStr = new Date(startDate || Date.now()).toLocaleDateString(locale, { day: "2-digit", month: "long", year: "numeric" });
  const fmtVal = value ? Hydor.fmtMoney0(value) : "";

  React.useEffect(() => {
    const body = bodyRef.current; if (!body) return;
    const check = () => { if (body.scrollTop + body.clientHeight >= body.scrollHeight - 20) setScrolled(true); };
    body.addEventListener("scroll", check); check();
    return () => body.removeEventListener("scroll", check);
  }, []);

  function getPos(e, canvas) {
    const r = canvas.getBoundingClientRect();
    const src = e.touches ? e.touches[0] : e;
    return { x: (src.clientX - r.left) * (canvas.width / r.width), y: (src.clientY - r.top) * (canvas.height / r.height) };
  }
  function onPointerDown(e) {
    e.preventDefault(); const c = canvasRef.current; if (!c) return;
    drawingRef.current = true; const pos = getPos(e, c);
    const ctx = c.getContext("2d"); ctx.beginPath(); ctx.moveTo(pos.x, pos.y);
  }
  function onPointerMove(e) {
    e.preventDefault(); if (!drawingRef.current) return;
    const c = canvasRef.current; if (!c) return; const pos = getPos(e, c);
    const ctx = c.getContext("2d");
    ctx.strokeStyle = "#1a1f2e"; ctx.lineWidth = 2.5; ctx.lineCap = "round"; ctx.lineJoin = "round";
    ctx.lineTo(pos.x, pos.y); ctx.stroke(); setHasStroke(true);
  }
  function onPointerUp(e) { e.preventDefault(); drawingRef.current = false; }
  function clearSig() { const c = canvasRef.current; if (!c) return; c.getContext("2d").clearRect(0, 0, c.width, c.height); setHasStroke(false); }
  function confirm() {
    const c = canvasRef.current; if (!c) return;
    const out = document.createElement("canvas"); out.width = c.width; out.height = c.height;
    const ctx = out.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, out.width, out.height); ctx.drawImage(c, 0, 0);
    onSign(out.toDataURL("image/png", 0.9));
  }
  const ss = {
    section: { marginBottom: 20 },
    head: { fontSize: 13, fontWeight: 700, color: "#1a1f2e", marginBottom: 8, paddingBottom: 5, borderBottom: "1px solid #cdd5e0", textTransform: "uppercase", letterSpacing: ".06em" },
    para: { fontSize: 13, color: "#2a3444", lineHeight: 1.75, marginBottom: 6 },
    li: { fontSize: 12.5, color: "#2a3444", lineHeight: 1.75, marginBottom: 5 },
  };

  /* ---- Arabic content ---- */
  const arContent = (
    <div ref={bodyRef} dir="rtl" style={{ padding: "22px 26px", overflowY: "auto", maxHeight: 420, background: "#fff", fontFamily: "'IBM Plex Sans Arabic', 'Tajawal', sans-serif" }}>
      <div style={{ textAlign: "center", marginBottom: 20 }}>
        <div style={{ fontSize: 17, fontWeight: 700, color: "#1a1f2e" }}>عقد صيانة</div>
        <div style={{ fontSize: 12, color: "#6b7a96", marginTop: 3 }}>MAINTENANCE CONTRACT</div>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>أطراف العقد</div>
        <p style={ss.para}><b>الطرف الأول (مزوّد الخدمة):</b> {company || "هايدور لمعالجة المياه"}</p>
        <p style={ss.para}><b>الطرف الثاني (العميل):</b> {customerName || "—"}</p>
        <p style={ss.para}><b>تاريخ العقد:</b> {today} &nbsp;|&nbsp; <b>البداية:</b> {startStr} &nbsp;|&nbsp; <b>النهاية:</b> {endStr}</p>
        <p style={ss.para}><b>المدة:</b> {durationYears} {Number(durationYears) === 1 ? "سنة" : "سنوات"}</p>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>نطاق الخدمات</div>
        <p style={ss.para}>يلتزم الطرف الأول بتقديم خدمات الصيانة التالية لجهاز معالجة المياه المثبّت لدى الطرف الثاني:</p>
        <ol style={{ paddingRight: 20, paddingLeft: 0, margin: 0 }}>
          <li style={ss.li}><b>ثلاث زيارات صيانة دورية سنوياً</b> — بمعدّل زيارة كل أربعة أشهر.</li>
          <li style={ss.li}><b>الفحص الشامل</b> للجهاز والتحقق من سلامة جميع مكوّناته.</li>
          <li style={ss.li}><b>تنظيف الجهاز</b> وفحص جميع الوصلات والتأكد من عدم وجود تسرّبات.</li>
          <li style={ss.li}><b>قياس جودة المياه</b> ومراقبة أداء منظومة التنقية.</li>
          <li style={ss.li}><b>تغيير الفلاتر الدورية مرة سنوياً</b> وفق المواصفات المعتمدة للجهاز.</li>
          <li style={ss.li}><b>تقديم الدعم الفني والاستشارات</b> المتعلقة بتشغيل الجهاز وصيانته.</li>
        </ol>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>قيمة العقد</div>
        <p style={ss.para}><b>قيمة العقد السنوية: {fmtVal ? fmtVal + " دينار أردني فقط لا غير." : "حسب الاتفاق."}</b></p>
        <p style={ss.para}>يُستحق السداد عند توقيع العقد أو وفق ما يتفق عليه الطرفان.</p>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>الخصومات والمزايا الإضافية</div>
        <ul style={{ paddingRight: 20, paddingLeft: 0, margin: 0 }}>
          <li style={ss.li}><b>خصم 50% على قطع الغيار والمكونات:</b> بعد توقيع هذا العقد، يحق للطرف الثاني الحصول على أي قطعة غيار أو مكون إضافي للجهاز بخصم 50% من السعر المعتمد.</li>
          <li style={ss.li}><b>خصم 30% عند استبدال الجهاز أو إضافة منتج جديد:</b> في حال رغبة الطرف الثاني باستبدال الجهاز أو إضافة منتج آخر لنفس المنزل، يحق له الحصول على خصم 30% من السعر المعتمد.</li>
        </ul>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>الاستثناءات</div>
        <p style={ss.para}><b>لا يشمل</b> هذا العقد:</p>
        <ul style={{ paddingRight: 20, paddingLeft: 0, margin: 0 }}>
          <li style={ss.li}>استبدال خزان المياه أو المضخة أو أغشية التناضح العكسي أو أي قطعة تالفة بسبب الإساءة في الاستخدام أو عوامل خارجية.</li>
          <li style={ss.li}>أي أعمال إضافية أو قطع غيار غير منصوص عليها في هذا العقد، وتُحسب بعد موافقة الطرف الثاني.</li>
        </ul>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>التزامات الطرف الثاني</div>
        <ul style={{ paddingRight: 20, paddingLeft: 0, margin: 0 }}>
          <li style={ss.li}>السماح لفني الصيانة بالوصول إلى الجهاز في المواعيد المحددة.</li>
          <li style={ss.li}>الحفاظ على الجهاز واستخدامه وفق التعليمات التشغيلية الموصى بها.</li>
        </ul>
      </div>
      <div style={{ padding: "10px 14px", background: "#f4f6fa", borderRadius: 10, fontSize: 12, color: "#6b7a96", lineHeight: 1.65 }}>
        بالتوقيع أدناه، يُقرّ الطرف الثاني بأنه قرأ جميع بنود وشروط عقد الصيانة هذا وفهمها ووافق عليها.
      </div>
    </div>
  );

  /* ---- English content ---- */
  const enContent = (
    <div ref={bodyRef} dir="ltr" style={{ padding: "22px 26px", overflowY: "auto", maxHeight: 420, background: "#fff" }}>
      <div style={{ textAlign: "center", marginBottom: 20 }}>
        <div style={{ fontSize: 17, fontWeight: 700, color: "#1a1f2e" }}>MAINTENANCE CONTRACT</div>
        <div style={{ fontSize: 12, color: "#6b7a96", marginTop: 3 }}>عقد صيانة</div>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>Contract Parties</div>
        <p style={ss.para}><b>First Party (Service Provider):</b> {company || "HYDOR Water Treatment"}</p>
        <p style={ss.para}><b>Second Party (Customer):</b> {customerName || "—"}</p>
        <p style={ss.para}><b>Contract Date:</b> {today} &nbsp;|&nbsp; <b>Start:</b> {startStr} &nbsp;|&nbsp; <b>End:</b> {endStr}</p>
        <p style={ss.para}><b>Duration:</b> {durationYears} year{Number(durationYears) !== 1 ? "s" : ""}</p>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>Scope of Services</div>
        <p style={ss.para}>The First Party agrees to provide the following maintenance services for the water treatment device:</p>
        <ol style={{ paddingLeft: 20, margin: 0 }}>
          <li style={ss.li}><b>Three periodic maintenance visits annually</b> — one visit every four months.</li>
          <li style={ss.li}><b>Comprehensive inspection</b> of the device and verification of the integrity of all its parts.</li>
          <li style={ss.li}><b>Cleaning the device</b>, checking all connections, and ensuring there are no leaks.</li>
          <li style={ss.li}><b>Measuring water quality</b> and monitoring the purification system's performance.</li>
          <li style={ss.li}><b>Replacing the periodic filters once a year</b> according to the device's approved specifications.</li>
          <li style={ss.li}><b>Providing technical support and consultations</b> related to operating and maintaining the device.</li>
        </ol>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>Contract Value</div>
        <p style={ss.para}><b>Annual contract value: {fmtVal ? fmtVal + " Jordanian Dinars only." : "As agreed."}</b></p>
        <p style={ss.para}>Payment is due upon signing the contract, or as agreed upon by both parties.</p>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>Discounts &amp; Additional Benefits</div>
        <ul style={{ paddingLeft: 20, margin: 0 }}>
          <li style={ss.li}><b>50% discount on spare parts &amp; components:</b> After signing this contract, any additional part or component added to the device will be provided at a 50% discount off the standard price.</li>
          <li style={ss.li}><b>30% discount on device replacement or additional products:</b> If you wish to replace the device or add another product for the same household, you will receive a 30% discount off the standard price.</li>
        </ul>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>Exclusions</div>
        <p style={ss.para}>This contract does <b>not</b> include:</p>
        <ul style={{ paddingLeft: 20, margin: 0 }}>
          <li style={ss.li}>Replacement of the water tank, pump, RO membranes, or any part damaged due to misuse or external factors.</li>
          <li style={ss.li}>Any additional work or spare parts not stipulated in this contract, which will be calculated after the Second Party's approval.</li>
        </ul>
      </div>
      <div style={ss.section}>
        <div style={ss.head}>Second Party Obligations</div>
        <ul style={{ paddingLeft: 20, margin: 0 }}>
          <li style={ss.li}>To allow the maintenance technician access to the device at the scheduled times.</li>
          <li style={ss.li}>To maintain and use the device according to the recommended operating instructions.</li>
        </ul>
      </div>
      <div style={{ padding: "10px 14px", background: "#f4f6fa", borderRadius: 10, fontSize: 12, color: "#6b7a96", lineHeight: 1.55 }}>
        By signing below, the Second Party acknowledges having read, understood, and agreed to all terms and conditions of this maintenance contract.
      </div>
    </div>
  );

  const scrollMsg = isAr ? "يرجى التمرير حتى نهاية العقد قبل التوقيع." : "Please scroll to the bottom of the contract before signing.";
  const sigLabel = isAr ? ("توقيع العميل — " + (customerName || "—")) : ("Customer Signature — " + (customerName || "—"));
  const sigHint = isAr ? "ارسم توقيعك باستخدام إصبعك أو القلم أو الفأرة" : "Draw your signature using your finger, stylus, or mouse";
  const clearLbl = isAr ? "مسح" : "Clear";
  const cancelLbl = isAr ? "إلغاء" : "Cancel";
  const confirmLbl = isAr ? "✓ توقيع وتأكيد العقد" : "✓ Sign & confirm";
  const scrollHint = isAr ? "مرّر العقد قبل التوقيع" : "Scroll the contract before signing";
  const drawHint = isAr ? "ارسم توقيعك أعلاه" : "Draw your signature above";

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 2000, background: "rgba(0,0,0,.72)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "20px 12px", overflowY: "auto" }}>
      <div dir={dir} style={{ background: "#fff", borderRadius: 18, width: "100%", maxWidth: 680, display: "flex", flexDirection: "column", boxShadow: "0 24px 80px rgba(0,0,0,.45)", overflow: "hidden" }}>
        {/* header */}
        <div style={{ background: "#0a0f1a", padding: "16px 22px", display: "flex", alignItems: "center", gap: 14 }}>
          <svg width="28" height="34" viewBox="0 0 32 38" fill="none"><defs><linearGradient id="cdgB" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#5fd0ff"/><stop offset=".5" stopColor="#3b8cff"/><stop offset="1" stopColor="#2f6fe0"/></linearGradient></defs><path d="M16 2C16 2 30 16 30 25A14 14 0 1 1 2 25C2 16 16 2 16 2Z" fill="url(#cdgB)"/><ellipse cx="12" cy="22" rx="5" ry="7" fill="rgba(255,255,255,.45)"/></svg>
          <div>
            <div style={{ fontFamily: "'IBM Plex Sans','Tajawal',sans-serif", fontWeight: 700, fontSize: 17, letterSpacing: ".12em", color: "#e9eef7" }}>{isAr ? "هايدور" : "HYDOR"}</div>
            <div style={{ fontSize: 10.5, color: "#6b7a96" }}>{isAr ? "معالجة المياه — عقد صيانة" : "Water Treatment — Maintenance Contract"}</div>
          </div>
          <button onClick={onCancel} style={{ marginInlineStart: "auto", background: "rgba(255,255,255,.1)", border: "none", borderRadius: 8, width: 30, height: 30, cursor: "pointer", display: "grid", placeItems: "center", color: "#fff" }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>

        {/* scroll guard */}
        {!scrolled && (
          <div dir={dir} style={{ background: "#fff8ed", borderBottom: "1px solid #ffe4b3", padding: "8px 20px", fontSize: 12, color: "#7a4800", display: "flex", alignItems: "center", gap: 7 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
            {scrollMsg}
          </div>
        )}

        {/* contract body */}
        {isAr ? arContent : enContent}

        {/* signature pad */}
        <div dir={dir} style={{ background: "#f7f9fc", borderTop: "1px solid #dce3ef", padding: "16px 22px 22px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: "#1a1f2e" }}>{sigLabel}</div>
              <div style={{ fontSize: 11.5, color: "#6b7a96", marginTop: 2 }}>{sigHint}</div>
            </div>
            <button onClick={clearSig} style={{ background: "none", border: "1px solid #cdd5e0", borderRadius: 8, padding: "5px 12px", cursor: "pointer", fontSize: 12, color: "#6b7a96", fontFamily: "inherit" }}>{clearLbl}</button>
          </div>
          <canvas ref={canvasRef} width={640} height={130}
            style={{ width: "100%", height: 130, background: "#fff", border: scrolled ? "2px solid #3b8cff" : "2px dashed #cdd5e0", borderRadius: 12, display: "block", cursor: "crosshair", touchAction: "none" }}
            onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerLeave={onPointerUp} />
          <div style={{ display: "flex", gap: 10, marginTop: 14, justifyContent: "flex-end", alignItems: "center", flexWrap: "wrap" }}>
            {!scrolled && <span style={{ fontSize: 11.5, color: "#b07800", marginInlineEnd: "auto" }}>{scrollHint}</span>}
            {scrolled && !hasStroke && <span style={{ fontSize: 11.5, color: "#6b7a96", marginInlineEnd: "auto" }}>{drawHint}</span>}
            <button onClick={onCancel} style={{ background: "none", border: "1px solid #cdd5e0", borderRadius: 10, padding: "9px 18px", cursor: "pointer", fontSize: 13, fontWeight: 600, color: "#6b7a96", fontFamily: "inherit" }}>{cancelLbl}</button>
            <button onClick={confirm} disabled={!scrolled || !hasStroke}
              style={{ background: scrolled && hasStroke ? "#3b8cff" : "#cdd5e0", border: "none", borderRadius: 10, padding: "9px 22px", cursor: scrolled && hasStroke ? "pointer" : "default", fontSize: 13, fontWeight: 700, color: scrolled && hasStroke ? "#fff" : "#8a9bb0", fontFamily: "inherit", transition: ".15s" }}>
              {confirmLbl}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { DrawToSignContract });

/* ============================ PROSPECT FORM ============================ */
function ProspectForm({ editing, onClose }) {
  const push = useToast();
  const s = Hydor.getState();
  const [f, setF] = React.useState(editing
    ? { name: editing.name, segment: editing.segment, location: editing.location, phone: editing.phone, website: editing.website, source: editing.source, status: editing.status, assignedTo: editing.assignedTo, campaign: editing.campaign, estValue: editing.estValue, notes: editing.notes }
    : { name: "", segment: "", location: "", phone: "", website: "", source: "manual", status: "new", assignedTo: "", campaign: "", estValue: "", notes: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const save = () => {
    if (!f.name.trim()) return push("Prospect name is required.", "err");
    if (editing) { Hydor.updateProspect(editing.id, f); push("Prospect updated."); }
    else { Hydor.addProspect(f); push("Prospect added."); }
    onClose();
  };
  const reps = s.users.filter((u) => u.active && (u.department === "Customer Success" || u.department === "Sales"));
  return (
    <Modal title={editing ? "Edit prospect" : "New prospect"} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>{editing ? "Save changes" : "Add prospect"}</Btn>
    </>}>
      <div className="form-grid">
        <Field label="Business name" span2><input className="inp" value={f.name} onChange={(e) => set("name", e.target.value)} placeholder="e.g. Le Royal Residences" autoFocus /></Field>
        <Field label="Segment" hint="Type of business"><input className="inp" value={f.segment} onChange={(e) => set("segment", e.target.value)} placeholder="Hospitality, pools, residential…" /></Field>
        <Field label="Location"><input className="inp" value={f.location} onChange={(e) => set("location", e.target.value)} placeholder="Amman, Abdoun" /></Field>
        <Field label="Phone"><input className="inp" value={f.phone} onChange={(e) => set("phone", e.target.value)} placeholder="Optional" /></Field>
        <Field label="Website"><input className="inp" value={f.website} onChange={(e) => set("website", e.target.value)} placeholder="Optional" /></Field>
        <Field label="Source">
          <select className="sel" value={f.source} onChange={(e) => set("source", e.target.value)}>
            <option value="manual">Added manually</option>
            <option value="maps">Google Maps</option>
            <option value="referral">Referral</option>
            <option value="campaign">Marketing campaign</option>
            <option value="website">Website enquiry</option>
          </select>
        </Field>
        <Field label="Stage">
          <select className="sel" value={f.status} onChange={(e) => set("status", e.target.value)}>
            {["new", "contacted", "qualified", "won", "lost"].map((x) => <option key={x} value={x}>{Hydor.cap(x)}</option>)}
          </select>
        </Field>
        <Field label="Assigned to">
          <select className="sel" value={f.assignedTo} onChange={(e) => set("assignedTo", e.target.value)}>
            <option value="">— unassigned —</option>
            {reps.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
          </select>
        </Field>
        <Field label="Estimated value"><Affix affix="JOD"><input className="inp num" type="number" value={f.estValue} onChange={(e) => set("estValue", e.target.value)} style={{ paddingRight: 44 }} placeholder="0" /></Affix></Field>
        <Field label="Campaign"><input className="inp" value={f.campaign} onChange={(e) => set("campaign", e.target.value)} placeholder="Optional" /></Field>
        <Field label="Notes" span2><input className="inp" value={f.notes} onChange={(e) => set("notes", e.target.value)} placeholder="What's the opportunity?" /></Field>
      </div>
    </Modal>
  );
}

Object.assign(window, { ProspectForm });
