// Admin Dashboard — analytics SaaS, dense, dark/light supported

const ADMIN_NAV = [
  ["OVERVIEW", [["Dashboard", I.chart, "/app/admin"], ["Revenue", I.wallet, "/app/admin/billing"], ["Schedule", I.calendar, "/app/admin/schedule"]]],
  ["PEOPLE", [["Students", I.users, "/app/admin/students"], ["Teachers", I.users, "/app/admin/teachers"], ["Batches", I.book, "/app/admin/batches"], ["Attendance", I.check, "/app/admin/attendance"], ["Kit Delivery", I.rocket, "/app/admin/kits"]]],
  ["LEARNING", [["Courses", I.book, "/app/admin/courses"], ["Quizzes", I.puzzle, "/app/admin/quizzes"], ["Certificates", I.trophy, "/app/admin/certificates"], ["XP Criteria", I.star, "/app/admin/xp-criteria"]]],
  ["SYSTEM", [["Broadcast", I.bell, "/app/admin/broadcast"], ["Payments", I.coin, "/app/admin/payments"], ["Sub-centres", I.pin, "/app/admin/centres"], ["Settings", I.cog, "/app/admin/settings"]]],
];

const AdminSidebar = ({ active = "/app/admin", go }) => {
  // Permission-driven nav: show modules the current user is allowed to use.
  const nav = React.useMemo(() => {
    const systemExtras = [];
    if (hasPerm("manage_users")) systemExtras.push(["Users", I.users, "/app/admin/users"]);
    if (hasPerm("manage_roles")) systemExtras.push(["Roles & Perms", I.cog, "/app/admin/roles"]);
    if (hasPerm("manage_institutions")) systemExtras.push(["Institutions", I.pin, "/app/admin/institutions"]);
    if (hasPerm("view_audit")) systemExtras.push(["Audit Log", I.book, "/app/admin/audit"]);
    const peopleExtras = [];
    if (hasPerm("manage_inquiries")) peopleExtras.push(["Leads", I.users, "/app/admin/leads"]);
    return ADMIN_NAV.map(([head, items]) => {
      if (head === "SYSTEM" && systemExtras.length) return [head, [...items, ...systemExtras]];
      if (head === "PEOPLE" && peopleExtras.length) return [head, [...peopleExtras, ...items]];
      return [head, items];
    });
  }, []);

  return (
    <div style={{
      width: 200, padding: 18, borderRight: "var(--border-thin)",
      background: "var(--paper-card)", display: "flex", flexDirection: "column", gap: 14,
      flexShrink: 0, overflowY: "auto",
    }}>
      <div className="display" style={{ fontSize: 18 }}>
        <span style={{ color: "var(--coral)" }}>Epiq</span>Minds
        <span style={{ color: "var(--ink-mute)", fontSize: 10, marginLeft: 6, fontWeight: 500 }}>
          {currentRole() === 'superadmin' ? 'superadmin' : 'admin'}
        </span>
      </div>
      {nav.map(([head, items]) => (
        <div key={head}>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: ".08em", padding: "0 8px", marginBottom: 4 }}>{head}</div>
          {items.map(([label, ic, path]) => {
            const isActive = active === path;
            return (
              <button key={label} onClick={() => go && go(path)} style={{
                display: "flex", alignItems: "center", gap: 10, width: "100%",
                padding: "6px 8px", borderRadius: 8, border: "none",
                background: isActive ? "var(--paper-deep)" : "transparent",
                color: isActive ? "var(--ink)" : "var(--ink-soft)",
                fontWeight: isActive ? 700 : 500, fontSize: 12,
                cursor: "pointer", textAlign: "left",
              }}>
                {ic({ size: 14 })} {label}
              </button>
            );
          })}
        </div>
      ))}
    </div>
  );
};

