// verify-page.jsx — full credential verification results page.
const { useState: vS, useEffect: vE } = React;
const VC = window.HOME;
const VI = window.AICONS;
const VDIMS = window.PROFILE_DIMS || VC.profile && VC.profile.dims || [];

function VerifyApp() {
  window.useReveal();
  // Prefill from ?id= (QR codes / share links deep-link here).
  const params = new URLSearchParams(window.location.search);
  const initial = (params.get("id") || "").toUpperCase();
  const [input, setInput] = vS(initial);
  const [res, setRes] = vS(null);
  const [busy, setBusy] = vS(false);
  const [copied, setCopied] = vS(false);
  const [scan, setScan] = vS(false);

  // Live verification against the assessment platform's public registry.
  const API = "https://ai-assessment-backend-o2rx.onrender.com";
  // Canonical D1-D6 dimension keys used by the platform's item bank.
  const DIM_KEYS = ["Prompt 设计与迭代", "AI 输出评估与验证", "工具认知与学习敏捷度",
  "AI 任务执行与流程设计", "情境适配与判断力", "AI 风险识别与责任判断"];

  const fromApi = (id, data) => {
    const ds = data.dimension_scores || {};
    const scores = DIM_KEYS.some((k) => k in ds) ?
    DIM_KEYS.map((k) => ds[k] != null ? Math.round(ds[k]) : null) :
    Object.values(ds).slice(0, 6).map((v) => Math.round(v));
    return {
      ok: true, id, sample: false,
      name: "AI Readiness Certification",
      level: data.readiness_level || "Certified",
      holder: data.recipient_name,
      issued: new Date(data.issued_at).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
      validity: "Score " + Math.round(data.overall_score) + " / 100",
      status: "Active",
      scores
    };
  };

  const lookup = async (rawId) => {
    const id = rawId.trim().toUpperCase();
    if (!id) return;
    setBusy(true);setCopied(false);
    try {
      const r = await fetch(API + "/api/certificates/verify/" + encodeURIComponent(id));
      const data = await r.json();
      if (data.valid) {setRes(fromApi(id, data));setBusy(false);return;}
    } catch (e) {/* network error → fall through to sample records */}
    const rec = VC.validIds[id];
    setRes(rec ? { ok: true, id, sample: true, ...rec } : { ok: false, id });
    setBusy(false);
  };
  vE(() => {if (initial) lookup(initial);}, []); // auto-verify deep links

  const submit = (e) => {e.preventDefault();lookup(input);};
  // The QR path resolves to the SAME public record as the ID path.
  const scanSample = () => {
    const id = "ATL-2F9K-4827-LX";
    setInput(id);
    lookup(id);
    setScan(false);
  };

  const shareLink = res && res.ok ?
  window.location.origin + window.location.pathname + "?id=" + res.id : "";
  const copy = () => {
    if (!shareLink) return;
    const done = () => {setCopied(true);setTimeout(() => setCopied(false), 2000);};
    if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(shareLink).then(done, done);else
    done();
  };

  return (
    <React.Fragment>
      <Nav />
      <Breadcrumb trail={[["Verify a credential", null]]} />
      <main className="vp">
        <section className="vp-head">
          <div className="wrap">
            <span className="label label-accent"><span className="nv-dot" aria-hidden="true"></span>Credential verification</span>
            <h1>Verify any Atlas credential.</h1>
            <p className="vp-lead">Every Atlas credential resolves to a public record — confirm one in seconds.</p>

            <div className="vp-methods">
              <div className="vp-method">
                <span className="vp-method-k">1 · Enter a credential ID</span>
                <form className="vp-form" onSubmit={submit}>
                  <input className="vp-input" value={input} onChange={(e) => setInput(e.target.value)}
                  placeholder="ATLAS-XXXX-XXXX-XXXX" aria-label="Credential ID" spellCheck="false" />
                  <button type="submit" className="btn btn-primary btn-lg" disabled={busy}>{busy ? "Verifying…" : "Verify"}</button>
                </form>
                <div className="vp-samples">
                  Try a sample:
                  {Object.keys(VC.validIds).map((id) =>
                  <button key={id} type="button" className="vp-sample-chip mono" onClick={() => {setInput(id);}}>{id}</button>
                  )}
                </div>
              </div>

              <div className="vp-method-or" aria-hidden="true"><span>or</span></div>

              <div className="vp-method">
                <span className="vp-method-k">2 · Scan QR code</span>
                <p className="vp-method-desc">Scan the QR code printed on any certificate — it resolves to this same public record.</p>
                {!scan &&
                <button type="button" className="vp-scan-btn" onClick={() => setScan(true)}>
                    <span className="vp-scan-ico"><QR /></span>
                    Scan QR code
                  </button>
                }
                {scan &&
                <div className="vp-scanner">
                    <div className="vp-scan-frame">
                      <QR />
                      <span className="vp-scan-line" aria-hidden="true"></span>
                    </div>
                    <p className="vp-scan-hint">Point your camera at the certificate's QR code.</p>
                    <div className="vp-scan-actions">
                      <button type="button" className="btn btn-primary" onClick={scanSample}>Use sample certificate QR <VI.arrow /></button>
                      <button type="button" className="vp-scan-cancel" onClick={() => setScan(false)}>Cancel</button>
                    </div>
                  </div>
                }
              </div>
            </div>

            <p className="vp-noacct"><span className="nv-dot" aria-hidden="true"></span>No account needed. Anyone can verify.</p>
          </div>
        </section>

        <section className="vp-body">
          <div className="wrap">
            {res && res.ok && <CredentialRecord res={res} shareLink={shareLink} copy={copy} copied={copied} />}
            {res && !res.ok &&
            <div className="vp-fail">
                <span className="vp-fail-badge"><VI.x /></span>
                <div>
                  <h3>No credential found for this ID</h3>
                  <p>We couldn't find a record for <span className="mono">{res.id}</span>. Double-check the ID and try again, or scan the QR code on the certificate. IDs look like <span className="mono">ATLAS-XXXX-XXXX-XXXX</span>.</p>
                </div>
              </div>
            }
            <a className="vp-how" href="#how">How verification works <VI.arrow /></a>
          </div>
        </section>

        <section className="vp-how-sec" id="how">
          <div className="wrap vp-how-grid">
            <div className="reveal">
              <span className="label label-accent">How verification works</span>
              <h2>Independent, and impossible to fake.</h2>
            </div>
            <ul className="vp-how-list reveal">
              <li><VI.check className="pp-check" /> Each credential carries a unique ID and a public record — no login required to check it.</li>
              <li><VI.check className="pp-check" /> The record shows the holder, level, exam date, validity, and a score in each of the six competency dimensions.</li>
              <li><VI.check className="pp-check" /> Anyone — an employer, a school, a partner — can confirm a credential in one step and share the link.</li>
              <li><VI.check className="pp-check" /> Graded against a published standard, <a href="standard.html" className="inline-link">Methodology / The Standard</a>, revised in the open.</li>
            </ul>
          </div>
        </section>

        <section className="vp-cta-sec">
          <div className="wrap vp-cta-inner">
            <h2>Don't have a credential yet?</h2>
            <p>Sit the proctored Atlas exam and earn a verifiable credential in 15–30 minutes.</p>
            <a href="https://app.atlas-ai.academy/register" className="btn btn-primary">Get certified <VI.arrow /></a>
          </div>
        </section>
      </main>
      <TeamBanner />
      <Footer />
    </React.Fragment>);

}

