// auth.jsx — Student Login / Register + Dashboard (wired to the WordPress REST API)
(function () {
  const { useState, useEffect } = React;
  const Icon = window.Icon;
  const { PageHero } = window;
  const CFG = window.INFOTECH || {};

  const STATUS_META = {
    valid: { cls: "status-valid", label: "Valid", color: "var(--ok)", bg: "var(--ok-bg)" },
    expired: { cls: "status-expired", label: "Expired", color: "var(--warn)", bg: "var(--warn-bg)" },
    cancelled: { cls: "status-cancelled", label: "Cancelled", color: "var(--bad)", bg: "var(--bad-bg)" },
  };

  /* ===================== LOGIN / REGISTER ===================== */
  function Login({ navigate }) {
    const [mode, setMode] = useState("login"); // login | register
    const [form, setForm] = useState({ username: "", password: "", name: "", email: "", reg: "" });
    const [errors, setErrors] = useState({});
    const [msg, setMsg] = useState("");
    const [busy, setBusy] = useState(false);

    // Already signed in? Go straight to the dashboard.
    useEffect(() => { if (CFG.loggedIn) navigate("dashboard"); /* eslint-disable-next-line */ }, []);

    const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); if (errors[k]) setErrors((e) => ({ ...e, [k]: null })); setMsg(""); };

    const finishAuth = (data) => {
      if (data.nonce) window.setNonce(data.nonce);
      CFG.loggedIn = true;
      CFG.user = data.user;
      navigate("dashboard");
    };

    const submit = (e) => {
      e.preventDefault();
      setErrors({}); setMsg("");
      if (mode === "login") {
        if (!form.username.trim() || !form.password) { setMsg("Please enter your username/email and password."); return; }
        setBusy(true);
        window.api("login", { method: "POST", body: { username: form.username, password: form.password } }).then((res) => {
          setBusy(false);
          if (res.data && res.data.ok) finishAuth(res.data);
          else setMsg((res.data && res.data.message) || "Login failed. Please try again.");
        });
      } else {
        setBusy(true);
        window.api("register", { method: "POST", body: { name: form.name, email: form.email, reg: form.reg, password: form.password } }).then((res) => {
          setBusy(false);
          if (res.data && res.data.ok) finishAuth(res.data);
          else if (res.data && res.data.errors) setErrors(res.data.errors);
          else setMsg((res.data && res.data.message) || "Could not create your account. Please try again.");
        });
      }
    };

    const Tab = ({ id, label }) => (
      <button type="button" onClick={() => { setMode(id); setErrors({}); setMsg(""); }}
        style={{ flex: 1, padding: "12px 0", fontWeight: 700, fontSize: ".98rem", cursor: "pointer",
          border: 0, background: "none", color: mode === id ? "var(--brand)" : "var(--ink-3)",
          borderBottom: "2.5px solid " + (mode === id ? "var(--brand)" : "var(--line-2)") }}>{label}</button>
    );

    return (
      <main>
        <PageHero eyebrow="Student Portal" title={mode === "login" ? "Welcome back" : "Create your student account"}
          sub="Sign in to view your certificates, results and downloads — all in one place."
          crumb={[{ label: "Student Login" }]} navigate={navigate} />

        <section className="section">
          <div className="wrap" style={{ maxWidth: 480 }}>
            <div className="card" style={{ padding: "clamp(24px,4vw,38px)" }}>
              <div style={{ display: "flex", gap: 6, marginBottom: 26 }}>
                <Tab id="login" label="Sign in" />
                <Tab id="register" label="Create account" />
              </div>

              {msg && (
                <div style={{ padding: "12px 14px", borderRadius: 12, background: "var(--bad-bg)", color: "var(--bad)", fontWeight: 600, fontSize: ".92rem", marginBottom: 18, display: "flex", gap: 8, alignItems: "center" }}>
                  <Icon name="info" size={17} /> {msg}
                </div>
              )}

              <form onSubmit={submit} noValidate>
                {mode === "register" && (
                  <React.Fragment>
                    <div className="field">
                      <label>Full name <span className="req">*</span></label>
                      <input className={"input" + (errors.name ? " err" : "")} value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Your name" />
                      {errors.name && <span className="errmsg">{errors.name}</span>}
                    </div>
                    <div className="field" style={{ marginTop: 16 }}>
                      <label>Email <span className="req">*</span></label>
                      <input className={"input" + (errors.email ? " err" : "")} value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" />
                      {errors.email && <span className="errmsg">{errors.email}</span>}
                    </div>
                    <div className="field" style={{ marginTop: 16 }}>
                      <label>Registration # <span className="muted" style={{ fontWeight: 500 }}>(optional, links your certificates)</span></label>
                      <input className="input" value={form.reg} onChange={(e) => set("reg", e.target.value)} placeholder="e.g. INF-23-1142" />
                    </div>
                  </React.Fragment>
                )}

                {mode === "login" && (
                  <div className="field">
                    <label>Username or email <span className="req">*</span></label>
                    <input className="input" value={form.username} onChange={(e) => set("username", e.target.value)} placeholder="Username or email" autoComplete="username" />
                  </div>
                )}

                <div className="field" style={{ marginTop: 16 }}>
                  <label>Password <span className="req">*</span></label>
                  <input type="password" className={"input" + (errors.password ? " err" : "")} value={form.password} onChange={(e) => set("password", e.target.value)} placeholder="••••••••" autoComplete={mode === "login" ? "current-password" : "new-password"} />
                  {errors.password && <span className="errmsg">{errors.password}</span>}
                </div>

                <button type="submit" className="btn btn-accent btn-lg" disabled={busy} style={{ width: "100%", marginTop: 22, opacity: busy ? .8 : 1 }}>
                  {busy ? (<><span className="spinner" /> Please wait…</>) : (mode === "login" ? (<><Icon name="user" size={18} /> Sign in</>) : (<><Icon name="rocket" size={18} /> Create account</>))}
                </button>
              </form>
            </div>

            <p className="muted" style={{ textAlign: "center", marginTop: 18, fontSize: ".9rem" }}>
              {mode === "login" ? "New student?" : "Already have an account?"}{" "}
              <button onClick={() => setMode(mode === "login" ? "register" : "login")} style={{ background: "none", border: 0, color: "var(--brand)", fontWeight: 700, cursor: "pointer", padding: 0, textDecoration: "underline" }}>
                {mode === "login" ? "Create an account" : "Sign in"}
              </button>
            </p>
          </div>
        </section>
      </main>
    );
  }

  /* ===================== DASHBOARD ===================== */
  function CertItem({ c }) {
    const meta = STATUS_META[c.status] || STATUS_META.valid;
    const downloadCert = () => { if (c.certFileUrl) window.open(c.certFileUrl, "_blank"); else window.makeCertPDF(c); };
    return (
      <div className="card" style={{ padding: "clamp(20px,3vw,28px)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 16, flexWrap: "wrap", alignItems: "flex-start" }}>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <span style={{ width: 50, height: 50, borderRadius: 14, background: "var(--accent-soft)", color: "var(--accent-700)", display: "grid", placeItems: "center", flex: "0 0 auto" }}><Icon name="certificate" size={26} /></span>
            <div>
              <h3 style={{ fontSize: "1.2rem" }}>{c.course}</h3>
              <div className="muted" style={{ fontSize: ".88rem", marginTop: 2 }}>{c.certId}</div>
            </div>
          </div>
          <span className={"status " + meta.cls}><span className="dot" /> {meta.label}</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: "10px 24px", marginTop: 18 }}>
          {[["Registration #", c.reg], ["Grade", c.grade], ["Completed", c.completion], ["Issued", c.issued]].map(([l, v]) => (
            <div key={l}>
              <div className="muted" style={{ fontSize: ".78rem", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{l}</div>
              <div style={{ fontWeight: 700, marginTop: 2 }}>{v || "—"}</div>
            </div>
          ))}
        </div>

        {c.marks && c.marks.length > 0 && (
          <details style={{ marginTop: 18 }}>
            <summary style={{ cursor: "pointer", fontWeight: 700, color: "var(--brand)", display: "flex", alignItems: "center", gap: 8 }}>
              <Icon name="chart" size={17} /> View result marks <Icon name="chevronDown" size={16} />
            </summary>
            <div style={{ marginTop: 12, overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: ".94rem" }}>
                <thead>
                  <tr style={{ textAlign: "left", color: "var(--ink-2)" }}>
                    <th style={{ padding: "8px 10px", borderBottom: "1px solid var(--line-2)" }}>Subject</th>
                    <th style={{ padding: "8px 10px", borderBottom: "1px solid var(--line-2)" }}>Obtained</th>
                    <th style={{ padding: "8px 10px", borderBottom: "1px solid var(--line-2)" }}>Total</th>
                  </tr>
                </thead>
                <tbody>
                  {c.marks.map((m, i) => (
                    <tr key={i}>
                      <td style={{ padding: "8px 10px", borderBottom: "1px solid var(--line-2)", fontWeight: 600 }}>{m.subject}</td>
                      <td style={{ padding: "8px 10px", borderBottom: "1px solid var(--line-2)" }}>{m.obtained}</td>
                      <td style={{ padding: "8px 10px", borderBottom: "1px solid var(--line-2)" }}>{m.total}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </details>
        )}

        <div style={{ display: "flex", gap: 12, marginTop: 20, flexWrap: "wrap" }}>
          {c.status !== "cancelled" && (
            <button className="btn btn-brand btn-sm" onClick={downloadCert}><Icon name="download" size={17} /> Certificate</button>
          )}
          {c.hasResult && (
            <a className="btn btn-outline btn-sm" href={c.resultFileUrl} target="_blank" rel="noreferrer"><Icon name="download" size={17} /> Result / Marksheet</a>
          )}
        </div>
      </div>
    );
  }

  function Dashboard({ navigate }) {
    const [status, setStatus] = useState("loading"); // loading | ready | unauth
    const [data, setData] = useState(null);

    useEffect(() => {
      window.api("me").then((res) => {
        if (res.ok && res.data && res.data.ok) { setData(res.data); setStatus("ready"); }
        else { setStatus("unauth"); }
      });
    }, []);

    const logout = () => {
      window.api("logout", { method: "POST" }).then((res) => {
        if (res.data && res.data.nonce) window.setNonce(res.data.nonce);
        CFG.loggedIn = false; CFG.user = null;
        navigate("home");
      });
    };

    if (status === "loading") {
      return (
        <main style={{ minHeight: "60vh", display: "grid", placeItems: "center" }}>
          <div style={{ textAlign: "center" }}>
            <span className="spinner spinner-lg" style={{ borderTopColor: "var(--brand)" }} />
            <p className="muted" style={{ marginTop: 16, fontWeight: 600 }}>Loading your dashboard…</p>
          </div>
        </main>
      );
    }

    if (status === "unauth") {
      return (
        <main style={{ minHeight: "60vh", display: "grid", placeItems: "center", padding: "80px 24px" }}>
          <div style={{ textAlign: "center", maxWidth: 420 }}>
            <span style={{ width: 72, height: 72, borderRadius: 20, background: "var(--accent-soft)", color: "var(--accent-700)", display: "inline-grid", placeItems: "center" }}><Icon name="user" size={36} /></span>
            <h1 style={{ marginTop: 20, fontSize: "1.8rem" }}>Please sign in</h1>
            <p className="muted" style={{ marginTop: 10 }}>You need to be signed in to view your student dashboard.</p>
            <button className="btn btn-accent" style={{ marginTop: 22 }} onClick={() => navigate("login")}><Icon name="user" size={18} /> Go to login</button>
          </div>
        </main>
      );
    }

    const u = data.user;
    const certs = data.certs || [];

    return (
      <main>
        <PageHero eyebrow="Student Dashboard" title={"Hello, " + (u.name || "Student")}
          sub="Your certificates, results and downloads — all in one place."
          crumb={[{ label: "Dashboard" }]} navigate={navigate} />

        <section className="section">
          <div className="wrap" style={{ maxWidth: 880 }}>
            {/* profile strip */}
            <div className="card" style={{ padding: "clamp(20px,3vw,28px)", display: "flex", justifyContent: "space-between", gap: 16, flexWrap: "wrap", alignItems: "center", marginBottom: 28 }}>
              <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
                <span style={{ width: 56, height: 56, borderRadius: 16, background: "var(--brand)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 800, fontSize: "1.3rem" }}>
                  {(u.name || "S").charAt(0).toUpperCase()}
                </span>
                <div>
                  <div style={{ fontWeight: 800, fontSize: "1.1rem" }}>{u.name}</div>
                  <div className="muted" style={{ fontSize: ".9rem" }}>{u.email}{u.reg ? " · Reg " + u.reg : ""}</div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                {u.admin && (
                  <a className="btn btn-outline btn-sm" href={CFG.adminUrl}><Icon name="grid" size={16} /> Admin panel</a>
                )}
                <button className="btn btn-outline btn-sm" onClick={logout}><Icon name="arrowRight" size={16} /> Sign out</button>
              </div>
            </div>

            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18, gap: 12, flexWrap: "wrap" }}>
              <h2 style={{ fontSize: "1.4rem" }}>My certificates &amp; results</h2>
              <span className="chip">{certs.length} record{certs.length === 1 ? "" : "s"}</span>
            </div>

            {certs.length === 0 ? (
              <div style={{ textAlign: "center", padding: "60px 20px", background: "var(--surface)", borderRadius: "var(--r-lg)", border: "1px dashed var(--line)" }}>
                <span style={{ width: 64, height: 64, borderRadius: 18, background: "var(--cream-2)", display: "inline-grid", placeItems: "center", color: "var(--ink-3)" }}><Icon name="certificate" size={30} /></span>
                <h3 style={{ marginTop: 16 }}>No records yet</h3>
                <p className="muted" style={{ marginTop: 8, maxWidth: 420, marginInline: "auto" }}>
                  Your certificates and results will appear here once the institute issues them. If you have a Registration number, add it to your profile so we can link your records.
                </p>
                <button className="btn btn-outline btn-sm" style={{ marginTop: 18 }} onClick={() => navigate("verify")}><Icon name="shield" size={16} /> Verify a certificate</button>
              </div>
            ) : (
              <div style={{ display: "grid", gap: 20 }}>
                {certs.map((c) => <CertItem key={c.id} c={c} />)}
              </div>
            )}
          </div>
        </section>
      </main>
    );
  }

  Object.assign(window, { Login, Dashboard });
})();