const AdminHome = ({ dark = true, go }) => {
  const { data: stats, loading } = useApi("/admin/stats", {});
  const S = stats.students  || {};
  const I2 = stats.invoices  || {};
  const teachers = stats.teachers || [];
  const batches  = stats.batches  || [];
  const revenue  = stats.revenue  || [];
  const INQ      = stats.inquiries || {};
  const conv     = INQ.total > 0 ? Math.round((INQ.joined / INQ.total) * 100) : null;

  const fmt = n => n >= 100000 ? "₹" + (n/100000).toFixed(2) + "L"
                 : n >= 1000   ? "₹" + (n/1000).toFixed(1) + "K"
                 : "₹" + n;

  const attColor = a => a >= 90 ? "var(--moss)" : a >= 75 ? "var(--gold)" : "var(--coral)";

  if (loading) return <Spinner />;
  return (
  <Themed className={dark ? "theme-dark" : ""} style={{ width: "100%", height: "100%", display: "flex" }}>
    <AdminSidebar active="/app/admin" go={go}/>
    <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, background: "var(--paper)" }}>
      {/* Top bar */}
      <div style={{
        display: "flex", alignItems: "center", gap: 12, padding: "12px 22px",
        borderBottom: "var(--border-thin)", background: "var(--paper-card)",
      }}>
        <div>
          <div className="display" style={{ fontSize: 20 }}>Dashboard</div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)" }}>Last 30 days · vs prev period</div>
        </div>
        <div style={{ flex: 1 }}/>
        <Tabs items={["7d","30d","90d","All"]} active="30d" onChange={() => {}}/>
        <button className="btn btn-ghost" style={{ padding: "6px 12px", fontSize: 12 }}>{I.upload({ size: 14 })} Export</button>
        <button className="btn btn-primary" onClick={() => go && go("/app/admin/broadcast")} style={{ padding: "6px 12px", fontSize: 12 }}>{I.send({ size: 14 })} Broadcast</button>
      </div>

      <div style={{ padding: 22, flex: 1, overflow: "auto", display: "flex", flexDirection: "column", gap: 16 }}>
        {/* KPI row */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
          {[
            { label: "TOTAL STUDENTS", value: S.total ?? "—" },
            { label: "ACTIVE STUDENTS", value: S.active ?? "—" },
            { label: "AT-RISK", value: S.at_risk ?? "—", warn: S.at_risk > 0 },
            { label: "TOTAL SESSIONS", value: stats.sessions ?? "—" },
            { label: "AVG ATTENDANCE", value: stats.attendance != null ? stats.attendance + "%" : "—", warn: stats.attendance < 75 },
          ].map(k => (
            <div key={k.label} className="card-flat" style={{ padding: 14 }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: ".06em" }}>{k.label}</div>
              <div className="display" style={{ fontSize: 26, marginTop: 4, color: k.warn ? "var(--coral)" : "var(--ink)" }}>{k.value}</div>
            </div>
          ))}
        </div>

        {/* Leads / enrolment funnel */}
        {hasPerm("manage_inquiries") && (
          <div className="card-flat" style={{ padding: 16 }}>
            <SectionHead eyebrow="ENROLMENT FUNNEL" title="Leads"
              action={<button className="btn btn-ghost" onClick={() => go && go("/app/admin/leads")} style={{ padding:"4px 10px", fontSize:11 }}>Manage leads →</button>}/>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
              {[
                { label: "INQUIRED", value: INQ.inquired ?? 0, color: "var(--sky)" },
                { label: "NEGOTIATING", value: INQ.negotiating ?? 0, color: "var(--gold)" },
                { label: "JOINED", value: INQ.joined ?? 0, color: "var(--moss)" },
                { label: "CONVERSION", value: conv != null ? conv + "%" : "—", color: "var(--coral)" },
              ].map(k => (
                <div key={k.label} className="card-flat" style={{ padding: 14, borderLeft: `3px solid ${k.color}` }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: ".06em" }}>{k.label}</div>
                  <div className="display" style={{ fontSize: 26, marginTop: 4, color: k.color }}>{k.value}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
          {/* Teachers */}
          <div className="card-flat" style={{ padding: 16 }}>
            <SectionHead eyebrow="PEOPLE" title="Teachers"
              action={<button className="btn btn-ghost" onClick={() => go && go("/app/admin/teachers")} style={{ padding:"4px 10px", fontSize:11 }}>Manage →</button>}/>
            {teachers.length === 0 ? (
              <div style={{ color:"var(--ink-mute)", fontSize:13, padding:"12px 0" }}>No teachers yet. <a onClick={()=>go("/app/admin/teachers")} style={{ color:"var(--coral)", cursor:"pointer" }}>Add one →</a></div>
            ) : (
              <div style={{ display:"flex", flexDirection:"column" }}>
                {teachers.map((t, i) => (
                  <div key={t.id} style={{ display:"flex", alignItems:"center", gap:10, padding:"8px 0", borderTop: i?"var(--border-thin)":"none" }}>
                    <Avatar name={t.name[0]} color="var(--coral)" size={28}/>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13, fontWeight:700 }}>{t.name}</div>
                      <div style={{ fontSize:11, color:"var(--ink-mute)" }}>{t.email}</div>
                    </div>
                    <div className="chip flat" style={{ fontSize:11, padding:"2px 8px" }}>{t.batches} batches</div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Alerts + Revenue summary */}
          <div style={{ display:"flex", flexDirection:"column", gap:12 }}>
            <div className="card-flat" style={{ padding:16 }}>
              <SectionHead eyebrow="NEEDS ATTN" title="Alerts"/>
              {[
                S.at_risk > 0 && { type:"Churn risk", msg: `${S.at_risk} student${S.at_risk>1?"s":""} at risk`, color:"var(--coral)", path:"/app/admin/students" },
                I2.overdue > 0 && { type:"Payment", msg: `${I2.overdue} invoice${I2.overdue>1?"s":""} overdue`, color:"var(--gold)", path:"/app/admin/billing" },
              ].filter(Boolean).map((a, i) => (
                <div key={i} style={{ display:"flex", alignItems:"center", gap:10, padding:"8px 0", borderTop:i?"var(--border-thin)":"none" }}>
                  <div style={{ width:6, height:30, borderRadius:3, background:a.color }}/>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:12, fontWeight:700 }}>{a.type}</div>
                    <div style={{ fontSize:11, color:"var(--ink-mute)" }}>{a.msg}</div>
                  </div>
                  <button className="btn btn-ghost" onClick={()=>go&&go(a.path)} style={{ padding:"2px 8px", fontSize:11 }}>View</button>
                </div>
              ))}
              {S.at_risk === 0 && I2.overdue === 0 && (
                <div style={{ fontSize:13, color:"var(--ink-mute)", padding:"8px 0" }}>All clear ✓</div>
              )}
            </div>

            <div className="card-flat" style={{ padding:16 }}>
              <SectionHead eyebrow="REVENUE" title="Collected"/>
              <div className="display" style={{ fontSize:28, margin:"8px 0 4px" }}>{fmt(I2.collected || 0)}</div>
              <div style={{ fontSize:12, color:"var(--ink-mute)", marginBottom:12 }}>Pending: {fmt(I2.pending || 0)}</div>
              {revenue.map((r, i) => (
                <div key={i} style={{ display:"flex", justifyContent:"space-between", fontSize:12, padding:"4px 0", borderTop:i?"var(--border-thin)":"none" }}>
                  <span style={{ color:"var(--ink-soft)" }}>{r.plan || "—"}</span>
                  <span style={{ fontWeight:700 }}>{fmt(r.total)}</span>
                </div>
              ))}
              {revenue.length === 0 && <div style={{ fontSize:12, color:"var(--ink-mute)" }}>No paid invoices yet</div>}
            </div>
          </div>
        </div>

        {/* Batches table */}
        <div className="card-flat" style={{ padding:16 }}>
          <SectionHead eyebrow="COHORTS" title="All batches"
            action={<button className="btn btn-ghost" onClick={()=>go&&go("/app/admin/batches")} style={{ padding:"4px 10px", fontSize:11 }}>{I.plus({ size:12 })} Add batch</button>}/>
          {batches.length === 0 ? (
            <div style={{ color:"var(--ink-mute)", fontSize:13, padding:"12px 0" }}>No batches yet. <a onClick={()=>go("/app/admin/batches")} style={{ color:"var(--coral)", cursor:"pointer" }}>Create one →</a></div>
          ) : (
            <table style={{ width:"100%", borderCollapse:"collapse", fontSize:12 }}>
              <thead>
                <tr style={{ textAlign:"left", color:"var(--ink-mute)" }}>
                  {["Batch","Course","Teacher","Students","Attendance","Avg XP"].map(h => (
                    <th key={h} style={{ padding:"8px 0 8px 8px", fontWeight:600, fontSize:11, borderBottom:"var(--border-thin)" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {batches.map((b, i) => (
                  <tr key={i} style={{ borderTop:"var(--border-thin)" }}>
                    <td style={{ padding:"10px 8px", fontWeight:700 }}>{b.batch}</td>
                    <td style={{ padding:"10px 8px" }}>{b.course}</td>
                    <td style={{ padding:"10px 8px", color:"var(--ink-soft)" }}>{b.teacher || "—"}</td>
                    <td style={{ padding:"10px 8px", textAlign:"right" }}>{b.students}</td>
                    <td style={{ padding:"10px 8px", textAlign:"right", fontWeight:700, color: attColor(b.attendance) }}>{b.attendance}%</td>
                    <td style={{ padding:"10px 8px", textAlign:"right", fontFamily:"var(--font-mono)" }}>{b.avg_xp}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  </Themed>
  );
};

window.AdminHome = AdminHome;

