/* ============================================================
   approval.jsx — tokenised email-link approval landing
   The target of the one-click Approve/Reject links in the
   notification email. Standalone full-page (no persona shell).
   ============================================================ */

function ApprovalLanding({ token }) {
  const [doc, setDoc] = React.useState(null);
  const [biz, setBiz] = React.useState(null);
  const [state, setState] = React.useState("loading"); // loading|ready|invalid|done
  const [result, setResult] = React.useState(null);
  const [rejecting, setRejecting] = React.useState(false);
  const [reason, setReason] = React.useState("");

  React.useEffect(() => {
    (async () => {
      try {
        const d = await api.get(`/api/approvals/${token}`);
        setDoc(d);
        setBiz(d.business || { name: d.biz, short: "?", color: "#888" });
        setState("ready");
      } catch (e) {
        setState("invalid");
      }
    })();
  }, [token]);

  const approve = async () => {
    try { const r = await api.post(`/api/approvals/${token}/approve`); setResult(r.status); setState("done"); }
    catch (e) { setState("invalid"); }
  };
  const reject = async () => {
    try { const r = await api.post(`/api/approvals/${token}/reject`, { reason }); setResult(r.status); setState("done"); }
    catch (e) { setState("invalid"); }
  };

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)", display: "grid", placeItems: "center", padding: "40px 20px" }}>
      <div style={{ width: "min(680px, 100%)" }}>
        <div className="row gap12 mb20" style={{ justifyContent: "center" }}>
          <span style={{ fontFamily: "var(--serif)", fontWeight: 800, fontSize: 26, color: "var(--lime-ink)" }}>Lekha AI</span>
          <span className="tiny">Credit Note Approval</span>
        </div>

        {state === "loading" && <div className="card card-pad" style={{ textAlign: "center" }}>Loading…</div>}

        {state === "invalid" && (
          <div className="card card-pad" style={{ textAlign: "center" }}>
            <span className="k-ic" style={{ margin: "0 auto 12px", width: 44, height: 44, background: "var(--red-bg)", color: "var(--red-fg)" }}><Ic.x /></span>
            <div style={{ fontWeight: 700, fontSize: 17 }}>Link no longer valid</div>
            <div className="tiny mt8">This approval link has already been used or has expired. Open the portal to check the latest status.</div>
            <a className="btn btn-sm mt16" href="/" style={{ textDecoration: "none" }}>Go to portal</a>
          </div>
        )}

        {state === "done" && (
          <div className="card card-pad" style={{ textAlign: "center" }}>
            <span className="k-ic" style={{ margin: "0 auto 12px", width: 44, height: 44, background: result === "verified_in_tally" || result === "approved" ? "var(--green-bg)" : "var(--red-bg)", color: result === "verified_in_tally" || result === "approved" ? "var(--green-fg)" : "var(--red-fg)" }}>
              {result === "cancelled" ? <Ic.x /> : <Ic.check />}
            </span>
            <div style={{ fontWeight: 700, fontSize: 17 }}>{result === "cancelled" ? "Credit note rejected" : "Approved — posting to Tally"}</div>
            <div className="tiny mt8">{result === "cancelled" ? "Nakad has been notified." : "The entry is on its way to Tally. No manual entry needed."}</div>
            <a className="btn btn-sm mt16" href="/" style={{ textDecoration: "none" }}>Go to portal</a>
          </div>
        )}

        {state === "ready" && doc && biz && (
          <div className="card card-pad">
            <div className="row gap12 mb16" style={{ alignItems: "flex-start" }}>
              <BizAvatar biz={biz} size={42} />
              <div className="grow">
                <div style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 700 }}>{doc.cnNo}</div>
                <div className="tiny" style={{ marginTop: 3 }}>{biz.name} · against {doc.invoice}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="tiny">Total credit</div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 24, fontWeight: 700 }}>{fmtINR(doc.amount)}</div>
              </div>
            </div>

            <div className="hint info mb16"><Ic.shield style={{ marginTop: 1, flex: "0 0 15px" }} /><div>You're approving as the authorised finance email for {biz.name}. Approving posts this entry to Tally automatically.</div></div>

            <LineItems doc={doc} />

            {rejecting ? (
              <div className="mt16">
                <div className="field-label">Reason for rejection</div>
                <textarea className="input" style={{ width: "100%", minHeight: 76, resize: "vertical" }} placeholder="e.g. Amount doesn't match our debit note…" value={reason} onChange={(e) => setReason(e.target.value)} />
                <div className="row gap10 mt16">
                  <button className="btn btn-sm grow" onClick={() => setRejecting(false)}>Cancel</button>
                  <button className="btn btn-danger btn-sm grow" onClick={reject}><Ic.x />Confirm reject</button>
                </div>
              </div>
            ) : (
              <div className="row gap10 mt20">
                <button className="btn btn-danger grow" onClick={() => setRejecting(true)}><Ic.x />Reject</button>
                <button className="btn btn-primary btn-lg grow" onClick={approve}><Ic.check />Approve &amp; post</button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ApprovalLanding });
