// ADM-PROC-14 · Digital agreement (AMOMS Module 1)
// Admin Web · Procurement Manager (sign) / Farmer (acknowledge) · P1 · 1440×900
// Components: C-108 Modal · C-001 Button · C-009 Checkbox · Custom signature canvas
// Registered as window.Pages.agreement

const Ic14 = window.Icons;
const ORDER_14 = { id: "SO-2026-0413", po: "PO-2026-0042", req: "PR-2026-0184", product: "Hass", qty: 28000 };
const PARTIES = ["Mary Wairimu", "Esther Njeri", "Grace Wambui", "+4 farmers"];

const SignaturePad14 = ({ onSigned, disabled }) => {
  const ref = useRef(null);
  const drawing = useRef(false);
  const has = useRef(false);
  const pos = (e) => { const c = ref.current.getBoundingClientRect(); const t = e.touches ? e.touches[0] : e; return [(t.clientX) - c.left, (t.clientY) - c.top]; };
  useEffect(() => { const cv = ref.current; if (!cv) return; cv.width = cv.offsetWidth; cv.height = cv.offsetHeight; const ctx = cv.getContext("2d"); ctx.strokeStyle = "#1f4d2e"; ctx.lineWidth = 2.2; ctx.lineCap = "round"; }, [disabled]);
  if (disabled) return null;
  const start = (e) => { e.preventDefault(); drawing.current = true; const ctx = ref.current.getContext("2d"); const [x, y] = pos(e); ctx.beginPath(); ctx.moveTo(x, y); };
  const move = (e) => { if (!drawing.current) return; e.preventDefault(); const ctx = ref.current.getContext("2d"); const [x, y] = pos(e); ctx.lineTo(x, y); ctx.stroke(); if (!has.current) { has.current = true; onSigned(true); } };
  const end = () => { drawing.current = false; };
  const clear = () => { const cv = ref.current; cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); has.current = false; onSigned(false); };
  return (
    <div>
      <canvas ref={ref} className="ag-sigpad" onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end} onTouchStart={start} onTouchMove={move} onTouchEnd={end} />
      <div className="row" style={{ justifyContent: "space-between", marginTop: 6 }}>
        <span className="muted" style={{ fontSize: 11 }}>Sign with mouse or touch</span>
        <Button size="xs" variant="ghost" icon={Ic14.X} onClick={clear}>Clear</Button>
      </div>
    </div>
  );
};

const TLItem = ({ status, icon: I, step, meta, last }) => (
  <div style={{ display: "flex", gap: 12 }}>
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
      <span className={`ag-tl-dot ${status}`}>{status === "done" ? <Ic14.Check size={13} /> : <I size={12} />}</span>
      {!last && <span className="ag-tl-line" />}
    </div>
    <div style={{ paddingBottom: last ? 0 : 14 }}>
      <div className="ag-tl-step">{step}</div>
      <div className="ag-tl-meta">{meta}</div>
    </div>
  </div>
);

