// SPDX-License-Identifier: LicenseRef-Commercial
<script lang="ts">
  import { onDestroy } from 'svelte';
  import {
    proAnalyticsSummary,
    proAnalyticsDaily,
    proAnalyticsModelBreakdown,
    type AnalyticsSummary,
    type DailyStats,
    type ModelBreakdown,
  } from './pro-bridge';

  interface Props {
    projectId: string;
  }

  let { projectId }: Props = $props();

  const PERIODS = [7, 14, 30, 90] as const;
  type Period = (typeof PERIODS)[number];

  let days = $state<Period>(30);
  let loading = $state(true);
  let error = $state<string | null>(null);
  let summary = $state<AnalyticsSummary | null>(null);
  let daily = $state<DailyStats[]>([]);
  let models = $state<ModelBreakdown[]>([]);

  let maxDailyCost = $derived(Math.max(...daily.map((d) => d.costUsd), 0.001));

  async function load() {
    loading = true;
    error = null;
    try {
      const [s, d, m] = await Promise.all([
        proAnalyticsSummary(projectId, days),
        proAnalyticsDaily(projectId, days),
        proAnalyticsModelBreakdown(projectId, days),
      ]);
      summary = s;
      daily = d;
      models = m;
    } catch (e) {
      error = e instanceof Error ? e.message : String(e);
    } finally {
      loading = false;
    }
  }

  $effect(() => {
    // Re-run when projectId or days changes
    void projectId;
    void days;
    load();
  });

  function fmt(n: number, decimals = 2): string {
    return n.toFixed(decimals);
  }

  function fmtK(n: number): string {
    return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
  }
</script>

<div class="analytics-root">
  <div class="period-bar">
    {#each PERIODS as p}
      <button
        class="period-btn"
        class:active={days === p}
        onclick={() => (days = p)}
      >{p}d</button>
    {/each}
  </div>

  {#if loading}
    <div class="state-msg">Loading analytics...</div>
  {:else if error}
    <div class="state-msg error">{error}</div>
  {:else if summary}
    <div class="cards">
      <div class="card">
        <span class="card-label">Total Cost</span>
        <span class="card-value">${fmt(summary.totalCostUsd)}</span>
      </div>
      <div class="card">
        <span class="card-label">Sessions</span>
        <span class="card-value">{summary.totalSessions}</span>
      </div>
      <div class="card">
        <span class="card-label">Avg $/Session</span>
        <span class="card-value">${fmt(summary.avgCostPerSession)}</span>
      </div>
      <div class="card">
        <span class="card-label">Total Tokens</span>
        <span class="card-value">{fmtK(summary.totalTokens)}</span>
      </div>
    </div>

    {#if daily.length > 0}
      <div class="section-title">Daily Cost</div>
      <div class="chart-container">
        <svg viewBox="0 0 {daily.length * 20} 100" class="bar-chart" preserveAspectRatio="none">
          {#each daily as d, i}
            {@const h = Math.max((d.costUsd / maxDailyCost) * 90, 1)}
            <rect
              x={i * 20 + 2}
              y={100 - h}
              width="16"
              height={h}
              rx="2"
              class="bar"
            />
          {/each}
        </svg>
        <div class="chart-labels">
          {#each daily as d, i}
            {#if i === 0 || i === daily.length - 1 || i === Math.floor(daily.length / 2)}
              <span class="chart-label" style:left="{(i / Math.max(daily.length - 1, 1)) * 100}%">{d.date.slice(5)}</span>
            {/if}
          {/each}
        </div>
      </div>
    {/if}

    {#if models.length > 0}
      <div class="section-title">Model Breakdown</div>
      <table class="model-table">
        <thead>
          <tr>
            <th>Model</th>
            <th>Sessions</th>
            <th>Cost</th>
            <th>Tokens</th>
          </tr>
        </thead>
        <tbody>
          {#each models as m}
            <tr>
              <td class="model-name">{m.model}</td>
              <td>{m.sessionCount}</td>
              <td>${fmt(m.totalCostUsd)}</td>
              <td>{fmtK(m.totalTokens)}</td>
            </tr>
          {/each}
        </tbody>
      </table>
    {/if}
  {/if}
</div>

<style>
  .analytics-root {
    padding: 0.75rem;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    color: var(--ctp-text);
    font-family: var(--ui-font-family, system-ui, sans-serif);
    font-size: var(--ui-font-size, 0.8125rem);
    overflow-y: auto;
    height: 100%;
  }

  .period-bar {
    display: flex;
    gap: 0.25rem;
  }

  .period-btn {
    padding: 0.25rem 0.625rem;
    border: 1px solid var(--ctp-surface1);
    border-radius: 0.25rem;
    background: var(--ctp-surface0);
    color: var(--ctp-subtext0);
    cursor: pointer;
    font-size: 0.75rem;
  }

  .period-btn:hover {
    background: var(--ctp-surface1);
    color: var(--ctp-text);
  }

  .period-btn.active {
    background: var(--ctp-blue);
    color: var(--ctp-base);
    border-color: var(--ctp-blue);
  }

  .state-msg {
    padding: 1.5rem;
    text-align: center;
    color: var(--ctp-subtext0);
  }

  .state-msg.error {
    color: var(--ctp-red);
  }

  .cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0.5rem;
  }

  .card {
    display: flex;
    flex-direction: column;
    gap: 0.125rem;
    padding: 0.5rem 0.625rem;
    background: var(--ctp-surface0);
    border-radius: 0.375rem;
    border: 1px solid var(--ctp-surface1);
  }

  .card-label {
    font-size: 0.6875rem;
    color: var(--ctp-subtext0);
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  .card-value {
    font-size: 1.125rem;
    font-weight: 600;
    color: var(--ctp-text);
  }

  .section-title {
    font-size: 0.75rem;
    color: var(--ctp-subtext1);
    text-transform: uppercase;
    letter-spacing: 0.04em;
    margin-top: 0.25rem;
  }

  .chart-container {
    position: relative;
    background: var(--ctp-surface0);
    border-radius: 0.375rem;
    border: 1px solid var(--ctp-surface1);
    padding: 0.5rem 0.5rem 1.5rem;
  }

  .bar-chart {
    width: 100%;
    height: 6rem;
  }

  .bar {
    fill: var(--ctp-blue);
    opacity: 0.85;
  }

  .bar:hover {
    opacity: 1;
  }

  .chart-labels {
    position: relative;
    height: 1rem;
    margin-top: 0.25rem;
  }

  .chart-label {
    position: absolute;
    transform: translateX(-50%);
    font-size: 0.625rem;
    color: var(--ctp-overlay0);
  }

  .model-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.75rem;
  }

  .model-table th {
    text-align: left;
    padding: 0.375rem 0.5rem;
    color: var(--ctp-subtext0);
    border-bottom: 1px solid var(--ctp-surface1);
    font-weight: 500;
  }

  .model-table td {
    padding: 0.375rem 0.5rem;
    border-bottom: 1px solid var(--ctp-surface0);
    color: var(--ctp-subtext1);
  }

  .model-table tr:hover td {
    background: var(--ctp-surface0);
    color: var(--ctp-text);
  }

  .model-name {
    font-family: monospace;
    color: var(--ctp-blue);
  }
</style>
