// Documents page with e-signature flow

function DocumentsPage({ persona, employeeId, savedSignedIds }) {
  const [filter, setFilter] = React.useState("all");
  const [openDoc, setOpenDoc] = React.useState(null);

  // Merge default signed docs with any saved from the database
  const defaultSigned = new Set(DOCS.filter(d => d.status === "signed").map(d => d.id));
  const [signedIds, setSignedIds] = React.useState(() => {
    if (savedSignedIds && savedSignedIds.size > 0) {
      return new Set([...defaultSigned, ...savedSignedIds]);
    }
    return defaultSigned;
  });

  // Sync if parent passes updated savedSignedIds (e.g. after API load)
  React.useEffect(() => {
    if (savedSignedIds && savedSignedIds.size > 0) {
      setSignedIds(new Set([...defaultSigned, ...savedSignedIds]));
    }
  }, [savedSignedIds]);

  const filtered = DOCS.filter(d => {
    if (filter === "pending") return !signedIds.has(d.id);
    if (filter === "signed") return signedIds.has(d.id);
    return true;
  });

  const handleSign = async (id) => {
    setSignedIds(prev => new Set([...prev, id]));
    if (employeeId && window.onboardingAPI) {
      try { await window.onboardingAPI.apiSignDoc(employeeId, id); } catch (e) {}
    }
  };

  const total = DOCS.length;
  const signed = signedIds.size;
  const pct = Math.round(signed / total * 100);

  return (
    <div className="page fade-up">
      <div className="page-head">
        <div>
          <span className="eyebrow">E-signature</span>
          <h1 className="page-title">Documents to sign</h1>
          <p className="page-sub">Government forms, employment paperwork, and policy acknowledgements. All signatures are legally binding under the U.S. ESIGN Act.</p>
        </div>
        <div className="row">
          <button className="btn btn-ghost"><I.download size={14}/> Download all</button>
          <button className="btn btn-primary" onClick={() => {
            const next = DOCS.find(d => !signedIds.has(d.id));
            if (next) setOpenDoc(next);
          }}>
            <I.pen size={14}/> Sign next document
          </button>
        </div>
      </div>

      <div className="doc-progress card card-pad">
        <div className="dp-left">
          <div className="dp-pct t-display">{signed} <span className="muted">of</span> {total}</div>
          <div className="dp-label">documents signed</div>
        </div>
        <div className="dp-bar-wrap">
          <div className="bar" style={{ height: 8 }}>
            <i style={{ width: pct + "%" }}/>
          </div>
          <div className="dp-meta">
            <span className="muted">{pct}% complete</span>
            <span className="muted">·</span>
            <span className="muted">2 due tomorrow</span>
            <span className="muted">·</span>
            <span className="muted">~25 min remaining</span>
          </div>
        </div>
        <div className="dp-encrypt subtle">
          <I.lock size={13}/> 256-bit encrypted · DocuSign
        </div>
      </div>

      <div className="row" style={{ marginBottom: 14, gap: 6 }}>
        <FilterPill label={`All (${total})`} active={filter === "all"} onClick={() => setFilter("all")}/>
        <FilterPill label={`Pending (${total - signed})`} active={filter === "pending"} onClick={() => setFilter("pending")}/>
        <FilterPill label={`Signed (${signed})`} active={filter === "signed"} onClick={() => setFilter("signed")}/>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 40 }}></th>
              <th>Document</th>
              <th style={{ width: 140 }}>Category</th>
              <th style={{ width: 100 }}>Pages</th>
              <th style={{ width: 140 }}>Status / Due</th>
              <th style={{ width: 120 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => {
              const isSigned = signedIds.has(d.id);
              return (
                <tr key={d.id}>
                  <td>
                    <div className={"tick" + (isSigned ? " done" : "")} onClick={() => isSigned ? null : setOpenDoc(d)}>
                      <I.check size={11}/>
                    </div>
                  </td>
                  <td>
                    <div className="row" style={{ gap: 10 }}>
                      <div className="doc-thumb">
                        <I.doc size={16}/>
                      </div>
                      <div>
                        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{d.title}</div>
                        {d.priority === "high" && !isSigned && <div className="chip chip-warn" style={{ marginTop: 4 }}>High priority</div>}
                        {isSigned && <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>Signed {d.signedOn}</div>}
                      </div>
                    </div>
                  </td>
                  <td><span className="chip">{d.category}</span></td>
                  <td className="muted">{d.pages} pages</td>
                  <td>
                    {isSigned
                      ? <span className="chip chip-success"><I.check size={11}/> Signed</span>
                      : <span className="muted" style={{ fontSize: 12.5 }}>Due {d.due}</span>}
                  </td>
                  <td style={{ textAlign: "right" }}>
                    {isSigned ? (
                      <button className="btn btn-soft btn-sm">View</button>
                    ) : (
                      <button className="btn btn-primary btn-sm" onClick={() => setOpenDoc(d)}>
                        <I.pen size={12}/> Sign
                      </button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {openDoc && (
        <SignModal
          doc={openDoc}
          onClose={() => setOpenDoc(null)}
          onSign={(id) => { handleSign(id); setOpenDoc(null); }}
        />
      )}
    </div>
  );
}

function FilterPill({ label, active, onClick }) {
  return (
    <button className={"filter-pill" + (active ? " is-active" : "")} onClick={onClick}>
      {label}
    </button>
  );
}

// ──────────────── Signature modal (e-sign flow) ────────────────
function SignModal({ doc, onClose, onSign }) {
  const [step, setStep] = React.useState(1); // 1=review, 2=sign, 3=confirm
  const [sigType, setSigType] = React.useState("typed");
  const [typedSig, setTypedSig] = React.useState("Riley Park");
  const [agreed, setAgreed] = React.useState(false);
  const [drawn, setDrawn] = React.useState(false);

  const canvasRef = React.useRef(null);
  React.useEffect(() => {
    if (sigType !== "drawn" || !canvasRef.current) return;
    const c = canvasRef.current;
    const ctx = c.getContext("2d");
    let drawing = false;
    let last = null;

    const cssToPx = (e) => {
      const r = c.getBoundingClientRect();
      const x = (e.clientX - r.left) * (c.width / r.width);
      const y = (e.clientY - r.top) * (c.height / r.height);
      return [x, y];
    };
    const start = (e) => { drawing = true; last = cssToPx(e); };
    const move = (e) => {
      if (!drawing) return;
      const [x, y] = cssToPx(e);
      ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue("--text").trim();
      ctx.lineWidth = 2.5; ctx.lineCap = "round"; ctx.lineJoin = "round";
      ctx.beginPath(); ctx.moveTo(last[0], last[1]); ctx.lineTo(x, y); ctx.stroke();
      last = [x, y];
      setDrawn(true);
    };
    const end = () => { drawing = false; };
    c.addEventListener("pointerdown", start);
    c.addEventListener("pointermove", move);
    window.addEventListener("pointerup", end);
    return () => {
      c.removeEventListener("pointerdown", start);
      c.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", end);
    };
  }, [sigType]);

  const clearCanvas = () => {
    const c = canvasRef.current;
    if (!c) return;
    c.getContext("2d").clearRect(0, 0, c.width, c.height);
    setDrawn(false);
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal sign-modal" onClick={e => e.stopPropagation()}>
        <div className="sign-head">
          <div>
            <div className="muted" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".06em" }}>{doc.category} · {doc.pages} pages</div>
            <h2 style={{ margin: "4px 0 0", fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em" }}>{doc.title}</h2>
          </div>
          <div className="sign-stepper">
            <div className={"ss-step " + (step >= 1 ? "active" : "")}>1<span>Review</span></div>
            <div className="ss-line"/>
            <div className={"ss-step " + (step >= 2 ? "active" : "")}>2<span>Sign</span></div>
            <div className="ss-line"/>
            <div className={"ss-step " + (step >= 3 ? "active" : "")}>3<span>Done</span></div>
          </div>
          <button className="icon-btn" onClick={onClose}><I.x size={15}/></button>
        </div>

        <div className="sign-body">
          {step === 1 && <DocPreview doc={doc}/>}
          {step === 2 && (
            <div className="sign-pane">
              <div className="sign-paper">
                <div className="sp-head">
                  <strong>Signature required on Page {doc.pages}</strong>
                  <span className="muted">Convoso, Inc. — {doc.title}</span>
                </div>
                <div className="sp-body">
                  <p>By signing below, I, <strong>{PROFILE.legalName}</strong>, acknowledge that I have read and understood the terms of this document and agree to be bound by them under the U.S. ESIGN Act.</p>
                  <p className="muted small">Signed at <span className="mono">{new Date().toLocaleString()}</span> from IP <span className="mono">73.42.118.204</span></p>

                  <div className="sig-tabs">
                    <button className={"sig-tab " + (sigType === "typed" ? "active" : "")} onClick={() => setSigType("typed")}>Type</button>
                    <button className={"sig-tab " + (sigType === "drawn" ? "active" : "")} onClick={() => setSigType("drawn")}>Draw</button>
                    <button className={"sig-tab " + (sigType === "upload" ? "active" : "")} onClick={() => setSigType("upload")}>Upload</button>
                  </div>

                  <div className="sig-zone">
                    {sigType === "typed" && (
                      <>
                        <input
                          className="sig-input"
                          value={typedSig}
                          onChange={e => setTypedSig(e.target.value)}
                          placeholder="Type your full legal name"
                        />
                        <div className="sig-preview" style={{ fontFamily: '"Caveat", "Snell Roundhand", cursive' }}>
                          {typedSig || "—"}
                        </div>
                      </>
                    )}
                    {sigType === "drawn" && (
                      <div>
                        <canvas ref={canvasRef} width={620} height={140} className="sig-canvas"/>
                        <div className="row" style={{ justifyContent: "space-between", marginTop: 6 }}>
                          <span className="subtle small">Draw your signature with your mouse or touch</span>
                          <button className="btn btn-ghost btn-sm" onClick={clearCanvas}>Clear</button>
                        </div>
                      </div>
                    )}
                    {sigType === "upload" && (
                      <div className="slot" style={{ padding: 32 }}>
                        <I.upload size={20} style={{ marginBottom: 8 }}/>
                        <div>Drop a PNG or JPG of your signature</div>
                        <div className="subtle small">or click to browse · max 2 MB</div>
                      </div>
                    )}
                  </div>

                  <label className="sign-agree">
                    <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)}/>
                    <span>I agree this is my legal signature and I have read the document in full.</span>
                  </label>
                </div>
              </div>
            </div>
          )}
          {step === 3 && (
            <div className="sign-success">
              <div className="success-ring">
                <I.check size={36}/>
              </div>
              <h3 style={{ margin: "16px 0 6px", fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>
                Signed and submitted
              </h3>
              <p className="muted" style={{ maxWidth: 380, textAlign: "center", margin: "0 auto" }}>
                A copy of <strong>{doc.title}</strong> has been emailed to <span className="mono">{PROFILE.email}</span>. People Ops has been notified.
              </p>
              <div className="sign-receipt">
                <div className="sr-row"><span className="muted">Document ID</span><span className="mono">DSGN-{doc.id.toUpperCase()}-9F2A</span></div>
                <div className="sr-row"><span className="muted">Signed by</span><span>{PROFILE.legalName}</span></div>
                <div className="sr-row"><span className="muted">Timestamp</span><span className="mono">{new Date().toLocaleString()}</span></div>
                <div className="sr-row"><span className="muted">Status</span><span className="chip chip-success">Completed</span></div>
              </div>
            </div>
          )}
        </div>

        <div className="sign-foot">
          {step === 1 && (
            <>
              <span className="muted small"><I.lock size={12}/> Encrypted in transit and at rest</span>
              <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
              <button className="btn btn-primary" onClick={() => setStep(2)}>
                Continue to sign <I.arrow size={13}/>
              </button>
            </>
          )}
          {step === 2 && (
            <>
              <button className="btn btn-ghost" onClick={() => setStep(1)}><I.arrowL size={13}/> Back</button>
              <span className="spacer"/>
              <button
                className="btn btn-primary"
                disabled={!agreed || (sigType === "typed" ? !typedSig : sigType === "drawn" ? !drawn : false)}
                onClick={() => setStep(3)}
              >
                <I.pen size={13}/> Sign document
              </button>
            </>
          )}
          {step === 3 && (
            <>
              <button className="btn btn-ghost"><I.download size={13}/> Download PDF</button>
              <span className="spacer"/>
              <button className="btn btn-primary" onClick={() => onSign(doc.id)}>
                Continue <I.arrow size={13}/>
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// fake document preview pane
function DocPreview({ doc }) {
  return (
    <div className="doc-preview">
      <div className="dp-toolbar">
        <span className="muted small">Page 1 of {doc.pages}</span>
        <span className="spacer"/>
        <button className="icon-btn" style={{ width: 28, height: 28 }}><I.arrowL size={13}/></button>
        <button className="icon-btn" style={{ width: 28, height: 28 }}><I.arrow size={13}/></button>
      </div>
      <div className="dp-paper">
        <div className="dp-letterhead">
          <div className="dp-logo">CONVOSO</div>
          <div className="dp-addr subtle">
            6320 Canoga Ave · Woodland Hills, CA 91367<br/>
            convoso.com
          </div>
        </div>
        <h1 className="dp-h1">{doc.title}</h1>
        <p className="dp-meta">Effective date: May 11, 2026 · Document ID DSGN-{doc.id.toUpperCase()}-9F2A</p>
        <p className="dp-p"><strong>Employee:</strong> {PROFILE.legalName} (<span className="mono">{PROFILE.email}</span>)</p>
        <p className="dp-p"><strong>Position:</strong> Software Engineer, Platform — Voice Infrastructure</p>
        <h2 className="dp-h2">1. Purpose</h2>
        <p className="dp-p">This {doc.category.toLowerCase()} document outlines the terms and obligations of {PROFILE.legalName} (the "Employee") as they relate to Convoso, Inc. (the "Company"). By signing below, the Employee acknowledges that they have read this document in its entirety and agree to its terms.</p>
        <h2 className="dp-h2">2. Acknowledgement</h2>
        <p className="dp-p">The Employee confirms that all information provided herein is accurate to the best of their knowledge. The Employee further agrees to comply with all applicable Company policies, including but not limited to the Employee Handbook and Code of Conduct.</p>
        <div className="dp-fade"/>
      </div>
    </div>
  );
}

window.DocumentsPage = DocumentsPage;
