// verify.jsx — Certificate Verification page (wired to the WordPress REST API)
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.Icon;
  const { PageHero } = window;

  const STATUS_META = {
    valid: { cls: "status-valid", label: "Valid", icon: "shield", color: "var(--ok)", bg: "var(--ok-bg)", msg: "This is a genuine, active INFOTECH certificate." },
    expired: { cls: "status-expired", label: "Expired", icon: "clock", color: "var(--warn)", bg: "var(--warn-bg)", msg: "This certificate is genuine but has passed its validity period." },
    cancelled: { cls: "status-cancelled", label: "Cancelled", icon: "close", color: "var(--bad)", bg: "var(--bad-bg)", msg: "This certificate has been revoked and is no longer valid." },
  };

  function ResultRow({ label, value, strong }) {
    return (
      <div style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "15px 0", borderBottom: "1px solid var(--line-2)" }}>
        <span style={{ color: "var(--ink-2)", fontWeight: 600, fontSize: ".95rem" }}>{label}</span>
        <span style={{ fontWeight: strong ? 800 : 700, color: "var(--ink)", textAlign: "right", fontSize: ".98rem" }}>{value}</span>
      </div>
    );
  }

  function Verify({ navigate, prefill }) {
    const [query, setQuery] = useState(prefill || "");
    const [state, setState] = useState("idle"); // idle | loading | found | notfound | error
    const [record, setRecord] = useState(null);
    const [touched, setTouched] = useState(false);
    const resultRef = useRef(null);

    const run = (value) => {
      const v = (value ?? query).trim();
      setTouched(true);
      if (!v) { setState("idle"); return; }
      setState("loading"); setRecord(null);
      window.api("verify?q=" + encodeURIComponent(v)).then((res) => {
        if (res.ok && res.data && res.data.found) {
          setRecord(res.data.record); setState("found");
        } else if (res.ok) {
          setState("notfound");
        } else {
          setState("error");
        }
      });
    };

    useEffect(() => { if (prefill && prefill.trim()) run(prefill); /* eslint-disable-next-line */ }, []);
    useEffect(() => {
      if ((state === "found" || state === "notfound") && resultRef.current) {
        resultRef.current.scrollTop; // reflow
      }
    }, [state]);

    const onSubmit = (e) => { e.preventDefault(); run(); };
    const meta = record ? (STATUS_META[record.status] || STATUS_META.valid) : null;

    const download = () => {
      if (record.certFileUrl) { window.open(record.certFileUrl, "_blank"); return; }
      window.makeCertPDF(record);
    };

    return (
      <main>
        <PageHero eyebrow="Certificate Verification" title="Verify an INFOTECH certificate"
          sub="Confirm the authenticity of any certificate issued by INFOTECH Institute. This service is public, read-only and secure."
          crumb={[{ label: "Verify Certificate" }]} navigate={navigate} />

        <section className="section">
          <div className="wrap" style={{ maxWidth: 760 }}>
            {/* search card */}
            <div className="card" style={{ padding: "clamp(24px,4vw,40px)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22 }}>
                <span style={{ width: 54, height: 54, borderRadius: 15, background: "var(--brand)", color: "#fff", display: "grid", placeItems: "center", flex: "0 0 auto" }}><Icon name="shield" size={28} /></span>
                <div>
                  <h2 style={{ fontSize: "1.4rem" }}>Enter certificate details</h2>
                  <p className="muted" style={{ fontSize: ".95rem", marginTop: 3 }}>Use the Certificate ID or Registration Number printed on the document.</p>
                </div>
              </div>
              <form onSubmit={onSubmit}>
                <div className="field">
                  <label>Certificate ID or Registration Number <span className="req">*</span></label>
                  <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                    <div style={{ position: "relative", flex: 1, minWidth: 220 }}>
                      <Icon name="certificate" size={19} style={{ position: "absolute", left: 15, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)" }} />
                      <input className={"input" + (touched && !query.trim() && state !== "loading" ? " err" : "")}
                        placeholder="e.g. INFO-2025-GD-0142 or INF-23-1142"
                        value={query} onChange={(e) => setQuery(e.target.value)} style={{ paddingLeft: 46 }} />
                    </div>
                    <button type="submit" className="btn btn-accent" disabled={state === "loading"} style={{ minWidth: 150, opacity: state === "loading" ? .8 : 1 }}>
                      {state === "loading" ? (<><span className="spinner" /> Checking…</>) : (<><Icon name="search" size={18} /> Verify</>)}
                    </button>
                  </div>
                  {touched && !query.trim() && state !== "loading" && <span className="errmsg">Please enter a Certificate ID or Registration Number.</span>}
                </div>
              </form>

              {/* sample hint */}
              <div style={{ marginTop: 18, padding: "14px 16px", background: "var(--cream-2)", borderRadius: 12, display: "flex", gap: 10, alignItems: "flex-start" }}>
                <Icon name="info" size={18} style={{ color: "var(--brand-500)", flex: "0 0 auto", marginTop: 2 }} />
                <div style={{ fontSize: ".88rem", color: "var(--ink-2)" }}>
                  <strong style={{ color: "var(--ink)" }}>Try a sample:</strong>{" "}
                  {["INFO-2025-GD-0142", "INF-24-2098", "INFO-2023-AV-0307", "INFO-2024-PS-0233"].map((s, i) => (
                    <React.Fragment key={s}>
                      <button onClick={() => { setQuery(s); run(s); }} style={{ background: "none", border: 0, color: "var(--brand)", fontWeight: 700, cursor: "pointer", padding: 0, textDecoration: "underline" }}>{s}</button>
                      {i < 3 ? " · " : ""}
                    </React.Fragment>
                  ))}
                </div>
              </div>
            </div>

            {/* results */}
            <div ref={resultRef} style={{ marginTop: 24 }}>
              {state === "loading" && (
                <div className="card" style={{ padding: 40, textAlign: "center" }}>
                  <span className="spinner spinner-lg" style={{ borderTopColor: "var(--brand)" }} />
                  <p className="muted" style={{ marginTop: 16, fontWeight: 600 }}>Searching the certificate registry…</p>
                </div>
              )}

              {state === "error" && (
                <div className="card result-pop" style={{ padding: "clamp(28px,4vw,40px)", textAlign: "center", borderTop: "4px solid var(--warn)" }}>
                  <span style={{ width: 70, height: 70, borderRadius: "50%", background: "var(--warn-bg)", color: "var(--warn)", display: "inline-grid", placeItems: "center" }}><Icon name="info" size={36} /></span>
                  <h3 style={{ marginTop: 18, fontSize: "1.4rem" }}>Something went wrong</h3>
                  <p className="muted" style={{ marginTop: 10, maxWidth: 440, marginInline: "auto" }}>We couldn't reach the verification service. Please check your connection and try again.</p>
                  <button className="btn btn-outline" style={{ marginTop: 22 }} onClick={() => run()}><Icon name="refresh" size={18} /> Try again</button>
                </div>
              )}

              {state === "notfound" && (
                <div className="card result-pop" style={{ padding: "clamp(28px,4vw,40px)", textAlign: "center", borderTop: "4px solid var(--bad)" }}>
                  <span style={{ width: 70, height: 70, borderRadius: "50%", background: "var(--bad-bg)", color: "var(--bad)", display: "inline-grid", placeItems: "center" }}><Icon name="close" size={36} stroke={2.4} /></span>
                  <h3 style={{ marginTop: 18, fontSize: "1.4rem" }}>Certificate not found</h3>
                  <p className="muted" style={{ marginTop: 10, maxWidth: 440, marginInline: "auto" }}>Please check your Certificate ID or Registration Number and try again. If the problem continues, contact the institute.</p>
                  <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 22, flexWrap: "wrap" }}>
                    <button className="btn btn-outline" onClick={() => { setQuery(""); setState("idle"); setTouched(false); }}><Icon name="refresh" size={18} /> Try again</button>
                    <button className="btn btn-brand" onClick={() => navigate("contact")}><Icon name="headset" size={18} /> Contact support</button>
                  </div>
                </div>
              )}

              {state === "found" && record && (
                <div className="card result-pop" style={{ overflow: "hidden", borderTop: "4px solid " + meta.color }}>
                  {/* result header */}
                  <div style={{ padding: "clamp(22px,3.5vw,30px)", display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap", background: meta.bg + "55" }}>
                    <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
                      <span style={{ width: 58, height: 58, borderRadius: 16, background: meta.bg, color: meta.color, display: "grid", placeItems: "center", flex: "0 0 auto" }}><Icon name={meta.icon} size={30} /></span>
                      <div>
                        <div style={{ fontSize: ".82rem", fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--ink-2)" }}>Verification Result</div>
                        <h3 style={{ fontSize: "1.5rem", marginTop: 2 }}>{record.name}</h3>
                      </div>
                    </div>
                    <span className={"status " + meta.cls}><span className="dot" /> {meta.label}</span>
                  </div>

                  <div style={{ padding: "clamp(22px,3.5vw,32px)" }}>
                    <p style={{ display: "flex", gap: 10, alignItems: "center", color: meta.color, fontWeight: 700, marginBottom: 18 }}>
                      <Icon name={record.status === "valid" ? "check" : "info"} size={18} /> {meta.msg}
                    </p>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 40px" }}>
                      <div>
                        <ResultRow label="Student Name" value={record.name} strong />
                        <ResultRow label="Father Name" value={record.father} />
                        <ResultRow label="Course" value={record.course} />
                        <ResultRow label="Grade" value={record.grade} />
                      </div>
                      <div>
                        <ResultRow label="Registration #" value={record.reg} />
                        <ResultRow label="Certificate ID" value={record.certId} />
                        <ResultRow label="Completion Date" value={record.completion} />
                        <ResultRow label="Issued On" value={record.issued} />
                      </div>
                    </div>

                    <div style={{ display: "flex", gap: 12, marginTop: 26, flexWrap: "wrap", alignItems: "center" }}>
                      {record.status !== "cancelled" ? (
                        <button className="btn btn-brand" onClick={download}><Icon name="download" size={18} /> Download Certificate {record.certFileUrl ? "" : "PDF"}</button>
                      ) : (
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 8, color: "var(--ink-3)", fontWeight: 600, fontSize: ".92rem" }}><Icon name="info" size={17} /> Certificate download is disabled for cancelled records</span>
                      )}
                      <button className="btn btn-outline" onClick={() => { setQuery(""); setRecord(null); setState("idle"); setTouched(false); }}><Icon name="search" size={18} /> Verify another</button>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* trust note */}
            <div style={{ display: "flex", gap: 12, alignItems: "center", justifyContent: "center", marginTop: 28, color: "var(--ink-3)", fontSize: ".88rem", fontWeight: 600 }}>
              <Icon name="lock" size={16} /> Secure, read-only verification — your search is not stored.
            </div>
          </div>
        </section>
      </main>
    );
  }

  window.Verify = Verify;
})();
