// Certificate template + PDF download + public verification page.
// The certificate markup lives in ONE place (certificateInner) and is reused by
// both the printable/PDF document (certificateHTML → new window → print) and the
// in-app preview on the verification page (via dangerouslySetInnerHTML), so the
// two never drift apart.

// The stored cert.color is a CSS var name (e.g. "var(--coral)"). A standalone
// print window has none of the app's CSS variables, so map to real hex.
const CERT_HEX = {
  "var(--coral)": "#EA6A54",
  "var(--sky)":   "#4C9BE0",
  "var(--moss)":  "#5BA672",
  "var(--plum)":  "#9B6FC7",
  "var(--gold)":  "#E5B94E",
};
const certAccent = (c) =>
  CERT_HEX[c] || (typeof c === "string" && c.charAt(0) === "#" ? c : "#EA6A54");

const certEsc = (s) =>
  String(s == null ? "" : s).replace(/[&<>"]/g, (m) =>
    ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[m]));

// Inner certificate markup (landscape card, all-inline styles so it survives in
// a bare print window). `cert` = { id, name|student, title, course, issued, color }.
const certificateInner = (cert) => {
  const accent = certAccent(cert.color);
  const name = certEsc(cert.name || cert.student || "Student");
  const title = certEsc(cert.title || (cert.course || "") + " Certificate");
  const course = certEsc(cert.course || "");
  const issued = certEsc(cert.issued || "");
  const id = certEsc(cert.id || "");
  const verifyUrl = certEsc(location.origin + "/#/verify/" + (cert.id || ""));
  return (
    '<div style="width:900px;max-width:100%;aspect-ratio:1.414/1;background:#ffffff;' +
      "border:14px solid " + accent + ";padding:2px;box-shadow:0 10px 40px rgba(0,0,0,.12);" +
      'font-family:Georgia,\'Times New Roman\',serif;color:#2b2b2b;">' +
      '<div style="height:100%;border:2px solid ' + accent + '55;padding:6% 8%;display:flex;' +
        'flex-direction:column;align-items:center;text-align:center;position:relative;">' +
        '<div style="letter-spacing:.34em;font-size:13px;font-weight:700;color:' + accent + ';' +
          'text-transform:uppercase;font-family:Helvetica,Arial,sans-serif;">EpiqMinds</div>' +
        '<div style="font-size:clamp(26px,4.4vw,44px);margin-top:10px;letter-spacing:.02em;">' +
          'Certificate of Completion</div>' +
        '<div style="width:70px;height:4px;background:' + accent + ';border-radius:2px;margin:14px 0 22px;"></div>' +
        '<div style="font-size:15px;color:#666;font-family:Helvetica,Arial,sans-serif;">This certifies that</div>' +
        '<div style="font-size:clamp(30px,5vw,52px);margin:6px 0 4px;color:#1a1a1a;font-weight:700;">' + name + '</div>' +
        '<div style="font-size:15px;color:#666;font-family:Helvetica,Arial,sans-serif;margin-top:8px;">' +
          'has successfully completed</div>' +
        '<div style="font-size:clamp(18px,2.6vw,26px);margin-top:6px;color:' + accent + ';font-weight:700;">' +
          title + '</div>' +
        (course && course !== title
          ? '<div style="font-size:14px;color:#888;font-family:Helvetica,Arial,sans-serif;margin-top:4px;">' + course + '</div>'
          : "") +
        '<div style="flex:1"></div>' +
        '<div style="width:100%;display:flex;align-items:flex-end;justify-content:space-between;' +
          'font-family:Helvetica,Arial,sans-serif;margin-top:24px;">' +
          '<div style="text-align:left;">' +
            '<div style="font-size:11px;color:#999;text-transform:uppercase;letter-spacing:.08em;">Issued</div>' +
            '<div style="font-size:14px;font-weight:700;color:#444;">' + (issued || "—") + '</div>' +
          '</div>' +
          '<div style="width:58px;height:58px;border-radius:50%;background:' + accent + ';color:#fff;' +
            'display:flex;align-items:center;justify-content:center;font-size:26px;box-shadow:0 4px 12px ' + accent + '66;">&#127942;</div>' +
          '<div style="text-align:right;">' +
            '<div style="font-size:11px;color:#999;text-transform:uppercase;letter-spacing:.08em;">Certificate ID</div>' +
            '<div style="font-size:14px;font-weight:700;color:#444;font-family:\'Courier New\',monospace;">' + id + '</div>' +
          '</div>' +
        '</div>' +
        '<div style="margin-top:14px;font-size:11px;color:#aaa;font-family:Helvetica,Arial,sans-serif;">' +
          'Verify authenticity at ' + verifyUrl + '</div>' +
      '</div>' +
    '</div>'
  );
};

