// Claude usage heatmap — GitHub-style contribution grid backed by real ccheatmap data.
// Data: window.CLAUDE_HEATMAP = { grid: [52][7] levels 0-4, startDate, stats, thresholds }

window.ClaudeHeatmap = (function() {
  const DAY_IDX = { 0: "S", 1: "M", 2: "T", 3: "W", 4: "T", 5: "F", 6: "S" };

  function fmtNum(n) {
    if (n >= 1e9) return (n / 1e9).toFixed(1) + "B";
    if (n >= 1e6) return (n / 1e6).toFixed(1) + "M";
    if (n >= 1e3) return (n / 1e3).toFixed(1) + "k";
    return String(n);
  }

  function View({ theme = "light" }) {
    const real = window.CLAUDE_HEATMAP;
    const data = real ? real.grid : window.JAMES_EXTRAS.claudeHeatmap;
    const startDate = real ? new Date(real.startDate + "T00:00:00") : null;
    const stats = real ? real.stats : null;
    const [hover, setHover] = React.useState(null);

    const cell = 14, gap = 3;
    const weeks = data.length;
    const width = weeks * (cell + gap) + 30;
    const height = 7 * (cell + gap) + 28;

    const bg0 = theme === "dark" ? "#1a1a1e" : "#ebe6dc";
    const accent = "var(--accent)";
    const muted = theme === "dark" ? "#888" : "#8a8478";

    // Month labels: find first day of each month across the grid
    const monthLabels = [];
    if (startDate) {
      let lastMonth = -1;
      for (let w = 0; w < weeks; w++) {
        for (let d = 0; d < 7; d++) {
          const day = new Date(startDate);
          day.setDate(day.getDate() + w * 7 + d);
          if (day.getDate() <= 7 && day.getMonth() !== lastMonth) {
            monthLabels.push({ w, m: day.toLocaleString("en-US", { month: "short" }) });
            lastMonth = day.getMonth();
            break;
          }
        }
      }
    } else {
      const now = new Date();
      for (let w = 0; w < weeks; w += 4) {
        const d = new Date(now);
        d.setDate(d.getDate() - (weeks - w) * 7);
        monthLabels.push({ w, m: d.toLocaleString("en-US", { month: "short" }) });
      }
    }

    const activeDays = stats ? stats.activeDays : data.flat().filter(v => v > 0).length;
    const streak = stats ? stats.currentStreak : (() => {
      let s = 0;
      for (let w = weeks - 1; w >= 0; w--) {
        if (data[w].some(v => v > 0)) s++; else break;
      }
      return s;
    })();
    const sessions = stats ? stats.sessions : Math.round(data.flat().reduce((a, b) => a + b, 0) * 4);
    const tokens = stats ? stats.tokens : null;

    function hoverLabel() {
      if (!hover) return "Hover cells for details · real Claude Code usage from ~/.claude/projects.";
      if (!startDate) return `Week ${hover.w + 1}, ${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][hover.d]} — intensity ${hover.level}/4`;
      const day = new Date(startDate);
      day.setDate(day.getDate() + hover.w * 7 + hover.d);
      const iso = day.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric", year: "numeric" });
      return `${iso} — intensity ${hover.level}/4`;
    }

    const statRows = [
      { n: activeDays, l: "active days · last year" },
      { n: streak + "d", l: "current streak" },
      { n: sessions, l: "sessions" },
    ];
    if (tokens) statRows.push({ n: fmtNum(tokens), l: "tokens processed" });

    return (
      <div style={{ width: "100%" }}>
        <div style={{ display: "flex", gap: 28, marginBottom: 18, flexWrap: "wrap" }}>
          {statRows.map((s, i) => (
            <div key={i}>
              <div className="serif" style={{ fontSize: 40, lineHeight: 1, color: "var(--accent)" }}>{s.n}</div>
              <div className="mono" style={{ fontSize: 10.5, color: muted, letterSpacing: "0.12em", textTransform: "uppercase", marginTop: 4 }}>{s.l}</div>
            </div>
          ))}
        </div>

        <div style={{ overflowX: "auto" }}>
          <svg width={width} height={height} style={{ display: "block" }}>
            {monthLabels.map((ml, i) => (
              <text key={i} x={30 + ml.w * (cell + gap)} y={12}
                fontSize={10} fontFamily='"JetBrains Mono", monospace' fill={muted}>
                {ml.m}
              </text>
            ))}
            {[1, 3, 5].map(d => (
              <text key={d} x={0} y={28 + d * (cell + gap) + cell - 3}
                fontSize={9} fontFamily='"JetBrains Mono", monospace' fill={muted}>
                {DAY_IDX[d]}
              </text>
            ))}
            <g transform={`translate(30, 22)`}>
              {data.map((col, w) => col.map((level, d) => {
                const hov = hover && hover.w === w && hover.d === d;
                const fill = level === 0 ? bg0 :
                  level === 1 ? `color-mix(in oklch, ${accent} 22%, ${bg0})` :
                  level === 2 ? `color-mix(in oklch, ${accent} 45%, ${bg0})` :
                  level === 3 ? `color-mix(in oklch, ${accent} 72%, ${bg0})` :
                                accent;
                return (
                  <rect key={`${w}-${d}`}
                    x={w * (cell + gap)} y={d * (cell + gap)}
                    width={cell} height={cell} rx={3}
                    fill={fill}
                    stroke={hov ? "var(--ink)" : "none"}
                    strokeWidth={hov ? 1 : 0}
                    onMouseEnter={() => setHover({ w, d, level })}
                    onMouseLeave={() => setHover(null)}
                    style={{ cursor: "default", transition: "stroke .1s" }}
                  />
                );
              }))}
            </g>
          </svg>
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, gap: 16, flexWrap: "wrap" }}>
          <div className="mono" style={{ fontSize: 11, color: muted, minHeight: 16 }}>
            {hoverLabel()}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span className="mono" style={{ fontSize: 10.5, color: muted }}>less</span>
            {[0, 1, 2, 3, 4].map(l => {
              const fill = l === 0 ? bg0 :
                l === 1 ? `color-mix(in oklch, ${accent} 22%, ${bg0})` :
                l === 2 ? `color-mix(in oklch, ${accent} 45%, ${bg0})` :
                l === 3 ? `color-mix(in oklch, ${accent} 72%, ${bg0})` :
                          accent;
              return <span key={l} style={{ width: 12, height: 12, borderRadius: 3, background: fill, display: "inline-block" }} />;
            })}
            <span className="mono" style={{ fontSize: 10.5, color: muted }}>more</span>
          </div>
        </div>
      </div>
    );
  }

  return { View };
})();
