// ImprovementView — shows session progress, topic breakdown, accuracy trend
// Pro users see full history; free users see last 3 sessions + upgrade gate

const API_BASE = "https://api.usegreenroom.app";

function ImprovementView({ token, subscriptionPlan = "free", onUpgrade, darkMode = false }) {
  // Payments hidden: treat every user as having full access when there is no
  // upgrade path. This removes the locked-session blur overlay and the Pro CTA.
  const isPro = subscriptionPlan !== "free" || !onUpgrade;
  const [sessions,  setSessions]  = React.useState([]);
  const [loading,   setLoading]   = React.useState(true);
  const [error,     setError]     = React.useState(false);

  function loadSessions() {
    if (!token) { setLoading(false); return; }
    setLoading(true);
    setError(false);
    fetch(`${API_BASE}/api/history`, { headers: { Authorization: `Bearer ${token}` } })
      .then(r => { if (!r.ok) throw new Error(r.status); return r.json(); })
      .then(data => { setSessions(Array.isArray(data) ? data : []); setLoading(false); })
      .catch(() => { setError(true); setLoading(false); });
  }

  React.useEffect(() => { loadSessions(); }, [token]);

  const T = darkMode ? {
    bg: "#151618", surface: "rgba(255,255,255,.05)", border: "rgba(255,255,255,.08)",
    text1: "#f3f4f6", text2: "#b0b5be", text3: "#7d838e",
    track: "rgba(255,255,255,.06)", lock: "rgba(255,255,255,.03)",
  } : {
    bg: "#f4f5f7", surface: "#fff", border: "rgba(0,0,0,.08)",
    text1: "#0a0a0b", text2: "#52525b", text3: "#a1a1aa",
    track: "rgba(0,0,0,.06)", lock: "#f8f8f7",
  };

  // Helpers
  function fmt(iso) {
    const d = new Date(iso);
    return isNaN(d.getTime()) ? "—" : d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  }
  function accuracyColor(v) {
    if (!v) return T.text3;
    if (v >= 4) return "#15803d";
    if (v >= 3) return "#d97706";
    return "#dc2626";
  }
  function accuracyLabel(v) {
    return ["","Way off","Partially right","Mostly right","Pretty accurate","Spot on"][v] || "—";
  }

  // Visible sessions — free users see 5, pro see all
  const visible    = isPro ? sessions : sessions.slice(0, 5);
  const locked     = isPro ? [] : sessions.slice(5);
  const rated      = sessions.filter(s => s.accuracy_rating);
  const avgAccuracy = rated.length
    ? (rated.reduce((a, s) => a + s.accuracy_rating, 0) / rated.length).toFixed(1)
    : null;

  // Role breakdown
  const byRole = {};
  sessions.forEach(s => {
    const r = s.role || "Unknown";
    if (!byRole[r]) byRole[r] = { count: 0, accuracy: [] };
    byRole[r].count++;
    if (s.accuracy_rating) byRole[r].accuracy.push(s.accuracy_rating);
  });
  const roles = Object.entries(byRole)
    .map(([role, d]) => ({
      role,
      count: d.count,
      avg: d.accuracy.length ? (d.accuracy.reduce((a, b) => a + b, 0) / d.accuracy.length).toFixed(1) : null,
    }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 5);

  // Accuracy trend (chronological, only rated sessions)
  const trend = [...rated].reverse().slice(-12);

  if (loading) return (
    <div style={{ padding: 48, textAlign: "center", color: T.text3, font: "14px var(--font-sans)" }}>
      Loading progress…
    </div>
  );

  if (error) return (
    <div data-screen-label="Progress" style={{ minHeight: "100vh", background: T.bg }}>
      <header style={{ padding: "20px 32px", borderBottom: `1px solid ${T.border}` }}>
        <div style={{ font: "600 24px var(--font-sans)", letterSpacing: "-0.015em", color: T.text1 }}>Your progress</div>
      </header>
      <div style={{ padding: 64, textAlign: "center" }}>
        <div style={{ font: "500 16px var(--font-sans)", color: T.text2, marginBottom: 8 }}>Couldn't load sessions</div>
        <div style={{ font: "14px var(--font-sans)", color: T.text3, marginBottom: 20 }}>The backend may be waking up — this usually takes 30–60 seconds.</div>
        <button onClick={loadSessions} style={{
          padding: "9px 20px", borderRadius: 10, border: `1px solid ${T.border}`,
          background: "transparent", color: T.text2, font: "500 13px var(--font-sans)", cursor: "pointer",
        }}>Retry</button>
      </div>
    </div>
  );

  if (sessions.length === 0) return (
    <div data-screen-label="Progress" style={{ minHeight: "100vh", background: T.bg }}>
      <header style={{ padding: "20px 32px", borderBottom: `1px solid ${T.border}` }}>
        <div style={{ font: "600 24px var(--font-sans)", letterSpacing: "-0.015em", color: T.text1 }}>Your progress</div>
      </header>
      <div style={{ padding: 64, textAlign: "center" }}>
        <div style={{ font: "500 16px var(--font-sans)", color: T.text2, marginBottom: 8 }}>No sessions yet</div>
        <div style={{ font: "14px var(--font-sans)", color: T.text3 }}>Complete your first mock interview to start tracking progress.</div>
      </div>
    </div>
  );

  return (
    <div data-screen-label="Progress" style={{ minHeight: "100vh", background: T.bg }}>
      <header style={{ padding: "20px 32px", borderBottom: `1px solid ${T.border}`, background: T.surface }}>
        <div style={{ font: "600 24px var(--font-sans)", letterSpacing: "-0.015em", color: T.text1, marginBottom: 2 }}>Your progress</div>
        <div style={{ font: "13px var(--font-sans)", color: T.text3 }}>{sessions.length} session{sessions.length !== 1 ? "s" : ""} recorded</div>
      </header>

      <main style={{ padding: "28px 32px", display: "flex", flexDirection: "column", gap: 24 }}>

        {/* ── Stat row ── */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16 }}>
          {[
            { label: "Total sessions",    value: sessions.length,                             mono: true },
            { label: "Sessions rated",    value: `${rated.length} of ${sessions.length}`,    mono: false },
            { label: "Avg accuracy",      value: avgAccuracy ? `${avgAccuracy}/5` : "—",      mono: true, color: avgAccuracy >= 4 ? "#15803d" : avgAccuracy >= 3 ? "#d97706" : T.text1 },
            { label: "Roles practiced",   value: Object.keys(byRole).length,                  mono: true },
          ].map(({ label, value, mono, color }) => (
            <div key={label} style={{ padding: "20px", background: T.surface, border: `1px solid ${T.border}`, borderRadius: 14 }}>
              <div style={{ font: "11px var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.06em", color: T.text3, marginBottom: 10 }}>{label}</div>
              <div style={{ font: `700 28px ${mono ? "var(--font-mono)" : "var(--font-sans)"}`, color: color || T.text1, letterSpacing: "-0.02em" }}>{value}</div>
            </div>
          ))}
        </div>

        {/* ── Accuracy trend chart ── */}
        {trend.length >= 2 && (
          <div style={{ padding: 24, background: T.surface, border: `1px solid ${T.border}`, borderRadius: 14 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
              <div style={{ font: "500 14px var(--font-sans)", color: T.text1 }}>Accuracy over time</div>
              <div style={{ font: "12px var(--font-sans)", color: T.text3 }}>How accurately Ari assessed your actual knowledge (1–5)</div>
            </div>
            <div style={{ position: "relative", height: 80 }}>
              {/* Y-axis labels */}
              {[1,2,3,4,5].map(v => (
                <div key={v} style={{
                  position: "absolute", left: 0, top: `${(1 - (v - 1) / 4) * 100}%`,
                  transform: "translateY(-50%)", font: "10px var(--font-mono)", color: T.text3,
                  width: 14, textAlign: "right",
                }}>{v}</div>
              ))}
              {/* Chart area */}
              <svg style={{ position: "absolute", left: 20, right: 0, top: 0, bottom: 0, width: "calc(100% - 20px)", height: "100%", overflow: "visible" }}>
                {(() => {
                  const w = 100, h = 100;
                  const xs = trend.map((_, i) => (i / Math.max(trend.length - 1, 1)) * 100);
                  const ys = trend.map(s => (1 - (s.accuracy_rating - 1) / 4) * h);
                  const path = xs.map((x, i) => `${i === 0 ? "M" : "L"}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(" ");
                  const fill = `${path} L${xs[xs.length-1].toFixed(1)},100 L0,100 Z`;
                  return (
                    <>
                      <defs>
                        <linearGradient id="acc-grad" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="0%" stopColor="#15803d" stopOpacity="0.18" />
                          <stop offset="100%" stopColor="#15803d" stopOpacity="0" />
                        </linearGradient>
                      </defs>
                      <path d={fill} fill="url(#acc-grad)" />
                      <path d={path} fill="none" stroke="#15803d" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                      {xs.map((x, i) => (
                        <g key={i}>
                          <circle cx={`${x}%`} cy={`${ys[i]}%`} r="4" fill="#15803d" />
                          <title>{fmt(trend[i].created_at)} · {accuracyLabel(trend[i].accuracy_rating)}</title>
                        </g>
                      ))}
                    </>
                  );
                })()}
              </svg>
            </div>
            {/* X-axis dates */}
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, paddingLeft: 20 }}>
              <span style={{ font: "10px var(--font-sans)", color: T.text3 }}>{fmt(trend[0].created_at)}</span>
              <span style={{ font: "10px var(--font-sans)", color: T.text3 }}>{fmt(trend[trend.length - 1].created_at)}</span>
            </div>
          </div>
        )}

        {/* ── Two-column: session timeline + role breakdown ── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 16, alignItems: "start" }}>

          {/* Session timeline */}
          <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 14, overflow: "hidden" }}>
            <div style={{ padding: "14px 20px", borderBottom: `1px solid ${T.border}`, font: "500 13px var(--font-sans)", color: T.text1 }}>
              Sessions
            </div>

            {visible.map((s, i) => {
              const acc = s.accuracy_rating;
              const dot = acc >= 4 ? "#15803d" : acc >= 3 ? "#d97706" : acc ? "#dc2626" : T.text3;
              return (
                <div key={s.id} style={{
                  padding: "14px 20px",
                  borderBottom: i < visible.length - 1 || locked.length > 0 ? `1px solid ${T.border}` : "none",
                  display: "grid", gridTemplateColumns: "64px 1fr 1fr 120px",
                  alignItems: "center", gap: 12,
                }}>
                  <span style={{ font: "12px var(--font-mono)", color: T.text3 }}>{fmt(s.created_at)}</span>
                  <div>
                    <div style={{ font: "500 13px var(--font-sans)", color: T.text1 }}>{s.role || "—"}</div>
                    <div style={{ font: "12px var(--font-sans)", color: T.text3 }}>{s.questions_covered} questions</div>
                  </div>
                  <div style={{ font: "12px/1.5 var(--font-sans)", color: T.text2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {s.summary ? s.summary.slice(0, 80) + (s.summary.length > 80 ? "…" : "") : "—"}
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, justifyContent: "flex-end" }}>
                    {acc && (
                      <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
                        <div style={{ width: 8, height: 8, borderRadius: 99, background: dot }} />
                        <span style={{ font: "12px var(--font-sans)", color: dot }}>{accuracyLabel(acc)}</span>
                      </span>
                    )}
                    {!acc && <span style={{ font: "12px var(--font-sans)", color: T.text3 }}>No rating</span>}
                  </div>
                </div>
              );
            })}

            {/* Pro gate — locked sessions */}
            {locked.length > 0 && (
              <div style={{ position: "relative" }}>
                {locked.slice(0, 3).map((s, i) => (
                  <div key={s.id} style={{
                    padding: "14px 20px", filter: "blur(4px)", pointerEvents: "none", userSelect: "none",
                    borderBottom: `1px solid ${T.border}`,
                    display: "grid", gridTemplateColumns: "64px 1fr 1fr 120px", gap: 12, alignItems: "center",
                    background: T.lock, opacity: 0.5,
                  }}>
                    <span style={{ font: "12px var(--font-mono)", color: T.text3 }}>{fmt(s.created_at)}</span>
                    <div style={{ font: "500 13px var(--font-sans)", color: T.text1 }}>{s.role}</div>
                    <div style={{ font: "12px var(--font-sans)", color: T.text2 }}>████████████</div>
                    <div />
                  </div>
                ))}
                <div style={{
                  position: "absolute", inset: 0, display: "flex", flexDirection: "column",
                  alignItems: "center", justifyContent: "center", gap: 12,
                  background: darkMode ? "rgba(21,22,24,0.82)" : "rgba(255,255,255,0.82)",
                  backdropFilter: "blur(2px)",
                }}>
                  <div style={{ font: "500 14px var(--font-sans)", color: T.text1 }}>
                    +{locked.length} more session{locked.length !== 1 ? "s" : ""} hidden
                  </div>
                  <div style={{ font: "13px var(--font-sans)", color: T.text3, marginBottom: 4 }}>
                    Upgrade to Pro to see your full history and progress
                  </div>
                  <button onClick={() => onUpgrade?.("pro")} style={{
                    padding: "9px 20px", borderRadius: 10, border: "none", cursor: "pointer",
                    background: "var(--gr-green-500)", color: "#fff", font: "600 13px var(--font-sans)",
                  }}>
                    Unlock full history — $15/mo
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Role breakdown */}
          <div style={{ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 14, overflow: "hidden" }}>
            <div style={{ padding: "14px 20px", borderBottom: `1px solid ${T.border}`, font: "500 13px var(--font-sans)", color: T.text1 }}>
              By role
            </div>
            {roles.map(({ role, count, avg }) => {
              const pct = Math.round((count / sessions.length) * 100);
              return (
                <div key={role} style={{ padding: "14px 20px", borderBottom: `1px solid ${T.border}` }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                    <span style={{ font: "500 13px var(--font-sans)", color: T.text1 }}>{role}</span>
                    <span style={{ font: "12px var(--font-mono)", color: T.text3 }}>{count}x</span>
                  </div>
                  <div style={{ height: 4, background: T.track, borderRadius: 2, overflow: "hidden", marginBottom: 6 }}>
                    <div style={{ width: `${pct}%`, height: "100%", background: "var(--gr-green-500)", borderRadius: 2 }} />
                  </div>
                  {avg && (
                    <div style={{ font: "11px var(--font-sans)", color: accuracyColor(parseFloat(avg)) }}>
                      avg accuracy {avg}/5
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Pro gate message for full GitHub insights */}
        {!isPro && (
          <div style={{
            padding: 24, background: T.surface, border: `1px solid ${T.border}`,
            borderRadius: 14, display: "flex", alignItems: "center", justifyContent: "space-between",
          }}>
            <div>
              <div style={{ font: "500 14px var(--font-sans)", color: T.text1, marginBottom: 4 }}>
                Pro: cross-session GitHub insights
              </div>
              <div style={{ font: "13px var(--font-sans)", color: T.text3 }}>
                See which repos come up most, which topics you keep struggling with, and get questions that go deeper each session.
              </div>
            </div>
            <button onClick={() => onUpgrade?.("pro")} style={{
              padding: "10px 20px", borderRadius: 10, border: "none", cursor: "pointer", flexShrink: 0, marginLeft: 24,
              background: "var(--gr-green-500)", color: "#fff", font: "600 13px var(--font-sans)",
            }}>
              Upgrade to Pro
            </button>
          </div>
        )}

      </main>
    </div>
  );
}

window.ImprovementView = ImprovementView;