// Full standalone document that auto-opens the print dialog (save as PDF).
const certificateHTML = (cert) =>
  '<!doctype html><html><head><meta charset="utf-8"><title>Certificate ' + certEsc(cert.id || "") + '</title>' +
  '<style>' +
    '@page{size:A4 landscape;margin:0;}' +
    '*{box-sizing:border-box;-webkit-print-color-adjust:exact;print-color-adjust:exact;}' +
    "html,body{margin:0;padding:0;background:#f4f1ea;}" +
    ".wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:28px;}" +
    ".bar{text-align:center;padding:0 0 24px;font-family:Helvetica,Arial,sans-serif;}" +
    ".bar button{background:#2b2b2b;color:#fff;border:0;border-radius:8px;padding:10px 20px;font-size:14px;cursor:pointer;}" +
    "@media print{.wrap{padding:0;min-height:auto;}.bar{display:none;}}" +
  '</style></head><body>' +
    '<div class="wrap">' + certificateInner(cert) + '</div>' +
    '<div class="bar"><button onclick="window.print()">Save as PDF / Print</button></div>' +
    '<script>window.addEventListener("load",function(){setTimeout(function(){window.print();},350);});<\/script>' +
  '</body></html>';

// Open the certificate in a new tab and kick off the print/save-as-PDF flow.
const downloadCertificate = (cert) => {
  const w = window.open("", "_blank");
  if (!w) { alert("Please allow pop-ups to download the certificate."); return; }
  w.document.open();
  w.document.write(certificateHTML(cert));
  w.document.close();
};

// In-app certificate preview (reuses the exact print markup).
const CertificateArt = ({ cert }) => (
  <div style={{ width: "100%", display: "flex", justifyContent: "center" }}
       dangerouslySetInnerHTML={{ __html: certificateInner(cert) }}/>
);

// Public certificate verification page — route #/verify/<CERT-ID>. Works with no
// session; anyone can confirm a certificate is genuine.
const VerifyCertificate = ({ go }) => {
  const route = window.location.hash.slice(1); // "/verify/CERT-XXXX"
  const certId = decodeURIComponent((route.split("/verify/")[1] || "").trim());
  const [state, setState] = React.useState({ loading: true });

  React.useEffect(() => {
    if (!certId) { setState({ loading: false, valid: false }); return; }
    let alive = true;
    apiFetch(`/certificates/verify/${encodeURIComponent(certId)}`)
      .then((r) => r.json().then((d) => ({ ok: r.ok, d })).catch(() => ({ ok: false, d: {} })))
      .then(({ ok, d }) => { if (alive) setState({ loading: false, valid: ok && d.valid, cert: d }); })
      .catch(() => { if (alive) setState({ loading: false, valid: false }); });
    return () => { alive = false; };
  }, [certId]);

  return (
    <div className="codeland" style={{ minHeight: "100vh", background: "var(--paper)", display: "flex", flexDirection: "column" }}>
      <div style={{ padding: "16px 24px", borderBottom: "var(--border-thin)", background: "var(--paper-card)", display: "flex", alignItems: "center", gap: 12 }}>
        <div className="display" style={{ fontSize: 20 }}>
          <span style={{ color: "var(--coral)" }}>Epiq</span><span>Minds</span>
        </div>
        <span style={{ fontSize: 13, color: "var(--ink-mute)" }}>Certificate verification</span>
        <div style={{ flex: 1 }}/>
        <a href="#/login" className="btn btn-ghost" style={{ padding: "6px 12px", fontSize: 12 }}>Sign in</a>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: 28, display: "flex", justifyContent: "center" }}>
        <div style={{ width: "100%", maxWidth: 960 }}>
          {state.loading ? (
            <div style={{ padding: 60, textAlign: "center" }}><Spinner/></div>
          ) : !state.valid ? (
            <div className="card" style={{ padding: 40, textAlign: "center", maxWidth: 520, margin: "40px auto" }}>
              <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--coral)", color: "#fff",
                display: "grid", placeItems: "center", fontSize: 28, margin: "0 auto 16px" }}>✕</div>
              <div style={{ fontSize: 18, fontWeight: 800 }}>Certificate not found</div>
              <div style={{ fontSize: 13, color: "var(--ink-mute)", marginTop: 6 }}>
                No certificate matches {certId ? <b className="mono">{certId}</b> : "this link"}. Check the ID and try again.
              </div>
            </div>
          ) : (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--moss)", color: "#fff",
                padding: "12px 18px", borderRadius: "var(--r-card)", marginBottom: 22 }}>
                <div style={{ width: 34, height: 34, borderRadius: "50%", background: "rgba(255,255,255,.25)",
                  display: "grid", placeItems: "center", fontSize: 18, flexShrink: 0 }}>✓</div>
                <div>
                  <div style={{ fontWeight: 800, fontSize: 15 }}>Verified authentic certificate</div>
                  <div style={{ fontSize: 12.5, opacity: 0.92 }}>
                    Issued to <b>{state.cert.student}</b> · {state.cert.course} · {state.cert.issued}
                  </div>
                </div>
                <div style={{ flex: 1 }}/>
                <button onClick={() => downloadCertificate(state.cert)} className="btn"
                  style={{ background: "rgba(255,255,255,.2)", color: "#fff", padding: "8px 14px", fontSize: 12.5 }}>
                  {I.upload({ size: 13 })} Download PDF
                </button>
              </div>
              <CertificateArt cert={state.cert}/>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
