/* global React, adStyles, fmtDuration, fmtWhen */
/* Admin dashboard — analytics view for the N Brown × Klaviyo microsite */

const { useState, useEffect, useMemo } = React;

function useSessions() {
  const [sessions, setSessions] = useState(() => {
    try {return JSON.parse(localStorage.getItem("nb-analytics-sessions-v1") || "[]");}
    catch (_) {return [];}
  });
  useEffect(() => {
    const reload = () => {
      try {setSessions(JSON.parse(localStorage.getItem("nb-analytics-sessions-v1") || "[]"));}
      catch (_) {}
    };
    const t = setInterval(reload, 4000);
    window.addEventListener("focus", reload);
    return () => {clearInterval(t);window.removeEventListener("focus", reload);};
  }, []);
  return [sessions, setSessions];
}

function aggregateBySection(sessions) {
  const totals = {};
  const labels = {};
  sessions.forEach((s) => {
    const sm = s.sectionMs || {};
    const sl = s.sectionLabels || {};
    Object.keys(sm).forEach((k) => {
      totals[k] = (totals[k] || 0) + sm[k];
      labels[k] = sl[k] || labels[k] || k;
    });
  });
  return Object.keys(totals).
  map((k) => ({ id: k, label: labels[k] || k, ms: totals[k] })).
  sort((a, b) => b.ms - a.ms);
}

function uniqueVisitors(sessions) {
  const set = new Set();
  sessions.filter((s) => s.role !== "admin").forEach((s) => set.add((s.email || "").toLowerCase()));
  return set.size;
}

function activeNow(sessions) {
  const cutoff = Date.now() - 5 * 60 * 1000;
  return sessions.filter((s) => s.role !== "admin" && (s.lastSeenAt || 0) > cutoff).length;
}

function topSectionsFor(s) {
  const sm = s.sectionMs || {};
  const sl = s.sectionLabels || {};
  return Object.keys(sm).
  map((k) => ({ id: k, label: sl[k] || k, ms: sm[k] })).
  sort((a, b) => b.ms - a.ms).
  slice(0, 3);
}

