/* forms-waste.jsx — Waste reports. No money, no approval (submitted + emailed like WGR).
   One dashboard tile → chooser → two forms:
     IWR — Ingredient waste      (item · qty · weight · photo · reason)
     PWR — Finished-product waste (item · qty · photo · reason)
   Both: reason is REQUIRED per line; the ingredient picker shows ALL ingredients
   (including the 'other' / waste-only tag), the product picker reads the new
   per-company Finished-products list. */

/* ---------- finished-product picker (PWR) ---------- */
function ProductPicker({ company, lang, value, onChange }) {
  const options = (company.products || []).filter((p) => !p.archived).map((p) => ({
    value: p.id, label: p.th + " · " + p.en, sub: p.unit || "", icon: "basket",
  }));
  return (
    <PickerField value={value || ""} options={options} onChange={onChange}
      placeholder={window.t(lang, "selectProduct")} title={window.t(lang, "selectProduct")} lang={lang} />
  );
}

/* ---------- one item line (guided steps) ---------- */
function WasteItemSheet({ kind, company, lang, initial, onSave, onClose, onDelete }) {
  const isIWR = kind === "IWR";
  const [it, setIt] = useState(initial || (isIWR
    ? { itemId: "", qty: "", weight: "", photo: null, reason: "" }
    : { productId: "", qty: "", photo: null, reason: "" }));
  const [step, setStep] = useState(0);
  const set = (k, v) => setIt((p) => ({ ...p, [k]: v }));

  const chosen = isIWR
    ? company.ingredients.find((x) => x.id === it.itemId)
    : (company.products || []).find((x) => x.id === it.productId);
  const idVal = isIWR ? it.itemId : it.productId;

  // step order differs: IWR has a weight step, PWR does not.
  // Photo is encouraged but NOT blocking (same as GRN/WGR, and the app is camera-only
  // so a hard requirement could lock staff out). Reason IS required.
  const STEPS = isIWR ? ["item", "qty", "weight", "photo", "reason"] : ["item", "qty", "photo", "reason"];
  const canStep = {};
  STEPS.forEach((s, i) => {
    canStep[i] = s === "item" ? !!idVal
      : s === "qty" ? !!(it.qty && it.qty.trim())
      : s === "weight" ? (it.weight !== "" && it.weight != null && !isNaN(Number(it.weight)))
      : s === "reason" ? !!(it.reason && it.reason.trim())
      : true; // photo step is optional
  });
  const complete = STEPS.every((_, i) => canStep[i]);

  function finish() {
    onSave({
      ...it,
      weight: isIWR ? Number(parseFloat(it.weight).toFixed(2)) : null,
      desc: chosen ? chosen.th : "",
      en: chosen ? chosen.en : "",
      unit: chosen ? (chosen.unit || "") : "",
      reason: (it.reason || "").trim(),
    });
  }

  const fItem = (
    <Field label={window.t(lang, "itemDesc")} required>
      {isIWR
        ? <IngredientPicker company={company} lang={lang} value={it.itemId} onChange={(v) => set("itemId", v)} icon="trash" />
        : <ProductPicker company={company} lang={lang} value={it.productId} onChange={(v) => set("productId", v)} />}
    </Field>
  );
  const fQty = (
    <Field label={window.t(lang, "qty")} required hint={window.t(lang, "qtyHint")}>
      <input className="control" value={it.qty} placeholder="2 เข่ง / 3 จาน" onChange={(e) => set("qty", e.target.value)} />
    </Field>
  );
  const fWeight = (
    <Field label={window.t(lang, "weight")} required>
      <div className="input-suffix">
        <input className="control big-num" type="number" inputMode="decimal" value={it.weight}
          placeholder="0.00" step="0.01" onChange={(e) => set("weight", e.target.value)} style={{ paddingRight: 64 }} />
        <span className="suffix">{chosen && chosen.unit ? chosen.unit.split("/")[0].trim() : window.t(lang, "unit")}</span>
      </div>
    </Field>
  );
  const fPhoto = (
    <PhotoCapture lang={lang} label={window.t(lang, "photoPerItem")} value={it.photo}
      hint={window.t(lang, "photoEvidence")} onChange={(v) => set("photo", v)} />
  );
  const fReason = (
    <Field label={window.t(lang, "wasteReason")} required hint={window.t(lang, "wasteReasonHint")}>
      <textarea className="control" rows={3} value={it.reason}
        placeholder={window.t(lang, "wasteReasonPlaceholder")}
        onChange={(e) => set("reason", e.target.value)}
        style={{ resize: "vertical", fontFamily: "inherit" }} />
    </Field>
  );
  const fieldByName = { item: fItem, qty: fQty, weight: fWeight, photo: fPhoto, reason: fReason };

  return (
    <Sheet onClose={onClose}>
      <div className="stack-lg">
        <div className="stack gap-sm">
          <Steps total={STEPS.length} current={step} />
          <div className="hint mono">{window.t(lang, "step")} {step + 1} {window.t(lang, "of")} {STEPS.length}</div>
        </div>
        <div className="slide-in" key={step} style={{ minHeight: 120 }}>
          {fieldByName[STEPS[step]]}
        </div>
        <div className="btn-row">
          {step > 0
            ? <Button variant="ghost" onClick={() => setStep(step - 1)} icon="back">{window.t(lang, "back")}</Button>
            : onDelete && <Button variant="danger" onClick={onDelete} icon="trash">{window.t(lang, "remove")}</Button>}
          {step < STEPS.length - 1
            ? <Button onClick={() => setStep(step + 1)} disabled={!canStep[step]} icon="fwd">{window.t(lang, "next")}</Button>
            : <Button onClick={finish} disabled={!complete} icon="check">{window.t(lang, "done")}</Button>}
        </div>
      </div>
    </Sheet>
  );
}

