/* global React, Icon, Button, Stat, SectionHead, Av, cx, fmtLabel, CATEGORIES, CAT, US_STATES, todayLabel */
// LPE Learning Center — Admin Screens (Dashboard, CLE requests, Course CRUD, Learners)

const { useState: useStateAdmin, useMemo: useMemoAdmin } = React;

// Embedded styling for Admin dashboard & tools
const adminStyles = `
.lpe-scope .admin-dashboard-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.lpe-scope .admin-card {
  background: var(--white);
  border: 1px solid var(--grey-200);
  padding: 24px;
  position: relative;
  display: flex;
  flex-direction: column;
}

.lpe-scope .admin-card .kpi-label {
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: var(--tracking-eyebrow, 0.18em);
  color: var(--grey);
  margin-bottom: 8px;
}

.lpe-scope .admin-card .kpi-value {
  font-size: 32px;
  font-weight: 700;
  color: var(--navy);
  line-height: 1.1;
  margin-bottom: 6px;
}

.lpe-scope .admin-card .kpi-sub {
  font-size: 12px;
  color: var(--grey);
}

.lpe-scope .admin-card .kpi-icon {
  position: absolute;
  top: 24px;
  right: 24px;
  color: var(--grey-300);
}

.lpe-scope .admin-row-2col {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
}

@media (max-width: 1024px) {
  .lpe-scope .admin-row-2col {
    grid-template-columns: 1fr;
  }
}

.lpe-scope .chart-panel {
  background: var(--white);
  border: 1px solid var(--grey-200);
  padding: 24px;
}

.lpe-scope .chart-container {
  height: 220px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  padding-top: 24px;
  border-bottom: 1px solid var(--grey-200);
  position: relative;
}

.lpe-scope .chart-bar-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  justify-content: flex-end;
  position: relative;
}

.lpe-scope .chart-bar {
  width: 32px;
  background: var(--navy);
  transition: height 0.4s ease, background-color 0.2s;
  cursor: pointer;
  position: relative;
}

.lpe-scope .chart-bar:hover {
  background: var(--orange);
}

.lpe-scope .chart-bar-tooltip {
  position: absolute;
  top: -30px;
  background: var(--navy-900);
  color: white;
  font-size: 11px;
  padding: 4px 8px;
  border-radius: 2px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transform: translateY(5px);
  transition: opacity 0.2s, transform 0.2s;
  z-index: 10;
}

.lpe-scope .chart-bar-wrapper:hover .chart-bar-tooltip {
  opacity: 1;
  transform: translateY(0);
}

.lpe-scope .chart-label {
  font-size: 11px;
  color: var(--grey);
  margin-top: 10px;
  text-align: center;
}

.lpe-scope .recent-activities {
  background: var(--white);
  border: 1px solid var(--grey-200);
  padding: 24px;
  max-height: 310px;
  overflow-y: auto;
}

.lpe-scope .activity-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px dashed var(--grey-100);
}

.lpe-scope .activity-item:last-child {
  border-bottom: 0;
}

.lpe-scope .activity-item .time {
  font-size: 11px;
  color: var(--grey-300);
  font-family: var(--font-mono);
  white-space: nowrap;
}

.lpe-scope .activity-item .desc {
  font-size: 12.5px;
  color: var(--navy);
}

.lpe-scope .admin-table-container {
  background: var(--white);
  border: 1px solid var(--grey-200);
  overflow-x: auto;
  margin-bottom: 24px;
}

.lpe-scope .admin-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.lpe-scope .admin-table th {
  padding: 14px 18px;
  background: var(--cream);
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: var(--tracking-ui, 0.12em);
  color: var(--grey);
  border-bottom: 1px solid var(--grey-200);
}

.lpe-scope .admin-table td {
  padding: 16px 18px;
  font-size: 13px;
  color: var(--navy);
  border-bottom: 1px solid var(--grey-100);
  vertical-align: middle;
}

.lpe-scope .admin-table tr:last-child td {
  border-bottom: 0;
}

.lpe-scope .admin-table tr:hover td {
  background: var(--cream);
}

.lpe-scope .admin-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  font-weight: 600;
  padding: 3px 8px;
  border-radius: 2px;
  text-transform: uppercase;
  letter-spacing: 0.04em;
}

.lpe-scope .admin-badge.pending {
  background: #FFF9E6;
  color: var(--gold-700, #B38600);
}

.lpe-scope .admin-badge.approved {
  background: #EAF7F6;
  color: var(--teal);
}

.lpe-scope .admin-badge.rejected {
  background: #FDF1EB;
  color: var(--orange-700);
}

.lpe-scope .admin-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(10, 30, 54, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 24px;
}

.lpe-scope .admin-modal {
  background: var(--white);
  border: 1px solid var(--navy-900);
  width: 100%;
  max-width: 600px;
  display: flex;
  flex-direction: column;
}

.lpe-scope .admin-modal-header {
  padding: 18px 24px;
  border-bottom: 1px solid var(--grey-200);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--cream);
}

.lpe-scope .admin-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--navy);
}

.lpe-scope .admin-modal-body {
  padding: 24px;
  max-height: 480px;
  overflow-y: auto;
}

.lpe-scope .admin-modal-footer {
  padding: 16px 24px;
  border-top: 1px solid var(--grey-200);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: var(--cream);
}

.lpe-scope .admin-form-group {
  margin-bottom: 16px;
}

.lpe-scope .admin-form-group label {
  display: block;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: var(--grey);
  margin-bottom: 6px;
}

.lpe-scope .admin-form-group input,
.lpe-scope .admin-form-group select,
.lpe-scope .admin-form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid var(--grey-200);
  font-size: 13px;
  color: var(--navy);
  background: var(--white);
  outline: none;
}

.lpe-scope .admin-form-group input:focus,
.lpe-scope .admin-form-group select:focus,
.lpe-scope .admin-form-group textarea:focus {
  border-color: var(--navy);
}

.lpe-scope .admin-form-2col {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.lpe-scope .admin-form-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 13px;
  color: var(--navy);
}
`;