function toCSV(sessions) {
  const rows = [["email", "role", "login_at", "last_seen_at", "total_seconds", "section_breakdown"]];
  sessions.forEach((s) => {
    const breakdown = Object.keys(s.sectionMs || {}).
    map((k) => (s.sectionLabels && s.sectionLabels[k] || k) + ":" + Math.round((s.sectionMs[k] || 0) / 1000) + "s").
    join(" | ");
    rows.push([
    s.email || "",
    s.role || "viewer",
    new Date(s.loginAt || 0).toISOString(),
    new Date(s.lastSeenAt || 0).toISOString(),
    Math.round((s.totalMs || 0) / 1000),
    breakdown]);

  });
  return rows.map((r) => r.map((c) => '"' + String(c).replace(/"/g, '""') + '"').join(",")).join("\n");
}

function downloadCSV(sessions) {
  const blob = new Blob([toCSV(sessions)], { type: "text/csv" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "nbrown-klaviyo-microsite-analytics-" + new Date().toISOString().slice(0, 10) + ".csv";
  document.body.appendChild(a);a.click();a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

function AdminDashboard() {
  const [sessions, setSessions] = useSessions();
  const viewerSessions = useMemo(() => sessions.filter((s) => s.role !== "admin"), [sessions]);
  const sectionTotals = useMemo(() => aggregateBySection(viewerSessions), [viewerSessions]);
  const topSectionMs = sectionTotals[0] ? sectionTotals[0].ms : 1;
  const totalMs = viewerSessions.reduce((a, s) => a + (s.totalMs || 0), 0);

  const sortedSessions = useMemo(
    () => [...viewerSessions].sort((a, b) => (b.lastSeenAt || 0) - (a.lastSeenAt || 0)),
    [viewerSessions]
  );

  const exitMicrosite = () => {
    window.location.hash = "microsite";
    window.location.reload();
  };

  const seedDemo = () => {
    if (window.__nbAnalytics && window.__nbAnalytics.seedDemo) {
      window.__nbAnalytics.seedDemo();
      try {setSessions(JSON.parse(localStorage.getItem("nb-analytics-sessions-v1") || "[]"));} catch (_) {}
    }
  };

  const clearAll = () => {
    if (!window.confirm("Clear ALL recorded sessions? This cannot be undone.")) return;
    if (window.__nbAnalytics) window.__nbAnalytics.clear();
    setSessions([]);
  };

  return (
    <div style={adStyles.shell}>
      <div style={adStyles.topbar}>
        <div style={adStyles.brand}>
          <div style={adStyles.mark}>N</div>
          <div>
            <div style={adStyles.brandT}>Brown × Klaviyo · <span className="serif-i">Admin</span></div>
            <div style={adStyles.brandS}>Microsite analytics</div>
          </div>
        </div>
        <div style={adStyles.topActions}>
          <button style={adStyles.btn} onClick={seedDemo}>Seed demo data</button>
          <button style={adStyles.btn} onClick={clearAll}>Clear data</button>
          <button style={adStyles.btn} onClick={() => downloadCSV(viewerSessions)}>Export CSV</button>
          <button style={{ ...adStyles.btn, ...adStyles.btnPrimary }} onClick={exitMicrosite}>View microsite →</button>
        </div>
      </div>

      <div style={adStyles.hero}>
        <div style={adStyles.eyebrow}>● Admin · live</div>
        <h1 style={adStyles.h1}>Who's reading the <span className="serif-i" style={{ color: "#F4ABFF" }}>response</span>.</h1>
        <p style={adStyles.sub}>
          Every gated entry — email, login time, and time spent in each section
          — is captured here. Use this to see which chapters of the microsite
          are landing, who's coming back, and where to follow up.
        </p>
      </div>

      <div style={adStyles.kpiRow}>
        <Kpi label="Total visitors" value={uniqueVisitors(viewerSessions)} sub="Unique work emails" />
        <Kpi label="Sessions" value={viewerSessions.length} sub="Including repeat visits" />
        <Kpi label="Reading time" value={fmtDuration(totalMs)} sub="Combined dwell time" />
        <Kpi label="Active now" value={activeNow(sessions)} sub="Seen in the last 5 min" highlight />
      </div>

      <SectionPanel
        title="Where time is being spent"
        sub="Aggregate dwell time per chapter across all visitors">

        {sectionTotals.length === 0 ?
        <EmptyState /> :

        sectionTotals.map((row, i) =>
        <div key={row.id} style={{ ...adStyles.barRow, ...(i === 0 ? adStyles.barRowFirst : {}) }}>
              <div style={adStyles.barLabel}>{row.label}</div>
              <div style={adStyles.barBg}>
                <div style={{ ...adStyles.barFill, width: row.ms / topSectionMs * 100 + "%" }} />
              </div>
              <div style={adStyles.barVal}>{fmtDuration(row.ms)}</div>
            </div>
        )

        }
      </SectionPanel>

      <SectionPanel
        title="Visitor activity"
        sub={sortedSessions.length + " session" + (sortedSessions.length === 1 ? "" : "s")}>

        {sortedSessions.length === 0 ?
        <EmptyState /> :

        <table style={adStyles.table}>
            <thead>
              <tr>
                <th style={adStyles.th}>Visitor</th>
                <th style={adStyles.th}>Logged in</th>
                <th style={adStyles.th}>Last seen</th>
                <th style={adStyles.th}>Time on site</th>
                <th style={adStyles.th}>Top sections</th>
              </tr>
            </thead>
            <tbody>
              {sortedSessions.map((s) =>
            <tr key={s.id}>
                  <td style={adStyles.td}>
                    <div style={adStyles.emailCell}>
                      <span style={adStyles.emailMain}>{s.email}</span>
                      <span style={adStyles.emailMeta}>
                        {s.tz || "—"}{s.lang ? " · " + s.lang : ""}
                      </span>
                    </div>
                  </td>
                  <td style={adStyles.td}>
                    <div>{fmtWhen(s.loginAt)}</div>
                    <div style={adStyles.emailMeta}>
                      {new Date(s.loginAt).toLocaleString("en-GB", { hour: "2-digit", minute: "2-digit", day: "numeric", month: "short" })}
                    </div>
                  </td>
                  <td style={adStyles.td}>{fmtWhen(s.lastSeenAt)}</td>
                  <td style={adStyles.td}>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 18, color: "#F4ABFF" }}>{fmtDuration(s.totalMs)}</div>
                  </td>
                  <td style={adStyles.td}>
                    <div style={adStyles.topSections}>
                      {topSectionsFor(s).map((t) =>
                  <span key={t.id} style={adStyles.topChip} title={t.label + " · " + fmtDuration(t.ms)}>
                          {t.label} · {fmtDuration(t.ms)}
                        </span>
                  )}
                      {topSectionsFor(s).length === 0 && <span style={adStyles.emailMeta}>No section data yet</span>}
                    </div>
                  </td>
                </tr>
            )}
            </tbody>
          </table>
        }
      </SectionPanel>

      <div style={adStyles.footnote}>
        <div style={adStyles.footnoteT}>How sharing & tracking works</div>
        Visitors enter their work email and the access code <strong>InnovatingCRM</strong>.
        Their session — login time, time per chapter — is recorded on this device's
        local store. To collect analytics across <strong>all</strong> visitors in one
        place, host the microsite behind a small backend (Cloudflare Worker, Vercel
        Edge, or similar) and POST these same events to it. The schema is already
        wired and exportable as CSV.
      </div>
    </div>);

}

function Kpi({ label, value, sub, highlight }) {
  return (
    <div style={{ ...adStyles.kpi, ...(highlight ? { borderColor: "rgba(217,70,239,0.5)", background: "rgba(217,70,239,0.06)" } : {}) }}>
      <div style={adStyles.kpiLab}>{label}</div>
      <div style={{ ...adStyles.kpiVal, color: highlight ? "#F4ABFF" : "#F6F4EF" }}>{value}</div>
      <div style={adStyles.kpiSub}>{sub}</div>
    </div>);

}

function SectionPanel({ title, sub, children }) {
  return (
    <div style={adStyles.panel}>
      <div style={adStyles.panelHead}>
        <h2 style={adStyles.panelT}>{title}</h2>
        <span style={adStyles.panelS}>{sub}</span>
      </div>
      {children}
    </div>);

}

function EmptyState() {
  return (
    <div style={adStyles.empty}>
      <div style={adStyles.emptyT}>No visits recorded yet.</div>
      <div>Share the microsite with a stakeholder and their first session will appear here.</div>
      <div style={{ marginTop: 16, fontSize: 12 }}>
        Tap <strong>Seed demo data</strong> above to populate a realistic sample.
      </div>
    </div>);

}

window.AdminDashboard = AdminDashboard;