const DigitalAgreement = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = (tweaks && tweaks.agreementState) || "awaiting1";

  const [signed, setSigned] = useState(false);
  const [agree, setAgree] = useState(false);
  const [typed, setTyped] = useState("");
  useEffect(() => { setSigned(false); setAgree(false); setTyped(""); }, [state]);

  const managerDone = state !== "awaiting1";
  const farmerDone = state === "both";
  const declined = state === "declined";
  const bothSigned = state === "both";

  // Who is signing now
  const signerRole = state === "awaiting1" ? "Plant Manager" : "Farmer";
  const signerName = state === "awaiting1" ? "Caroline Wanjala" : "Mary Wairimu (lead farmer)";
  const canSign = !managerDone || (state === "awaiting2");
  const ready = (signed || typed.trim()) && agree;

  const onSign = () => {
    if (!ready) { toast({ title: "Sign and tick the agreement box first", tone: "danger" }); return; }
    toast({ title: `Signed by ${signerName}`, desc: state === "awaiting1" ? "Sent to farmers for acknowledgment." : "Agreement complete." });
    go("ADM-PROC-13.html");
  };

  return (
    <div className="page">
      <div className="ag-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-13.html")}><Ic14.ChevronLeft size={18} /></button>
        <div style={{ flex: 1 }}>
          <h1 className="ag-title">Supply agreement — <span className="mono" style={{ fontWeight: 600 }}>{ORDER_14.id}</span></h1>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{ORDER_14.po} · {ORDER_14.product} · {ORDER_14.qty.toLocaleString("en-US")} kg</div>
        </div>
        <div className="ag-head-actions">
          {(bothSigned) && <Button variant="outline" icon={Ic14.Download} onClick={() => toast({ title: "Downloading signed PDF" })}>Download PDF</Button>}
        </div>
      </div>

      {declined && (
        <div className="alert alert-soil" style={{ marginBottom: 16 }}>
          <span className="alert-icon"><Ic14.XCircle size={16} /></span>
          <div className="alert-body"><div className="alert-title">Agreement declined by farmer</div><div className="alert-desc">The order returns to Confirmed without a digital agreement. A paper fallback can be used.</div></div>
        </div>
      )}

      <div className="ag-grid">
        {/* PDF preview */}
        <div className="ag-pdf-wrap">
          <div className="ag-doc">
            <div className="ag-doc-mark"><span className="m"><Ic14.Leaf size={18} /></span><div><h1>Avocado Supply Agreement</h1><div style={{ fontSize: 11, color: "#555" }}>AMOMS Ltd · Murang'a Processing Plant</div></div></div>
            <div className="ag-doc-meta">
              <div><b>Agreement no.</b> AG-2026-0042</div><div><b>Order</b> {ORDER_14.id}</div>
              <div><b>Requirement</b> {ORDER_14.req}</div><div><b>Date</b> 12 May 2026</div>
            </div>
            <h2>1 · Parties</h2>
            <p>This agreement is made between AMOMS Ltd ("the Buyer") and the supplying farmers listed in Schedule A ("the Suppliers"), for the supply of fresh avocados to the Buyer's Murang'a plant.</p>
            <h2>2 · Goods &amp; quantity</h2>
            <p>The Suppliers shall deliver a combined {ORDER_14.qty.toLocaleString("en-US")} kg of {ORDER_14.product} avocados, export grade, minimum 200 g per fruit and dry matter at or above 24%, within the agreed delivery window.</p>
            <h2>3 · Price &amp; payment</h2>
            <p>The Buyer shall pay the agreed rate per kilogram on each Supplier's accepted offer, payable on delivery after weighbridge and quality confirmation.</p>
            <h2>Schedule A · Suppliers</h2>
            <table>
              <thead><tr><th>Farmer</th><th>Qty (kg)</th><th>Rate</th></tr></thead>
              <tbody>
                <tr><td>Mary Wairimu</td><td>6,200</td><td>KSh 92</td></tr>
                <tr><td>Esther Njeri</td><td>5,400</td><td>KSh 94</td></tr>
                <tr><td>Grace Wambui</td><td>4,500</td><td>KSh 96</td></tr>
                <tr><td>+4 more</td><td>11,900</td><td>—</td></tr>
              </tbody>
            </table>
            <div className="ag-sigline">
              <div className="ag-sigbox"><div className="ln">{managerDone ? "Caroline Wanjala" : ""}</div><div className="lbl">Buyer · Plant Manager{managerDone ? " · signed 12 May" : ""}</div></div>
              <div className="ag-sigbox"><div className="ln">{farmerDone ? "Mary Wairimu" : ""}</div><div className="lbl">Supplier · Lead farmer{farmerDone ? " · signed 12 May" : ""}</div></div>
            </div>
          </div>
        </div>

        {/* Signature panel + timeline */}
        <div className="ag-side">
          <Card style={{ marginBottom: 16 }}>
            <CardHead title={bothSigned ? "Fully signed" : declined ? "Declined" : "Your signature"} desc={bothSigned ? "Both parties have signed." : declined ? "Awaiting resolution." : `${signerName} · ${signerRole}`} />
            <div className="card-body" style={{ paddingTop: 2 }}>
              {bothSigned ? (
                <div className="proc-inline-empty" style={{ flexDirection: "column", padding: "20px 8px", gap: 8 }}>
                  <span style={{ width: 44, height: 44, borderRadius: 22, background: "var(--success-soft)", color: "var(--success)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Ic14.CheckCircle size={22} /></span>
                  <div style={{ fontSize: 13, color: "var(--foreground)", textAlign: "center" }}>Agreement is binding in-system. Download the signed PDF above.</div>
                </div>
              ) : declined ? (
                <div className="muted" style={{ fontSize: 13 }}>No signature required — the agreement was declined.</div>
              ) : (
                <>
                  <SignaturePad14 onSigned={setSigned} disabled={false} />
                  <div className="field" style={{ marginTop: 12 }}>
                    <label className="label">Or type your full name</label>
                    <input className="input" placeholder="Type to sign" value={typed} onChange={(e) => setTyped(e.target.value)} />
                  </div>
                  <label className="row" style={{ alignItems: "flex-start", gap: 8, marginTop: 12, cursor: "pointer" }} onClick={() => setAgree(a => !a)}>
                    <span className={`proc-check${agree ? " on" : ""}`} style={{ marginTop: 1 }}>{agree && <Ic14.Check size={11} />}</span>
                    <span style={{ fontSize: 12.5, lineHeight: 1.4 }}>I have read and agree to the terms of this supply agreement.</span>
                  </label>
                  <div className="row" style={{ marginTop: 16 }}>
                    <Button variant="outline" icon={Ic14.XCircle} onClick={() => { toast({ title: "Agreement declined" }); go("ADM-PROC-13.html"); }}>Decline</Button>
                    <Button variant="primary" icon={Ic14.Check} disabled={!ready} onClick={onSign} style={{ flex: 1 }}>Sign &amp; continue</Button>
                  </div>
                </>
              )}
            </div>
          </Card>

          <Card>
            <CardHead title="Signing progress" />
            <div className="card-body" style={{ paddingTop: 2 }}>
              <div className="ag-tl">
                <TLItem status={managerDone ? "done" : "active"} icon={Ic14.User} step="Plant Manager signs" meta={managerDone ? "Caroline Wanjala · 12 May 09:40" : "Awaiting signature"} />
                <TLItem status={farmerDone ? "done" : declined ? "active" : managerDone ? "active" : ""} icon={Ic14.User} step="Lead farmer acknowledges" meta={farmerDone ? "Mary Wairimu · 12 May 11:05" : declined ? "Declined" : managerDone ? "Notification sent" : "Pending manager"} />
                <TLItem status={bothSigned ? "done" : ""} icon={Ic14.File} step="Agreement complete" meta={bothSigned ? "Signed PDF generated" : "Pending both signatures"} last />
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { agreement: DigitalAgreement });
