// FRM-PROC-10 · Digital agreement sign — read → sign → confirm
const SignaturePad = ({ onChange }) => {
  const canvasRef = useRef(null);
  const drawing = useRef(false);
  const last = useRef(null);

  useEffect(() => {
    const cv = canvasRef.current;
    if (!cv) return;
    const rect = cv.getBoundingClientRect();
    cv.width = rect.width * 2; cv.height = rect.height * 2;
    const ctx = cv.getContext("2d");
    ctx.scale(2, 2);
    ctx.lineWidth = 2.4; ctx.lineCap = "round"; ctx.lineJoin = "round";
    ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue("--foreground") || "#222";

    const pos = (e) => {
      const r = cv.getBoundingClientRect();
      const p = e.touches ? e.touches[0] : e;
      return { x: p.clientX - r.left, y: p.clientY - r.top };
    };
    const start = (e) => { e.preventDefault(); drawing.current = true; last.current = pos(e); };
    const move = (e) => {
      if (!drawing.current) return;
      e.preventDefault();
      const p = pos(e);
      ctx.beginPath(); ctx.moveTo(last.current.x, last.current.y); ctx.lineTo(p.x, p.y); ctx.stroke();
      last.current = p; onChange?.(true);
    };
    const end = () => { drawing.current = false; };

    cv.addEventListener("mousedown", start); cv.addEventListener("mousemove", move);
    window.addEventListener("mouseup", end);
    cv.addEventListener("touchstart", start, { passive: false }); cv.addEventListener("touchmove", move, { passive: false });
    window.addEventListener("touchend", end);
    cv._clear = () => { ctx.clearRect(0, 0, cv.width, cv.height); onChange?.(false); };
    return () => {
      cv.removeEventListener("mousedown", start); cv.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", end);
      cv.removeEventListener("touchstart", start); cv.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", end);
    };
  }, []);

  return (
    <div className="fm-sign-pad">
      <canvas ref={canvasRef}/>
      <div className="fm-sign-baseline"/>
      <div className="fm-sign-x">✕</div>
      <div className="fm-sign-hint">Sign above the line</div>
    </div>
  );
};