function VHexRadar({ dims, scores }) {
  const cx = 200, cy = 188, R = 116, labelR = 150;
  const ang = (i) => (-90 + i * 60) * Math.PI / 180;
  const pt = (r, i) => [cx + r * Math.cos(ang(i)), cy + r * Math.sin(ang(i))];
  const poly = (r) => dims.map((_, i) => pt(r, i).join(",")).join(" ");
  const dataPoly = dims.map((_, i) => pt(R * ((scores[i] || 0) / 100), i).join(",")).join(" ");
  const rings = [25, 50, 75, 100];
  return (
    <svg className="hex-svg" viewBox="0 0 400 372" role="img"
      aria-label={"Competency profile across six dimensions: " + dims.map((d, i) => d.name + " " + scores[i]).join(", ")}>
      {rings.map((r) => <polygon key={r} className="hex-ring" points={poly(R * r / 100)} />)}
      {dims.map((_, i) => {const [x, y] = pt(R, i);return <line key={i} className="hex-axis" x1={cx} y1={cy} x2={x} y2={y} />;})}
      <g className="hex-data">
        <polygon className="hex-area" points={dataPoly} />
        {dims.map((_, i) => {const [x, y] = pt(R * ((scores[i] || 0) / 100), i);return <circle key={i} className="hex-dot" cx={x} cy={y} r="4" />;})}
      </g>
      {dims.map((d, i) => {
        const [lx, ly] = pt(labelR, i);
        const c = Math.cos(ang(i));
        const anchor = c > 0.3 ? "start" : c < -0.3 ? "end" : "middle";
        return (
          <text key={i} className="hex-label" x={lx} y={ly} textAnchor={anchor}>
            <tspan className="hl-name">D{i + 1} · {d.short}</tspan>
            <tspan className="hl-score" x={lx} dy="15">{scores[i] != null ? scores[i] : "—"}</tspan>
          </text>
        );
      })}
    </svg>);

}

