const RANGE_OPTS = [
  { v: "month",    l: "This month" },
  { v: "semester", l: "This semester" },
  { v: "year",     l: "This school year" },
  { v: "all",      l: "All time" },
];
const DIM_OPTS = [
  { v: "month",    l: "By month" },
  { v: "semester", l: "By semester" },
  { v: "grade",    l: "By grade level" },
  { v: "type",     l: "By resource type" },
];
const METRIC_OPTS = [
  { v: "interactions", l: "Interactions" },
  { v: "minutes",      l: "Minutes watched" },
  { v: "downloads",    l: "Downloads" },
  { v: "students",     l: "Athletes reached" },
];

function ImpactView() {
  const { IMPACT, TAGS, COUNSELOR } = window.DATA;
  const { Progress } = window.UI;
  const E = window.ENGAGEMENT;
  const events = useEvents();

  const [range, setRange] = useState("year");
  const [dim, setDim] = useState("month");
  const [metric, setMetric] = useState("interactions");

  const scoped = E.filterRange(events, range);
  const sum = E.summarize(scoped);

  // Sessions completed = distinct training sessions with a completion event
  const sessionsCompleted = new Set(
    events.filter(e => e.type === "complete" && e.source === "training").map(e => e.refId)
  ).size;
  const totalSessions = window.DATA.TRAINING_SESSIONS.length;

  const pillarRows = E.byPillar(scoped);
  const totalPillarInteractions = pillarRows.reduce((s, r) => s + r.interactions, 0) || 1;

  const breakdownRows = (
    dim === "month" ? E.byMonth(scoped) :
    dim === "semester" ? E.bySemester(scoped) :
    dim === "grade" ? E.byGrade(scoped) :
    E.byType(scoped)
  );
  const maxMetric = Math.max(...breakdownRows.map(r => r[metric]), 1);

  // Activity log from the real event stream (most recent first)
  const recent = [...events].sort((a, b) => (a.ts < b.ts ? 1 : -1)).slice(0, 8).map(e => ({
    kind: e.type,
    action: { watch: "Watched", download: "Downloaded", share: "Shared", complete: "Completed" }[e.type] || "Logged",
    target: e.title,
    detail: e.type === "watch" ? `${e.minutes} min watched`
      : e.type === "share" ? `with ${e.students} student-athlete${e.students === 1 ? "" : "s"}`
      : e.type === "download" ? `${(e.assetType || "file").toUpperCase()} · ${e.source}`
      : `${e.source} task`,
    when: new Date(e.ts).toLocaleDateString("en-US", { month: "short", day: "numeric" }),
  }));

  const rangeLabel = RANGE_OPTS.find(r => r.v === range)?.l.toLowerCase();

  return (
    <>
      <window.TopBar
        title="Impact & Engagement"
        subtitle="Every download, minute watched, and resource shared — rolled up across time, grade, and pillar."
        right={
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <select value={range} onChange={e => setRange(e.target.value)} style={{ padding: "8px 10px", border: "1px solid var(--line)", borderRadius: 8, background: "var(--card)", fontSize: 13 }}>
              {RANGE_OPTS.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
            </select>
            <button style={{
              padding: "8px 14px", borderRadius: 8, background: "var(--card)",
              border: "1px solid var(--line-2)", fontSize: 13, fontWeight: 500,
              display: "inline-flex", alignItems: "center", gap: 7,
            }}>
              <window.I.Download size={13} /> Export my report
            </button>
          </div>
        }
      />

      <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 24 }}>
        {/* Headline encouragement */}
        <div style={{
          padding: "22px 26px",
          borderRadius: "var(--radius-lg)",
          background: "linear-gradient(135deg, #FDF4E0 0%, #F7E8C0 100%)",
          border: "1px solid #D4A84B",
          display: "flex", alignItems: "center", gap: 22,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 14,
            background: "#E8A020", color: "white",
            display: "flex", alignItems: "center", justifyContent: "center",
            flexShrink: 0,
          }}>
            <window.I.Flame size={28} stroke="white" sw={2} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, letterSpacing: 0.06, textTransform: "uppercase", color: "#7A5000", fontWeight: 500, marginBottom: 4 }}>
              You're in the top 10% of counselors this month
            </div>
            <div className="serif" style={{ fontSize: 26, letterSpacing: -0.015, lineHeight: 1.2, color: "#3D2800" }}>
              {sum.minutes} minutes of training and{" "}
              <em>{sum.students} student-athletes reached</em> across {sum.downloads + sum.shares} shared resources {rangeLabel}.
            </div>
          </div>
        </div>

        {/* Top stats (computed from the event log, scoped to the range) */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          <StatCard
            label="Training minutes"
            value={sum.minutes}
            sub={`${sum.watches} viewing sessions`}
            icon="Clock"
            color="accent"
          />
          <StatCard
            label="Sessions completed"
            value={`${sessionsCompleted}/${totalSessions}`}
            sub="All-time, across pillars"
            icon="CheckCircle"
            color="success"
            progress={(sessionsCompleted / totalSessions) * 100}
          />
          <StatCard
            label="Resources downloaded"
            value={sum.downloads}
            sub={`${sum.shares} shared to athletes`}
            icon="Download"
            color="purple"
          />
          <StatCard
            label="Student-athletes reached"
            value={sum.students}
            sub={`via ${sum.shares} shared resources`}
            icon="Users"
            color="gold"
          />
        </div>

        {/* Cumulative rollups — the core of the tracking model */}
        <div style={{
          padding: 24, background: "var(--card)",
          border: "1px solid var(--line)", borderRadius: "var(--radius)",
        }}>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: -0.005 }}>Cumulative engagement</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
                Totals rolled up by month, semester, grade level, and resource type.
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <Segmented options={DIM_OPTS} value={dim} onChange={setDim} />
              <Segmented options={METRIC_OPTS} value={metric} onChange={setMetric} />
            </div>
          </div>

          {breakdownRows.length === 0 ? (
            <div style={{ padding: "26px 0", textAlign: "center", fontSize: 12.5, color: "var(--ink-3)" }}>
              No activity recorded for this range yet.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {breakdownRows.map((r, i) => (
                <div key={r.key} style={{ display: "flex", alignItems: "center", gap: 14, padding: "9px 0", borderTop: i > 0 ? "1px solid var(--line)" : "none" }}>
                  <div style={{ width: 150, flexShrink: 0, fontSize: 13, fontWeight: 500, letterSpacing: -0.005 }}>{r.label}</div>
                  <div style={{ flex: 1, minWidth: 0, height: 22, background: "var(--bg-2)", borderRadius: 5, overflow: "hidden", position: "relative" }}>
                    <div style={{ width: `${(r[metric] / maxMetric) * 100}%`, height: "100%", background: "var(--accent)", borderRadius: 5, transition: "width 300ms" }} />
                  </div>
                  <div className="mono" style={{ width: 52, textAlign: "right", flexShrink: 0, fontSize: 13, fontWeight: 600 }}>
                    {r[metric]}
                  </div>
                  <div style={{ width: 180, flexShrink: 0, fontSize: 11.5, color: "var(--ink-3)", textAlign: "right" }}>
                    {r.minutes}m · {r.downloads} dl · {r.students} reached
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Milestones */}
        <div style={{
          padding: 24, background: "var(--card)",
          border: "1px solid var(--line)", borderRadius: "var(--radius)",
        }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 18 }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: -0.005 }}>Milestones</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
                {IMPACT.milestones.filter(m => m.earned).length} earned · {IMPACT.milestones.filter(m => !m.earned).length} in progress
              </div>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            {IMPACT.milestones.map(m => <MilestoneCard key={m.id} m={m} />)}
          </div>
        </div>

        {/* Bottom grid: engagement by pillar + pain points */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
          <div style={{
            padding: 24, background: "var(--card)",
            border: "1px solid var(--line)", borderRadius: "var(--radius)",
          }}>
            <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: -0.005, marginBottom: 4 }}>Engagement by pillar</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginBottom: 20 }}>
              How your interactions split across the four pillars {rangeLabel}.
            </div>

            <div style={{ display: "flex", height: 12, borderRadius: 6, overflow: "hidden", marginBottom: 18 }}>
              {pillarRows.map(c => {
                const def = TAGS[c.key];
                const width = (c.interactions / totalPillarInteractions) * 100;
                return <div key={c.key} style={{ width: `${width}%`, background: `var(--${def?.color || "accent"})`, transition: "width 400ms" }} />;
              })}
            </div>

            {pillarRows.map(c => {
              const def = TAGS[c.key];
              const pct = Math.round((c.interactions / totalPillarInteractions) * 100);
              return (
                <div key={c.key} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderTop: "1px solid var(--line)" }}>
                  <div style={{ width: 10, height: 10, borderRadius: 3, background: `var(--${def?.color || "accent"})`, flexShrink: 0 }} />
                  <div style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>{c.label}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{c.interactions} interactions</div>
                  <div className="mono" style={{ fontSize: 12, fontWeight: 500, width: 40, textAlign: "right" }}>{pct}%</div>
                </div>
              );
            })}
          </div>

          {/* Pain points (unchanged) */}
          <div style={{
            padding: 24, background: "var(--card)",
            border: "1px solid var(--line)", borderRadius: "var(--radius)",
          }}>
            <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: -0.005, marginBottom: 4 }}>Your counselor pain points</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginBottom: 20 }}>
              Themes our AI has pulled from your support questions and notes. Shared with SASA to improve future training.
            </div>
            {IMPACT.painPoints.map((p, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 12, padding: "12px 0",
                borderTop: i > 0 ? "1px solid var(--line)" : "none",
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 7,
                  background: "var(--bg-2)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 11, fontWeight: 600, color: "var(--ink-2)",
                  fontFamily: "Geist Mono, monospace",
                }}>
                  {String(i + 1).padStart(2, "0")}
                </div>
                <div style={{ flex: 1, fontSize: 13, lineHeight: 1.4, letterSpacing: -0.005 }}>{p.theme}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{p.mentions}×</div>
                <TrendArrow trend={p.trend} />
              </div>
            ))}
          </div>
        </div>

        {/* Activity log — real event stream */}
        <div style={{
          padding: 24, background: "var(--card)",
          border: "1px solid var(--line)", borderRadius: "var(--radius)",
        }}>
          <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: -0.005, marginBottom: 18 }}>Activity log</div>
          {recent.map((a, i) => (
            <div key={i} style={{
              display: "flex", gap: 14, padding: "12px 0",
              borderTop: i > 0 ? "1px solid var(--line)" : "none",
            }}>
              <div style={{
                width: 32, height: 32, borderRadius: 8, flexShrink: 0,
                background: activityColor(a.kind, "soft"),
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                {React.createElement(window.I[activityIconI(a.kind)], { size: 14, stroke: activityColor(a.kind) })}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, letterSpacing: -0.005 }}>
                  <span style={{ color: "var(--ink-3)" }}>{a.action} </span>
                  <span style={{ fontWeight: 500 }}>{a.target}</span>
                </div>
                {a.detail && <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{a.detail}</div>}
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-4)", whiteSpace: "nowrap" }}>{a.when}</div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

function Segmented({ options, value, onChange }) {
  return (
    <div style={{ display: "flex", gap: 3, padding: 3, background: "var(--bg-2)", borderRadius: 8, border: "1px solid var(--line)" }}>
      {options.map(o => {
        const active = value === o.v;
        return (
          <button
            key={o.v}
            onClick={() => onChange(o.v)}
            style={{
              padding: "5px 11px", borderRadius: 5,
              background: active ? "var(--card)" : "transparent",
              color: active ? "var(--ink)" : "var(--ink-3)",
              fontSize: 12, fontWeight: 500, letterSpacing: -0.005,
              boxShadow: active ? "0 1px 2px rgba(0,0,0,0.06)" : "none",
              cursor: "pointer", whiteSpace: "nowrap",
            }}
          >
            {o.l}
          </button>
        );
      })}
    </div>
  );
}

function StatCard({ label, value, sub, icon, color, spark, progress }) {
  const Icon = window.I[icon];
  return (
    <div style={{
      padding: 18, background: "var(--card)",
      border: "1px solid var(--line)", borderRadius: "var(--radius)",
      display: "flex", flexDirection: "column", gap: 12,
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{
          width: 30, height: 30, borderRadius: 7,
          background: `var(--${color}-soft)`,
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon size={15} stroke={`var(--${color === "gold" ? "gold" : color === "success" ? "success" : color === "purple" ? "purple" : "accent"})`} />
        </div>
        {spark && <window.UI.Sparkline values={spark} color={`var(--${color === "gold" ? "gold" : color === "success" ? "success" : color === "purple" ? "purple" : "accent"})`} height={28} width={72} />}
      </div>
      <div>
        <div className="serif" style={{ fontSize: 32, lineHeight: 1, letterSpacing: -0.015 }}>{value}</div>
        <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--ink-2)", marginTop: 8, letterSpacing: -0.005 }}>{label}</div>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>{sub}</div>
      </div>
      {progress !== undefined && (
        <window.UI.Progress value={progress} color={`var(--${color === "gold" ? "gold" : color === "success" ? "success" : color === "purple" ? "purple" : "accent"})`} />
      )}
    </div>
  );
}

function MilestoneCard({ m }) {
  const iconMap = { check: "CheckCircle", share: "Share", flame: "Flame", trophy: "Trophy", heart: "Heart", medal: "Medal" };
  const Icon = window.I[iconMap[m.icon] || "Trophy"];
  return (
    <div style={{
      padding: 16, borderRadius: "var(--radius)",
      background: m.earned ? "var(--gold-soft)" : "var(--bg-2)",
      border: `1px solid ${m.earned ? "#E8A020" : "var(--line)"}`,
      opacity: m.earned ? 1 : 0.95,
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10,
          background: m.earned ? "#E8A020" : "var(--card)",
          color: m.earned ? "white" : "var(--ink-4)",
          border: m.earned ? "none" : "1px solid var(--line-2)",
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
        }}>
          <Icon size={18} sw={2} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 500, letterSpacing: -0.005 }}>{m.title}</div>
          <div style={{ fontSize: 12, color: m.earned ? "#7A5000" : "var(--ink-3)", marginTop: 3, lineHeight: 1.4 }}>
            {m.earned ? `Earned ${new Date(m.earnedDate).toLocaleDateString("en-US", { month: "short", day: "numeric" })}` : m.desc}
          </div>
        </div>
      </div>
      {!m.earned && m.progress !== undefined && (
        <div style={{ marginTop: 12 }}>
          <window.UI.Progress value={m.progress} max={m.total} color="var(--ink)" />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontSize: 11, color: "var(--ink-3)" }}>
            <span>{m.progress} / {m.total}</span>
            <span>{Math.round((m.progress / m.total) * 100)}%</span>
          </div>
        </div>
      )}
    </div>
  );
}

function TrendArrow({ trend }) {
  const colors = { up: "var(--warn)", down: "var(--success)", flat: "var(--ink-4)" };
  const rotate = trend === "up" ? "0deg" : trend === "down" ? "180deg" : "90deg";
  return (
    <div style={{
      width: 20, height: 20, borderRadius: 5,
      background: "rgba(27,61,47,0.10)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
    }}>
      <svg width="10" height="10" viewBox="0 0 12 12" style={{ transform: `rotate(${rotate})` }}>
        <path d="M6 2 L10 8 L2 8 Z" fill={colors[trend]} />
      </svg>
    </div>
  );
}

function activityIconI(kind) {
  return ({ download: "Download", watch: "Play", share: "Share", complete: "CheckCircle", support: "Chat" })[kind] || "Clock";
}

window.ImpactView = ImpactView;