/* ---------- the form (shared by IWR and PWR via `kind`) ---------- */
function WasteForm({ data, session, lang, kind, onLang, nav, onReview }) {
  const company = data.companies.find((c) => c.id === session.companyId);
  const [items, setItems] = useState([]);
  const [editing, setEditing] = useState(null);
  const isIWR = kind === "IWR";
  const docNo = window.nextDocNo(company, kind).no;
  const backRoute = "create-waste";

  function saveItem(item) {
    setItems((p) => {
      if (editing === "new") return [...p, item];
      const next = p.slice(); next[editing.idx] = item; return next;
    });
    setEditing(null);
  }
  function removeItem() {
    setItems((p) => p.filter((_, i) => i !== editing.idx)); setEditing(null);
  }

  const title = window.t(lang, isIWR ? "iwrTitle" : "pwrTitle");
  const header = window.t(lang, isIWR ? "iwrHeader" : "pwrHeader");
  const canReview = items.length > 0;

  return (
    <div className="app">
      <TopBar title={title} sub={header} onBack={() => nav(backRoute)} lang={lang} onLang={onLang} />
      <div className="scroll stack-lg">
        <div className="card">
          <div className="between">
            <div className="eyebrow">{window.t(lang, "docNo")}</div>
            <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: "var(--accent)" }}>{docNo}</span>
          </div>
          <hr className="hr" />
          <div style={{ fontWeight: 600, fontSize: 14 }}>{company.name.split("·")[0].trim()}</div>
          <div className="hint" style={{ marginTop: 3, textWrap: "pretty" }}>{company.address}</div>
          <div className="hint mono" style={{ marginTop: 4 }}>TAX {company.taxId} · {company.branch}</div>
        </div>

        <div className="stack">
          <div className="between">
            <div className="eyebrow">{window.t(lang, "items")} ({items.length}/20)</div>
          </div>
          {items.length === 0 && <div className="card center muted" style={{ padding: 26, textWrap: "pretty" }}>{window.t(lang, "emptyItems")}</div>}
          {items.map((it, i) => (
            <button key={i} className="row" style={{ textAlign: "left", alignItems: "flex-start" }} onClick={() => setEditing({ idx: i })}>
              <span className="ix" style={{ marginTop: 2 }}>{i + 1}</span>
              {it.photo && <img src={it.photo.dataUrl} alt="" style={{ width: 46, height: 46, borderRadius: 9, objectFit: "cover", flex: "0 0 auto" }} />}
              <div className="grow">
                <div style={{ fontWeight: 600 }}>{it.desc}</div>
                <div className="hint mono" style={{ marginTop: 3 }}>
                  {it.qty}{isIWR && it.weight != null && it.weight !== "" ? ` · ${Number(it.weight).toFixed(2)} ${(it.unit || "").split("/")[0].trim()}` : ""}
                </div>
                <div className="hint" style={{ marginTop: 2, color: "var(--text-2)", textWrap: "pretty" }}>
                  <Icon name="warn" size={12} style={{ verticalAlign: "-1px", color: "var(--warn)" }} /> {it.reason}
                </div>
              </div>
              <Icon name="edit" size={16} style={{ color: "var(--muted)", marginTop: 2 }} />
            </button>
          ))}
          {items.length < 20 && (
            <button className="btn btn-ghost" onClick={() => setEditing("new")} style={{ borderStyle: "dashed" }}>
              <Icon name="plus" size={18} />{window.t(lang, "addItem")}
            </button>
          )}
        </div>
      </div>

      <div className="action-bar">
        <Button onClick={() => onReview({ type: kind, companyId: company.id, docNo, items })}
          disabled={!canReview} icon="fwd">{window.t(lang, "next")}</Button>
      </div>

      {editing && (
        <WasteItemSheet kind={kind} company={company} lang={lang}
          initial={editing === "new" ? null : items[editing.idx]}
          onSave={saveItem} onClose={() => setEditing(null)}
          onDelete={editing !== "new" ? removeItem : null} />
      )}
    </div>
  );
}

/* ---------- chooser: which kind of waste? ---------- */
function WasteChooser({ lang, onLang, nav }) {
  return (
    <div className="app">
      <TopBar title={window.t(lang, "wasteTitle")} sub={window.t(lang, "wasteChooseType")}
        onBack={() => nav("home")} lang={lang} onLang={onLang} />
      <div className="scroll stack-lg">
        <p className="lead" style={{ textWrap: "pretty" }}>{window.t(lang, "wasteChooseType")}</p>
        <div className="stack">
          <button className="tap-card" onClick={() => nav("create-iwr")}>
            <div className="tile-icon"><Icon name="basket" size={24} /></div>
            <div className="grow" style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 16 }}>{window.t(lang, "iwrTitle")}</div>
              <div className="hint" style={{ marginTop: 3, textWrap: "pretty" }}>{window.t(lang, "iwrDesc")}</div>
            </div>
            <Icon name="fwd" size={20} style={{ color: "var(--muted)", flex: "0 0 auto" }} />
          </button>
          <button className="tap-card" onClick={() => nav("create-pwr")}>
            <div className="tile-icon"><Icon name="receipt" size={24} /></div>
            <div className="grow" style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 16 }}>{window.t(lang, "pwrTitle")}</div>
              <div className="hint" style={{ marginTop: 3, textWrap: "pretty" }}>{window.t(lang, "pwrDesc")}</div>
            </div>
            <Icon name="fwd" size={20} style={{ color: "var(--muted)", flex: "0 0 auto" }} />
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WasteForm, WasteChooser, ProductPicker });