const SignAgreementScreen = ({ nav, t, setTweak, params }) => {
  const { AppBar, Btn } = window.Fm;
  const Ic = window.Icons, FD = window.FD;
  const step = t.signStep; // read | sign | confirm
  const [read, setRead] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [hasSig, setHasSig] = useState(false);
  const stepIdx = step === "read" ? 0 : step === "sign" ? 1 : 2;

  const onScroll = (e) => {
    const el = e.target;
    if (el.scrollTop + el.clientHeight >= el.scrollHeight - 30) setScrolled(true);
  };

  return (
    <>
      <AppBar onBack={() => step === "read" ? nav.back() : setTweak("signStep", step === "confirm" ? "sign" : "read")}
              title="Sign agreement" align="left"
              right={<span className="fm-step-count" style={{ alignSelf: "center", paddingRight: 8 }}>Step {stepIdx + 1} of 3</span>}/>
      <div style={{ padding: "0 20px 12px" }}>
        <div className="fm-steps">
          {[0, 1, 2].map(i => <div key={i} className={`fm-step-pip ${i < stepIdx ? "done" : i === stepIdx ? "cur" : ""}`}/>)}
        </div>
      </div>

      {step === "read" && (
        <>
          <div className="fm-body" onScroll={onScroll}>
            <div className="fm-scroll">
              <div className="fm-pdf">
                <div className="fm-pdf-h"/>
                <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 10 }}>Supply Agreement · {FD.RESP_BY_ID[params.id]?.po || "PO-2026-0461"}</div>
                <div className="muted" style={{ fontSize: 12.5, lineHeight: 1.6, marginBottom: 14 }}>
                  This agreement is made between AMOMS (the Buyer) and {FD.ME.name} (the Supplier)
                  for the supply of avocados as specified in the accepted purchase order.
                </div>
                {Array.from({ length: 9 }).map((_, i) => <div key={i} className="fm-pdf-line" style={{ width: `${[100, 96, 88, 100, 72, 94, 100, 80, 60][i]}%` }}/>)}
                <div style={{ fontSize: 13, fontWeight: 700, margin: "16px 0 10px" }}>Terms of delivery & payment</div>
                {Array.from({ length: 8 }).map((_, i) => <div key={i} className="fm-pdf-line" style={{ width: `${[100, 84, 92, 100, 70, 88, 100, 56][i]}%` }}/>)}
              </div>
              <button className={`fm-check ${read ? "on" : ""}`} style={{ marginTop: 18, opacity: scrolled ? 1 : 0.5 }}
                      disabled={!scrolled} onClick={() => scrolled && setRead(v => !v)}>
                <span className="fm-check-box">{read && <Ic.Check size={15}/>}</span>
                <span className="fm-check-text">I have read and understood this agreement.{!scrolled && <span className="muted" style={{ display: "block", fontSize: 11.5 }}>Scroll to the end to enable.</span>}</span>
              </button>
            </div>
          </div>
          <div className="fm-actionbar">
            <Btn variant="primary" disabled={!read} onClick={() => setTweak("signStep", "sign")}>Continue</Btn>
          </div>
        </>
      )}

      {step === "sign" && (
        <>
          <div className="fm-body">
            <div className="fm-scroll">
              <div className="fm-banner fm-banner-info" style={{ marginBottom: 16 }}>
                <span className="fm-banner-ic"><Ic.Info size={18}/></span>
                <div className="fm-banner-desc" style={{ color: "var(--info)" }}>Turn your phone sideways for more room to sign.</div>
              </div>
              <SignaturePad onChange={setHasSig}/>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{FD.ME.name}</div>
                <button className="fm-link" style={{ display: "inline-flex", alignItems: "center", gap: 5 }}
                        onClick={() => { const cv = document.querySelector(".fm-sign-pad canvas"); cv?._clear?.(); setHasSig(false); }}>
                  <Ic.Refresh size={14}/> Clear
                </button>
              </div>
              <div className="fm-field" style={{ marginTop: 18 }}>
                <label className="fm-label">Or type your name as signature <span className="muted" style={{ fontWeight: 400 }}>(optional)</span></label>
                <input className="fm-input" placeholder="Type full name" onChange={(e) => setHasSig(e.target.value.length > 1)}/>
              </div>
            </div>
          </div>
          <div className="fm-actionbar">
            <Btn variant="primary" disabled={!hasSig} onClick={() => setTweak("signStep", "confirm")}>Continue</Btn>
          </div>
        </>
      )}

      {step === "confirm" && (
        <>
          <div className="fm-body">
            <div className="fm-scroll">
              <div className="fm-ds-label" style={{ margin: "0 2px 8px" }}>Review &amp; submit</div>
              <div className="fm-card flush">
                <div className="fm-srow" style={{ flexDirection: "column", alignItems: "stretch", gap: 8 }}>
                  <span className="k">Your signature</span>
                  <div style={{ height: 64, borderRadius: 10, background: "var(--surface)", display: "flex", alignItems: "center", paddingLeft: 16, fontFamily: "cursive", fontSize: 26, color: "var(--foreground)" }}>{FD.ME.name}</div>
                </div>
                <div className="fm-srow" style={{ flexDirection: "column", alignItems: "stretch", gap: 8 }}>
                  <span className="k">Buyer signature</span>
                  <div style={{ height: 64, borderRadius: 10, background: "var(--surface)", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 16px", fontFamily: "cursive", fontSize: 22, color: "var(--foreground)" }}>
                    AMOMS <span className="badge badge-success"><Ic.CheckCircle size={11}/> Signed</span>
                  </div>
                </div>
              </div>
              <div className="muted" style={{ fontSize: 12, lineHeight: 1.5, marginTop: 14, padding: "0 2px" }}>
                By submitting, you agree to be legally bound by this supply agreement. A copy will be saved to your profile.
              </div>
            </div>
          </div>
          <div className="fm-actionbar">
            <Btn variant="primary" icon={Ic.CheckCircle} onClick={() => { setTweak("acceptedState", "both"); nav.replace("responseAccepted", { id: params.id }); }}>Submit signature</Btn>
          </div>
        </>
      )}
    </>
  );
};

window.FarmerPages = Object.assign(window.FarmerPages || {}, {
  signAgreement: { brandStatus: false, render: (ctx) => <SignAgreementScreen {...ctx}/> },
});