// Helper component to inject the styles
function AdminStyles() {
  return <style dangerouslySetInnerHTML={{ __html: adminStyles }} />;
}

// -------------------------------------------------------------
// 1. Admin Dashboard Screen
// -------------------------------------------------------------
function AdminDashboardScreen({ videos, cleRequests, learners, onNavigate, showToast, hideCle, onToggleCle }) {
  const videosArr = videos || [];
  const cleRequestsArr = cleRequests || [];
  const learnersArr = learners || [];

  const pendingRequestsCount = cleRequestsArr.filter((r) => r.status === "pending").length;
  const approvedRequestsCount = cleRequestsArr.filter((r) => r.status === "approved").length;

  const totalCreditsIssued = useMemoAdmin(() => {
    return cleRequestsArr
      .filter((r) => r.status === "approved")
      .reduce((sum, r) => sum + r.credits, 0);
  }, [cleRequestsArr]);

  const recentActivities = useMemoAdmin(() => {
    const list = cleRequestsArr.slice(0, 5).map(req => {
      const statusLabel = req.status === "approved" ? "approved" : req.status === "rejected" ? "rejected" : "submitted";
      return {
        time: req.timestamp || "Just now",
        desc: `${req.learnerName} ${statusLabel} CLE request for ${req.videoId} (${req.credits} credits)`
      };
    });
    if (list.length === 0) {
      return [
        { time: "System", desc: "Portal database initialized successfully." },
        { time: "Seeding", desc: "Default administrative accounts & course libraries ready." }
      ];
    }
    return list;
  }, [cleRequestsArr]);

  // Dummy active learners weekly chart
  const weeklyData = [
    { label: "Mon", count: 48 },
    { label: "Tue", count: 62 },
    { label: "Wed", count: 85 },
    { label: "Thu", count: 72 },
    { label: "Fri", count: 54 },
    { label: "Sat", count: 21 },
    { label: "Sun", count: 18 },
  ];

  const maxCount = Math.max(...weeklyData.map((d) => d.count));

  return (
    <div className="lc-page">
      <AdminStyles />
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow" style={{ color: "var(--orange)" }}>Administrative Panel</div>
          <h1>System Overview & Metrics</h1>
          <p className="subtitle">Real-time status of members, continuing legal education claims, and session catalog.</p>
        </div>
        {onToggleCle ? (
          <div className="header-actions" style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <Button
              variant={hideCle ? "primary" : "secondary"}
              icon="award"
              onClick={onToggleCle}
            >
              {hideCle ? "Enable CLE Features" : "Hide CLE Features"}
            </Button>
          </div>
        ) : null}
      </div>

      <div className="admin-dashboard-grid">
        <div className="admin-card">
          <div className="kpi-label">Total Learners</div>
          <div className="kpi-value">{learnersArr.length}</div>
          <div className="kpi-sub">{learnersArr.filter((l) => l.onboarded).length} verified members</div>
          <span className="kpi-icon"><Icon name="user" size={24} /></span>
        </div>

        <div className="admin-card" style={{ cursor: "pointer" }} onClick={() => onNavigate("admin-cle")}>
          <div className="kpi-label">Pending CLE Claims</div>
          <div className="kpi-value" style={pendingRequestsCount > 0 ? { color: "var(--orange)" } : {}}>{pendingRequestsCount}</div>
          <div className="kpi-sub">{approvedRequestsCount} requests approved all-time</div>
          <span className="kpi-icon"><Icon name="award" size={24} /></span>
        </div>

        <div className="admin-card" style={{ cursor: "pointer" }} onClick={() => onNavigate("admin-courses")}>
          <div className="kpi-label">Active Library Sessions</div>
          <div className="kpi-value">{videosArr.length}</div>
          <div className="kpi-sub">
            {videosArr.filter((v) => v.format === "webinar").length} webinars · {videosArr.filter((v) => v.format === "tutorial").length} tutorials
          </div>
          <span className="kpi-icon"><Icon name="video" size={24} /></span>
        </div>

        <div className="admin-card">
          <div className="kpi-label">CLE Credits Earned</div>
          <div className="kpi-value">{totalCreditsIssued.toFixed(1)}</div>
          <div className="kpi-sub">Across all jurisdictions</div>
          <span className="kpi-icon"><Icon name="award" size={24} /></span>
        </div>
      </div>

      <div className="admin-row-2col">
        <div className="chart-panel">
          <div className="lc-section-head" style={{ marginTop: 0, marginBottom: 12 }}>
            <h2>Learner Activity (Weekly)</h2>
            <span className="meta">Unique active logins per day</span>
          </div>
          <div className="chart-container">
            {weeklyData.map((d) => {
              const pct = (d.count / maxCount) * 80; // Scale to fit
              return (
                <div key={d.label} className="chart-bar-wrapper">
                  <div className="chart-bar-tooltip">{d.count} learners</div>
                  <div className="chart-bar" style={{ height: `${pct}%` }} />
                  <div className="chart-label">{d.label}</div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="recent-activities">
          <div className="lc-section-head" style={{ marginTop: 0, marginBottom: 12 }}>
            <h2>Activity Log</h2>
          </div>
          <div>
            {recentActivities.map((act, i) => (
              <div key={i} className="activity-item">
                <span className="time">{act.time}</span>
                <span className="desc">{act.desc}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// -------------------------------------------------------------
// 2. Admin CLE Approvals Screen
// -------------------------------------------------------------
function AdminCleScreen({ cleRequests, setCleRequests, videoMap, showToast, setAttended }) {
  const [filter, setFilter] = useStateAdmin("pending"); // pending | all
  const cleRequestsArr = cleRequests || [];

  const shown = useMemoAdmin(() => {
    if (filter === "pending") return cleRequestsArr.filter((r) => r.status === "pending");
    return cleRequestsArr;
  }, [cleRequestsArr, filter]);

  function handleAction(reqId, action) {
    setCleRequests((prev) =>
      (prev || []).map((r) => {
        if (r.id === reqId) {
          return { ...r, status: action === "approve" ? "approved" : "rejected" };
        }
        return r;
      })
    );

    const matchedReq = cleRequestsArr.find((r) => r.id === reqId);
    if (matchedReq) {
      if (action === "approve") {
        showToast(`Approved CLE claim for ${matchedReq.learnerName}`);
      } else {
        showToast(`Rejected CLE claim for ${matchedReq.learnerName}`);
      }
    }
  }

  return (
    <div className="lc-page">
      <AdminStyles />
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow" style={{ color: "var(--orange)" }}>Administrative Panel</div>
          <h1>CLE Affidavit Approvals</h1>
          <p className="subtitle">Verify and approve retroactive CLE credit affidavits submitted by attorneys.</p>
        </div>
      </div>

      <div className="lc-toolbar">
        <div className="lc-chiprow">
          <button className={cx("lc-chip", filter === "pending" && "active")} onClick={() => setFilter("pending")}>
            Pending Approvals <span className="ct">{cleRequestsArr.filter((r) => r.status === "pending").length}</span>
          </button>
          <button className={cx("lc-chip", filter === "all" && "active")} onClick={() => setFilter("all")}>
            All Submissions <span className="ct">{cleRequestsArr.length}</span>
          </button>
        </div>
      </div>

      <div className="admin-table-container">
        {shown.length === 0 ? (
          <div style={{ padding: "40px", textStyle: "center", textAlign: "center", color: "var(--grey)" }}>
            <Icon name="checkCircle" size={24} style={{ color: "var(--teal)", marginBottom: 12 }} />
            <h4>No submissions found</h4>
            <p>All affidavits have been processed.</p>
          </div>
        ) : (
          <table className="admin-table">
            <thead>
              <tr>
                <th>Learner</th>
                <th>Jurisdiction & Bar</th>
                <th>Session code & title</th>
                <th>Hours & Type</th>
                <th>Date submitted</th>
                <th>Status</th>
                <th style={{ textAlign: "right" }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {shown.map((req) => {
                const video = videoMap[req.videoId] || { title: "Unknown", code: req.videoId, cle: { credits: req.credits, type: req.type } };
                return (
                  <tr key={req.id}>
                    <td>
                      <div style={{ fontWeight: 600 }}>{req.learnerName}</div>
                      <div style={{ fontSize: 11, color: "var(--grey)" }}>{req.learnerEmail}</div>
                    </td>
                    <td>
                      <div>{req.state}</div>
                      <div style={{ fontSize: 11.5, color: "var(--grey)", fontFamily: "var(--font-mono)" }}>{req.barNo}</div>
                    </td>
                    <td>
                      <div style={{ fontSize: 11.5, fontFamily: "var(--font-mono)", fontWeight: 700 }}>{video.code}</div>
                      <div style={{ textOverflow: "ellipsis", overflow: "hidden", whiteSpace: "nowrap", maxWidth: "250px" }} title={video.title}>{video.title}</div>
                    </td>
                    <td>
                      <div><b>{video.cle.credits.toFixed(1)}</b> hrs</div>
                      <div style={{ fontSize: 11, color: "var(--grey)", textTransform: "uppercase" }}>{video.cle.type}</div>
                    </td>
                    <td>
                      <div style={{ fontSize: 12 }}>{req.attendedOn}</div>
                      <div style={{ fontSize: 11, color: "var(--grey)" }}>{req.timestamp}</div>
                    </td>
                    <td>
                      <span className={cx("admin-badge", req.status)}>
                        {req.status}
                      </span>
                    </td>
                    <td style={{ textAlign: "right" }}>
                      {req.status === "pending" ? (
                        <div style={{ display: "inline-flex", gap: 6 }}>
                          <Button variant="navy" size="sm" onClick={() => handleAction(req.id, "approve")}>Approve</Button>
                          <Button variant="ghost" size="sm" onClick={() => handleAction(req.id, "reject")} style={{ color: "var(--orange-700)" }}>Deny</Button>
                        </div>
                      ) : (
                        <span style={{ fontSize: 12, color: "var(--grey)", fontStyle: "italic" }}>Processed</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

// -------------------------------------------------------------
// 3. Admin Manage Library Screen (CRUD)
// -------------------------------------------------------------
function AdminCoursesScreen({ videos, setVideos, showToast }) {
  const [modal, setModal] = useStateAdmin(null); // null | { mode: 'add' | 'edit', video: null | Object }
  const videosArr = videos || [];
  const [form, setForm] = useStateAdmin({
    code: "", title: "", sub: "", format: "webinar", cat1: "valuation", cat2: "",
    speakerName: "", speakerRole: "", speakerColor: "navy", duration: 60,
    cleEligible: true, cleCredits: 1.0, cleType: "General", blurb: "", youtubeId: "",
    thumbnailUrl: "", customResources: []
  });
  const [search, setSearch] = useStateAdmin("");

  const filtered = useMemoAdmin(() => {
    const q = search.trim().toLowerCase();
    if (!q) return videosArr;
    return videosArr.filter((v) =>
      v && v.speaker && (v.title + " " + v.code + " " + v.speaker.name).toLowerCase().includes(q)
    );
  }, [videosArr, search]);

  function openAdd() {
    const maxNum = videosArr.reduce((max, v) => {
      const match = (v.code || "").match(/LPE-W(\d+)/i);
      return match ? Math.max(max, parseInt(match[1], 10)) : max;
    }, 18);
    setForm({
      code: "LPE-W" + (maxNum + 1),
      title: "",
      sub: "",
      format: "webinar",
      cat1: "valuation",
      cat2: "",
      speakerName: "Tom Lenfestey",
      speakerRole: "Founder, LPE",
      speakerColor: "navy",
      duration: 60,
      cleEligible: true,
      cleCredits: 1.0,
      cleType: "General",
      blurb: "",
      youtubeId: "",
      thumbnailUrl: "",
      customResources: [
        { name: "Executive presentation", type: "PDF", size: "1.2 MB", url: "#" }
      ]
    });
    setModal({ mode: "add", video: null });
  }

  function openEdit(v) {
    setForm({
      code: v.code,
      title: v.title,
      sub: v.sub,
      format: v.format,
      cat1: v.cats[0] || "valuation",
      cat2: v.cats[1] || "",
      speakerName: v.speaker.name,
      speakerRole: v.speaker.title || v.speaker.role || "",
      speakerColor: v.speaker.color || "navy",
      duration: v.duration,
      cleEligible: !!(v.cle && v.cle.eligible),
      cleCredits: v.cle ? v.cle.credits : 1.0,
      cleType: v.cle ? (v.cle.type || "General") : "General",
      blurb: v.blurb || "",
      youtubeId: v.youtubeId || "",
      thumbnailUrl: v.thumbnailUrl || "",
      customResources: v.resources || []
    });
    setModal({ mode: "edit", video: v });
  }

  function handleSave(e) {
    e.preventDefault();

    if (!form.code || !form.title || !form.speakerName) {
      showToast("Please fill in required fields (Code, Title, Speaker)");
      return;
    }

    const cats = [form.cat1];
    if (form.cat2) cats.push(form.cat2);

    const videoObj = {
      id: form.code,
      code: form.code,
      title: form.title,
      sub: form.sub,
      format: form.format,
      cats: cats,
      speaker: {
        name: form.speakerName,
        initials: form.speakerName.split(" ").map((n) => n[0]).join("").slice(0, 2).toUpperCase(),
        role: form.speakerRole,
        color: form.speakerColor
      },
      date: todayLabel(),
      addedOn: todayLabel(),
      duration: Number(form.duration),
      durLabel: form.duration >= 60
        ? `${Math.floor(form.duration / 60)}h ${form.duration % 60 ? (form.duration % 60) + "m" : ""}`
        : `${form.duration}m`,
      cle: {
        eligible: form.cleEligible,
        credits: Number(form.cleCredits),
        type: form.cleEligible ? form.cleType : null,
        accredited: form.cleEligible ? ["OH", "NC", "TX", "FL", "PA"] : []
      },
      views: modal.mode === "add" ? 0 : modal.video.views,
      rating: modal.mode === "add" ? 5.0 : modal.video.rating,
      progress: modal.mode === "add" ? 0 : modal.video.progress,
      attended: modal.mode === "add" ? false : modal.video.attended,
      blurb: form.blurb,
      youtubeId: form.youtubeId || null,
      thumbnailUrl: form.thumbnailUrl || null,
      chapters: modal.mode === "add" ? [
        { t: "00:00", label: "Introduction" },
        { t: "10:00", label: "Core framework" },
        { t: "35:00", label: "Live Q&A" }
      ] : modal.video.chapters,
      resources: form.customResources
    };

    if (modal.mode === "add") {
      setVideos((prev) => [videoObj, ...prev]);
      showToast(`Added ${form.code} to library`);
    } else {
      setVideos((prev) => prev.map((v) => (v.id === modal.video.id ? videoObj : v)));
      showToast(`Updated details for ${form.code}`);
    }

    setModal(null);
  }

  function handleDelete(videoId) {
    if (confirm(`Are you sure you want to delete session ${videoId}?`)) {
      setVideos((prev) => prev.filter((v) => v.id !== videoId));
      showToast(`Deleted ${videoId} from library`);
    }
  }

  return (
    <div className="lc-page">
      <AdminStyles />
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow" style={{ color: "var(--orange)" }}>Administrative Panel</div>
          <h1>Manage Course Library</h1>
          <p className="subtitle">Publish new webinars, modify course details, or manage session collateral.</p>
        </div>
        <div className="header-actions">
          <Button variant="primary" icon="plus" onClick={openAdd}>Publish Session</Button>
        </div>
      </div>

      <div className="lc-toolbar">
        <div className="lc-search-inline">
          <Icon name="search" size={14} />
          <input
            placeholder="Search by title, code or speaker…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </div>

      <div className="admin-table-container">
        <table className="admin-table">
          <thead>
            <tr>
              <th>Code</th>
              <th>Format</th>
              <th>Course Title</th>
              <th>Speaker</th>
              <th>Jurisdictions</th>
              <th>Credits & Type</th>
              <th style={{ textAlign: "right" }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((v) => (
              <tr key={v.id}>
                <td style={{ fontFamily: "var(--font-mono)", fontWeight: 700 }}>{v.code}</td>
                <td>
                  <span className="meta" style={{ textTransform: "capitalize" }}>{v.format}</span>
                </td>
                <td>
                  <div style={{ fontWeight: 600 }}>{v.title}</div>
                  <div style={{ fontSize: 11, color: "var(--grey)" }}>{v.sub}</div>
                </td>
                <td>
                  <div>{v.speaker.name}</div>
                  <div style={{ fontSize: 11, color: "var(--grey)" }}>{v.speaker.role}</div>
                </td>
                <td>
                  <div style={{ fontSize: 11, color: "var(--grey)", display: "flex", gap: 3, flexWrap: "wrap" }}>
                    {v.cle.eligible ? (v.cle.accredited || ["OH", "NC", "TX"]).map((st) => (
                      <span key={st} style={{ background: "var(--grey-100)", padding: "2px 4px", fontSize: 9 }}>{st}</span>
                    )) : "—"}
                  </div>
                </td>
                <td>
                  {v.cle.eligible ? (
                    <div>
                      <b>{v.cle.credits.toFixed(1)}</b> hr · <span style={{ fontSize: 11, textTransform: "uppercase" }}>{v.cle.type}</span>
                    </div>
                  ) : (
                    <span style={{ color: "var(--grey)", fontSize: 12 }}>No credit</span>
                  )}
                </td>
                <td style={{ textAlign: "right" }}>
                  <div style={{ display: "inline-flex", gap: 6 }}>
                    <Button variant="secondary" size="sm" onClick={() => openEdit(v)}>Edit</Button>
                    <Button variant="ghost" size="sm" onClick={() => handleDelete(v.id)} style={{ color: "var(--orange-700)" }}>Delete</Button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {modal ? (
        <div className="admin-modal-backdrop" onClick={() => setModal(null)}>
          <div className="admin-modal" onClick={(e) => e.stopPropagation()}>
            <div className="admin-modal-header">
              <h3>{modal.mode === "add" ? "Publish New Session" : "Edit Session Details"}</h3>
              <button style={{ background: "transparent", border: 0, cursor: "pointer" }} onClick={() => setModal(null)}>
                <Icon name="x" size={16} />
              </button>
            </div>
            <form onSubmit={handleSave}>
              <div className="admin-modal-body">
                <div className="admin-form-2col">
                  <div className="admin-form-group">
                    <label>Course Code *</label>
                    <input
                      type="text"
                      required
                      value={form.code}
                      onChange={(e) => setForm({ ...form, code: e.target.value })}
                      placeholder="e.g. LPE-W19"
                    />
                  </div>
                  <div className="admin-form-group">
                    <label>Format</label>
                    <select
                      value={form.format}
                      onChange={(e) => setForm({ ...form, format: e.target.value })}
                    >
                      <option value="webinar">Webinar</option>
                      <option value="tutorial">Tutorial</option>
                      <option value="session">Recorded session</option>
                    </select>
                  </div>
                </div>

                <div className="admin-form-group">
                  <label>Course Title *</label>
                  <input
                    type="text"
                    required
                    value={form.title}
                    onChange={(e) => setForm({ ...form, title: e.target.value })}
                    placeholder="e.g. Advanced LOI Structuring"
                  />
                </div>

                <div className="admin-form-group">
                  <label>Subtitle / Description snippet</label>
                  <input
                    type="text"
                    value={form.sub}
                    onChange={(e) => setForm({ ...form, sub: e.target.value })}
                    placeholder="e.g. Normalization adjustments, earn-outs and indemnity caps"
                  />
                </div>

                <div className="admin-form-group">
                  <label>YouTube Video ID (Optional)</label>
                  <input
                    type="text"
                    value={form.youtubeId}
                    onChange={(e) => setForm({ ...form, youtubeId: e.target.value })}
                    placeholder="e.g. nlEU_Queiu8 (enables embedded streaming)"
                  />
                </div>

                <div className="admin-form-2col">
                  <div className="admin-form-group">
                    <label>Primary Topic Category</label>
                    <select
                      value={form.cat1}
                      onChange={(e) => setForm({ ...form, cat1: e.target.value })}
                    >
                      {CATEGORIES.map((c) => <option key={c.id} value={c.id}>{c.label}</option>)}
                    </select>
                  </div>
                  <div className="admin-form-group">
                    <label>Secondary Topic (Optional)</label>
                    <select
                      value={form.cat2}
                      onChange={(e) => setForm({ ...form, cat2: e.target.value })}
                    >
                      <option value="">None</option>
                      {CATEGORIES.map((c) => <option key={c.id} value={c.id}>{c.label}</option>)}
                    </select>
                  </div>
                </div>

                <div className="admin-form-2col">
                  <div className="admin-form-group">
                    <label>Speaker Name *</label>
                    <input
                      type="text"
                      required
                      value={form.speakerName}
                      onChange={(e) => setForm({ ...form, speakerName: e.target.value })}
                      placeholder="e.g. Lauren Mason"
                    />
                  </div>
                  <div className="admin-form-group">
                    <label>Speaker Role</label>
                    <input
                      type="text"
                      value={form.speakerRole}
                      onChange={(e) => setForm({ ...form, speakerRole: e.target.value })}
                      placeholder="e.g. Valuation expert"
                    />
                  </div>
                </div>

                <div className="admin-form-2col">
                  <div className="admin-form-group">
                    <label>Duration (minutes)</label>
                    <input
                      type="number"
                      value={form.duration}
                      onChange={(e) => setForm({ ...form, duration: e.target.value })}
                    />
                  </div>
                  <div className="admin-form-group">
                    <label>Speaker Color Tag</label>
                    <select
                      value={form.speakerColor}
                      onChange={(e) => setForm({ ...form, speakerColor: e.target.value })}
                    >
                      <option value="navy">Navy</option>
                      <option value="teal">Teal</option>
                      <option value="gold">Gold</option>
                    </select>
                  </div>
                </div>

                <div style={{ borderTop: "1px solid var(--grey-100)", paddingTop: "14px", marginTop: "10px" }}>
                  <div className="admin-form-group">
                    <label className="admin-form-checkbox">
                      <input
                        type="checkbox"
                        checked={form.cleEligible}
                        onChange={(e) => setForm({ ...form, cleEligible: e.target.checked })}
                      />
                      Eligible for CLE credit
                    </label>
                  </div>

                  {form.cleEligible ? (
                    <div className="admin-form-2col">
                      <div className="admin-form-group">
                        <label>CLE Credit Hours</label>
                        <input
                          type="number"
                          step="0.1"
                          value={form.cleCredits}
                          onChange={(e) => setForm({ ...form, cleCredits: e.target.value })}
                        />
                      </div>
                      <div className="admin-form-group">
                        <label>CLE Category Type</label>
                        <select
                          value={form.cleType}
                          onChange={(e) => setForm({ ...form, cleType: e.target.value })}
                        >
                          <option value="General">General</option>
                          <option value="Ethics">Ethics</option>
                        </select>
                      </div>
                    </div>
                  ) : null}
                </div>

                 <div className="admin-form-group">
                  <label>Session Abstract (Blurb)</label>
                  <textarea
                    rows="3"
                    value={form.blurb}
                    onChange={(e) => setForm({ ...form, blurb: e.target.value })}
                    placeholder="Provide a detailed outline of what this course covers..."
                  />
                </div>

                <div className="admin-form-group" style={{ borderTop: "1px solid var(--grey-100)", paddingTop: "14px", marginTop: "14px" }}>
                  <label>Course Thumbnail Image</label>
                  <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 6 }}>
                    <div style={{
                      width: 80,
                      height: 50,
                      backgroundImage: form.thumbnailUrl ? `url(${form.thumbnailUrl})` : "none",
                      backgroundSize: "cover",
                      backgroundPosition: "center",
                      backgroundColor: "var(--cream-2)",
                      border: "1px solid var(--grey-200)",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      flexShrink: 0
                    }}>
                      {!form.thumbnailUrl && <Icon name="video" size={16} style={{ color: "var(--grey)" }} />}
                    </div>
                    <div style={{ flex: 1 }}>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => {
                          const file = e.target.files[0];
                          if (file) {
                            const reader = new FileReader();
                            reader.onload = (evt) => {
                              setForm({ ...form, thumbnailUrl: evt.target.result });
                            };
                            reader.readAsDataURL(file);
                          }
                        }}
                      />
                      <p style={{ margin: "4px 0 0 0", fontSize: 11, color: "var(--grey)" }}>
                        Upload PNG/JPG to display a custom course card thumbnail.
                      </p>
                    </div>
                  </div>
                </div>

                <div className="admin-form-group" style={{ borderTop: "1px solid var(--grey-100)", paddingTop: "14px", marginTop: "14px" }}>
                  <label>Session Collateral / Handouts (PDF)</label>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 6 }}>
                    {(form.customResources || []).map((res, index) => (
                      <div key={index} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--cream-2)", padding: "6px 10px", border: "1px solid var(--grey-200)", fontSize: 12 }}>
                        <span><b>{res.name}</b> ({res.type} · {res.size})</span>
                        <button type="button" style={{ color: "var(--orange-700)", border: 0, background: "transparent", cursor: "pointer", fontSize: 12 }}
                          onClick={() => {
                            setForm({ ...form, customResources: form.customResources.filter((_, idx) => idx !== index) });
                          }}>
                          Remove
                        </button>
                      </div>
                    ))}
                    <div style={{ marginTop: 4 }}>
                      <input
                        type="file"
                        accept="application/pdf"
                        onChange={(e) => {
                          const file = e.target.files[0];
                          if (file) {
                            const reader = new FileReader();
                            reader.onload = (evt) => {
                              const newRes = {
                                name: file.name.replace(/\.[^/.]+$/, ""),
                                type: "PDF",
                                size: (file.size / 1024 / 1024).toFixed(1) + " MB",
                                url: evt.target.result
                              };
                              setForm({ ...form, customResources: [...(form.customResources || []), newRes] });
                            };
                            reader.readAsDataURL(file);
                          }
                        }}
                      />
                    </div>
                  </div>
                </div>
              </div>
              <div className="admin-modal-footer">
                <Button variant="ghost" onClick={() => setModal(null)}>Cancel</Button>
                <Button variant="primary" type="submit">
                  {modal.mode === "add" ? "Publish Session" : "Save Changes"}
                </Button>
              </div>
            </form>
          </div>
        </div>
      ) : null}
    </div>
  );
}

// -------------------------------------------------------------
// 4. Admin Learners Directory Screen
// -------------------------------------------------------------
function AdminLearnersScreen({ learners, setLearners, showToast, onDeleteLearner }) {
  const learnersArr = learners || [];
  function toggleVerification(learnerId) {
    setLearners((prev) =>
      (prev || []).map((l) => {
        if (l.id === learnerId) {
          const newStatus = !l.onboarded;
          showToast(`${l.name} is now ${newStatus ? "verified" : "unverified"}`);
          return { ...l, onboarded: newStatus };
        }
        return l;
      })
    );
  }

  return (
    <div className="lc-page">
      <AdminStyles />
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow" style={{ color: "var(--orange)" }}>Administrative Panel</div>
          <h1>Learners Directory</h1>
          <p className="subtitle">View member profiles, verify bar numbers, and manage LMS application access.</p>
        </div>
      </div>

      <div className="admin-table-container">
        <table className="admin-table">
          <thead>
            <tr>
              <th>Member</th>
              <th>Firm & Role</th>
              <th>Email</th>
              <th>Bar State & No</th>
              <th>Member since</th>
              <th>CLE Credits Logged</th>
              <th>Access status</th>
              <th style={{ textAlign: "right" }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {learnersArr.map((l) => (
              <tr key={l.id}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <Av initials={l.initials} size={28} />
                    <div style={{ fontWeight: 600 }}>{l.name}</div>
                  </div>
                </td>
                <td>
                  <div>{l.firm}</div>
                  <div style={{ fontSize: 11, color: "var(--grey)" }}>{l.role}</div>
                </td>
                <td style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{l.email}</td>
                <td>
                  <div>{l.barState}</div>
                  <div style={{ fontSize: 11, color: "var(--grey)", fontFamily: "var(--font-mono)" }}>{l.barNo}</div>
                </td>
                <td>{l.memberSince}</td>
                 <td>
                   <div><b>{(l.totalCredits || 0).toFixed(1)}</b> CLE hrs</div>
                   <div style={{ fontSize: 11, color: "var(--grey)" }}>{l.totalMinutesWatched || 0} min watched</div>
                 </td>
                <td>
                  <span className={cx("admin-badge", l.onboarded ? "approved" : "pending")}>
                    {l.onboarded ? "Verified" : "Unverified"}
                  </span>
                </td>
                <td style={{ textAlign: "right" }}>
                  <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
                    <Button variant="secondary" size="sm" onClick={() => toggleVerification(l.id)}>
                      {l.onboarded ? "Revoke Access" : "Verify Bar No"}
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => {
                      if (confirm(`Are you sure you want to permanently delete user ${l.name}? This will remove all their course completions and progress records.`)) {
                        onDeleteLearner(l.id);
                      }
                    }} style={{ color: "var(--orange-700)" }}>
                      Delete
                    </Button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// -------------------------------------------------------------
// 5. Admin Live Event Registrations Screen
// -------------------------------------------------------------
function AdminEventsScreen({ learners, showToast }) {
  const learnersArr = learners || [];
  const events = window.UPCOMING_LIVE || [];

  // Group registrants by event ID
  const registrantsByEvent = {};
  events.forEach(evt => {
    registrantsByEvent[evt.id] = learnersArr.filter(l => 
      l.registered && l.registered.includes(evt.id)
    );
  });

  return (
    <div className="lc-page">
      <AdminStyles />
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow" style={{ color: "var(--orange)" }}>Administrative Panel</div>
          <h1>Live Event Registrations</h1>
          <p className="subtitle">View and manage member registrations for upcoming live webinars.</p>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 30 }}>
        {events.map(evt => {
          const registrants = registrantsByEvent[evt.id] || [];
          const dateStr = new Date(evt.startISO).toLocaleDateString("en-US", {
            weekday: "long",
            month: "long",
            day: "numeric",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit"
          });

          return (
            <div key={evt.id} style={{
              background: "var(--white)",
              border: "1px solid var(--grey-200)",
              borderRadius: 6,
              padding: 24,
              boxShadow: "0 2px 8px rgba(0,0,0,0.02)"
            }}>
              {/* Event Header Info */}
              <div style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "flex-start",
                borderBottom: "1px solid var(--grey-100)",
                paddingBottom: 16,
                marginBottom: 16,
                flexWrap: "wrap",
                gap: 12
              }}>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                    <span className="admin-badge approved" style={{ background: "rgba(228, 116, 37, 0.1)", color: "var(--orange)" }}>
                      {evt.code}
                    </span>
                    <span style={{ fontSize: 13, color: "var(--grey)", fontWeight: 500 }}>
                      {dateStr} ({evt.timezone})
                    </span>
                  </div>
                  <h2 style={{ fontSize: 20, fontWeight: 700, color: "var(--navy)", margin: "4px 0" }}>
                    {evt.title}
                  </h2>
                  <p style={{ fontSize: 14, color: "var(--grey)", margin: 0 }}>
                    Presenter: <b>{evt.speaker.name}</b> ({evt.speaker.role}) · {evt.durLabel} · {evt.cle.credits} CLE credit ({evt.cle.type})
                  </p>
                </div>
                <div style={{
                  background: "var(--navy-900)",
                  color: "var(--white)",
                  padding: "10px 18px",
                  borderRadius: 4,
                  textAlign: "center",
                  minWidth: 100
                }}>
                  <div style={{ fontSize: 24, fontWeight: 700 }}>{registrants.length}</div>
                  <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.1em", opacity: 0.8 }}>
                    Registrants
                  </div>
                </div>
              </div>

              {/* Registrants Table */}
              {registrants.length > 0 ? (
                <div className="admin-table-container" style={{ margin: 0, boxShadow: "none", border: 0 }}>
                  <table className="admin-table">
                    <thead>
                      <tr>
                        <th>Member</th>
                        <th>Firm & Role</th>
                        <th>Email</th>
                        <th>Bar State & No</th>
                        <th>Status</th>
                      </tr>
                    </thead>
                    <tbody>
                      {registrants.map(l => (
                        <tr key={l.id}>
                          <td>
                            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                              <Av initials={l.initials} size={28} />
                              <div style={{ fontWeight: 600 }}>{l.name}</div>
                            </div>
                          </td>
                          <td>
                            <div>{l.firm}</div>
                            <div style={{ fontSize: 11, color: "var(--grey)" }}>{l.role}</div>
                          </td>
                          <td style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{l.email}</td>
                          <td>
                            <div>{l.barState}</div>
                            <div style={{ fontSize: 11, color: "var(--grey)", fontFamily: "var(--font-mono)" }}>{l.barNo || "N/A"}</div>
                          </td>
                          <td>
                            <span className={cx("admin-badge", l.onboarded ? "approved" : "pending")}>
                              {l.onboarded ? "Verified" : "Unverified"}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div style={{
                  padding: "30px 20px",
                  textAlign: "center",
                  background: "var(--grey-50)",
                  borderRadius: 4,
                  color: "var(--grey)"
                }}>
                  <Icon name="calendar" size={32} style={{ marginBottom: 8, opacity: 0.6 }} />
                  <p style={{ margin: 0, fontSize: 14 }}>No registered attendees for this live event yet.</p>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Assign components to the window context so app.jsx can access them.
Object.assign(window, {
  AdminDashboardScreen,
  AdminCleScreen,
  AdminCoursesScreen,
  AdminLearnersScreen,
  AdminEventsScreen
});