function CredentialRecord({ res, shareLink, copy, copied }) {
  const dims = VDIMS;
  const scores = res.scores || [];
  const [view, setView] = vS("bars");
  return (
    <div className="cred-record reveal">
      {res.sample && <div className="cr-sample" aria-label="Demonstration data">Sample record — for demonstration</div>}
      <div className="cr-top">
        <div className="cr-top-l">
          <span className="cr-verified"><span className="vr-badge ok"><VI.check /></span>Verified</span>
          <h2 className="cr-title">{res.name}<span className="cr-level"> · {res.level}</span></h2>
          <p className="cr-holder-line">Issued to <strong>{res.holder}</strong></p>
        </div>
        <div className="cr-seal" aria-hidden="true"><span className="brand-mark">A</span></div>
      </div>

      <div className="cr-fields">
        <div className="cr-field"><span className="cr-k">Holder name</span><span className="cr-v">{res.holder}</span></div>
        <div className="cr-field"><span className="cr-k">Credential ID</span><span className="cr-v mono">{res.id}</span></div>
        <div className="cr-field"><span className="cr-k">Level</span><span className="cr-v">{res.name} · {res.level}</span></div>
        <div className="cr-field"><span className="cr-k">Issued date</span><span className="cr-v">{res.issued}</span></div>
        <div className="cr-field"><span className="cr-k">Validity</span><span className="cr-v">{res.validity}</span></div>
        <div className="cr-field"><span className="cr-k">Status</span><span className="cr-v"><span className="cr-status-dot"></span>{res.status}</span></div>
      </div>

      <div className="cr-scores">
        <div className="cr-scores-head">
          <div className="cr-scores-head-l">
            <span className="cr-scores-title">Competency profile</span>
            <span className="cr-scores-note">Scored 0–100 across the six AI competency dimensions (D1–D6)</span>
          </div>
          <div className="cr-view-toggle" role="tablist" aria-label="Profile view">
            <button type="button" role="tab" aria-selected={view === "bars"} className={"cr-view-btn" + (view === "bars" ? " active" : "")} onClick={() => setView("bars")}>
              <svg viewBox="0 0 16 16" aria-hidden="true"><rect x="2" y="3" width="9" height="2.2" rx="1.1" /><rect x="2" y="6.9" width="12" height="2.2" rx="1.1" /><rect x="2" y="10.8" width="6" height="2.2" rx="1.1" /></svg>
              Bars
            </button>
            <button type="button" role="tab" aria-selected={view === "radar"} className={"cr-view-btn" + (view === "radar" ? " active" : "")} onClick={() => setView("radar")}>
              <svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><polygon points="8,1.5 14,5 14,11 8,14.5 2,11 2,5" stroke="currentColor" strokeWidth="1.4" /><polygon points="8,5 11,6.6 10.4,10 5.6,9.6 5,6" fill="currentColor" fillOpacity=".55" stroke="none" /></svg>
              Radar
            </button>
          </div>
        </div>
        {view === "bars" ?
        <div className="cr-score-rows">
          {dims.map((d, i) =>
          <div className="cr-score-row" key={d.name}>
              <span className="cr-score-d mono">D{i + 1}</span>
              <span className="cr-score-name">{d.name}</span>
              <span className="cr-score-bar"><span className="cr-score-fill" style={{ width: (scores[i] || 0) + "%" }}></span></span>
              <span className="cr-score-num mono">{scores[i] != null ? scores[i] : "—"}</span>
            </div>
          )}
        </div> :
        <div className="cr-radar">
          <div className="hex-figure"><VHexRadar dims={dims} scores={scores} /></div>
        </div>
        }
      </div>

      <div className="cr-share">
        <div className="cr-share-l">
          <span className="cr-k">Share this verification</span>
          <a className="cr-share-link mono" href={shareLink}>{shareLink}</a>
        </div>
        <button type="button" className="btn btn-outline cr-copy" onClick={copy}>{copied ? "Copied ✓" : "Copy link"}</button>
      </div>
    </div>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<VerifyApp />);