'use client';

import { useEffect, useMemo, useState } from 'react';
import { fetchWithAuth } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';
import { DonutChart, SectionCard, Sparkline } from '../analytics/charts';
import {
  evalCaseScores,
  evalScoreItems,
  type BehaviorMetric,
  type BehaviorTeamPattern,
  type ProfileSpend,
  type ScenarioSlice,
  type TeamUsage,
  type WeeklyTrendPoint,
  type WorkspaceMode,
} from './data';
import {
  buildUsageData,
  emptyAggregatedUsageData,
  getUsageDates,
  type UsageDataSource,
} from './usageData';

const FONT = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
const COLORS = {
  primary: '#5c5fbc',
  primarySoft: '#eef0ff',
  green: '#10b981',
  amber: '#f59e0b',
  red: '#ef4444',
  purple: '#8b5cf6',
  text: '#1f2937',
  muted: '#6b7280',
  faint: '#9ca3af',
  border: '#eef0f5',
};

function formatCurrency(value: number) {
  return `$${value.toFixed(2)}`;
}

function formatCurrencyCompact(value: number) {
  return `$${value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

function formatPct(value: number, total: number) {
  return total > 0 ? `${((value / total) * 100).toFixed(1)}%` : '0.0%';
}

function KpiCard({
  label,
  value,
  hint,
  sparkline,
  color = COLORS.primary,
}: {
  label: string;
  value: string;
  hint: string;
  sparkline: number[];
  color?: string;
}) {
  return (
    <div
      style={{
        background: '#fff',
        border: `1px solid ${COLORS.border}`,
        borderRadius: 10,
        padding: '16px 18px',
        boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
        minHeight: 118,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
      }}
    >
      <div>
        <div style={{ fontSize: 12, color: COLORS.muted, fontWeight: 600 }}>{label}</div>
        <div style={{ marginTop: 8, fontSize: 28, lineHeight: 1, color: COLORS.text, fontWeight: 750 }}>
          {value}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 10 }}>
        <div style={{ fontSize: 12, color: COLORS.faint, lineHeight: 1.45 }}>{hint}</div>
        <Sparkline data={sparkline} color={color} width={86} height={28} />
      </div>
    </div>
  );
}

function ScoreBars() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {evalScoreItems.map((item) => (
        <div key={item.label} style={{ display: 'grid', gridTemplateColumns: '160px 1fr 88px', gap: 12, alignItems: 'center' }}>
          <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.label}
          </div>
          <div style={{ position: 'relative', height: 20, background: '#f3f4f6', borderRadius: 5, overflow: 'hidden' }}>
            <div
              style={{
                width: `${item.rate}%`,
                height: '100%',
                background: item.color,
                borderRadius: 5,
              }}
            />
            <div
              style={{
                position: 'absolute',
                inset: 0,
                display: 'flex',
                alignItems: 'center',
                paddingLeft: 8,
                color: item.rate > 45 ? '#fff' : COLORS.muted,
                fontSize: 11,
                fontWeight: 700,
              }}
            >
              {item.rate.toFixed(1)}%
            </div>
          </div>
          <div style={{ color: COLORS.muted, fontSize: 12, textAlign: 'right' }}>{item.score}</div>
        </div>
      ))}
    </div>
  );
}

function WeeklyTrendChart({
  data,
  workspaceLabel,
  activeUsersLabel,
  costLabel,
}: {
  data: WeeklyTrendPoint[];
  workspaceLabel: string;
  activeUsersLabel: string;
  costLabel: string;
}) {
  if (!data.length) return <EmptyChart />;
  const H = 260;
  const pad = { top: 26, right: 62, bottom: 46, left: 48 };
  const minW = 720;
  const dayW = 66;
  const W = Math.max(minW, pad.left + pad.right + data.length * dayW);
  const chartW = W - pad.left - pad.right;
  const chartH = H - pad.top - pad.bottom;
  const maxCount = Math.max(1, ...data.flatMap((d) => [d.workspaces, d.activeUsers])) * 1.18;
  const maxCost = Math.max(1, ...data.map((d) => d.cost)) * 1.14;
  const groupW = chartW / data.length;
  const barW = Math.min(17, groupW * 0.22);
  const barGap = Math.min(5, groupW * 0.07);

  return (
    <div style={{ overflowX: 'auto', overflowY: 'hidden', paddingBottom: 4 }}>
      <svg
        viewBox={`0 0 ${W} ${H}`}
        width={W}
        height={H}
        style={{ display: 'block', width: W === minW ? '100%' : W, minWidth: W, maxWidth: 'none', fontFamily: FONT }}
      >
        {[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
          const y = pad.top + chartH - ratio * chartH;
          return (
            <g key={ratio}>
              <line x1={pad.left} y1={y} x2={W - pad.right} y2={y} stroke="#eef0f5" />
              <text x={pad.left - 8} y={y + 4} textAnchor="end" fill={COLORS.faint} fontSize={10}>
                {Math.round(maxCount * ratio)}
              </text>
              <text x={W - pad.right + 8} y={y + 4} fill={COLORS.faint} fontSize={10}>
                ${Math.round(maxCost * ratio)}
              </text>
            </g>
          );
        })}
        {data.map((d, i) => {
          const centerX = pad.left + groupW * i + groupW / 2;
          const workspaceX = centerX - barW * 1.5 - barGap;
          const activeUsersX = centerX - barW / 2;
          const costX = centerX + barW / 2 + barGap;
          const workspaceH = (d.workspaces / maxCount) * chartH;
          const activeUsersH = (d.activeUsers / maxCount) * chartH;
          const costH = (d.cost / maxCost) * chartH;
          const workspaceY = pad.top + chartH - workspaceH;
          const activeUsersY = pad.top + chartH - activeUsersH;
          const costY = pad.top + chartH - costH;
          return (
            <g key={d.period}>
              <rect x={workspaceX} y={workspaceY} width={barW} height={workspaceH} rx={5} fill={COLORS.primary} opacity={0.82} />
              <rect x={activeUsersX} y={activeUsersY} width={barW} height={activeUsersH} rx={5} fill={COLORS.green} opacity={0.8} />
              <rect x={costX} y={costY} width={barW} height={costH} rx={5} fill={COLORS.red} opacity={0.82} />
              <text x={workspaceX + barW / 2} y={workspaceY - 6} textAnchor="middle" fill={COLORS.muted} fontSize={10} fontWeight={650}>
                {d.workspaces}
              </text>
              <text x={activeUsersX + barW / 2} y={activeUsersY - 6} textAnchor="middle" fill={COLORS.green} fontSize={10} fontWeight={650}>
                {d.activeUsers}
              </text>
              <text x={costX + barW / 2} y={costY - 6} textAnchor="middle" fill={COLORS.red} fontSize={10} fontWeight={700}>
                ${Math.round(d.cost)}
              </text>
              <text x={centerX} y={H - 18} textAnchor="middle" fill={COLORS.muted} fontSize={10}>
                {d.period.replace('-', ' - ')}
              </text>
            </g>
          );
        })}
        <g transform={`translate(${pad.left}, 10)`}>
          <rect width={10} height={10} rx={2} fill={COLORS.primary} />
          <text x={16} y={9} fill={COLORS.muted} fontSize={11}>{workspaceLabel}</text>
          <rect x={96} width={10} height={10} rx={2} fill={COLORS.green} />
          <text x={112} y={9} fill={COLORS.muted} fontSize={11}>{activeUsersLabel}</text>
          <rect x={192} width={10} height={10} rx={2} fill={COLORS.red} />
          <text x={218} y={9} fill={COLORS.muted} fontSize={11}>{costLabel}</text>
        </g>
      </svg>
    </div>
  );
}

function TeamUsageChart({ teams }: { teams: TeamUsage[] }) {
  if (!teams.length) return <EmptyChart />;
  const maxInteractions = Math.max(...teams.map((team) => team.totalInteractions));
  const maxCost = Math.max(...teams.map((team) => team.totalCost));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {teams.map((team) => (
        <div key={team.team} style={{ display: 'grid', gridTemplateColumns: '210px 1fr 76px', gap: 12, alignItems: 'center' }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {team.rank}. {team.shortName}
            </div>
            <div style={{ color: COLORS.faint, fontSize: 11, marginTop: 2 }}>{team.wsCount} WS · {team.activeUsers} users</div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ height: 11, background: '#f3f4f6', borderRadius: 4, overflow: 'hidden' }}>
              <div style={{ width: `${(team.totalInteractions / maxInteractions) * 100}%`, height: '100%', background: COLORS.primary, borderRadius: 4 }} />
            </div>
            <div style={{ height: 8, background: '#f3f4f6', borderRadius: 4, overflow: 'hidden' }}>
              <div style={{ width: `${(team.totalCost / maxCost) * 100}%`, height: '100%', background: COLORS.amber, borderRadius: 4 }} />
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 700 }}>{team.totalInteractions}</div>
            <div style={{ color: COLORS.amber, fontSize: 11, fontWeight: 650 }}>{formatCurrency(team.totalCost)}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ProfileSpendChart({
  data,
  totalLabel,
}: {
  data: ProfileSpend[];
  totalLabel: string;
}) {
  if (!data.length) return <EmptyChart />;
  const total = data.reduce((sum, item) => sum + item.spend, 0);
  const maxSpend = Math.max(...data.map((item) => item.spend));

  return (
    <div>
      <div
        style={{
          display: 'flex',
          alignItems: 'baseline',
          justifyContent: 'space-between',
          gap: 12,
          marginBottom: 14,
        }}
      >
        <div style={{ color: COLORS.faint, fontSize: 12, fontWeight: 650 }}>{totalLabel}</div>
        <div style={{ color: COLORS.text, fontSize: 22, lineHeight: 1, fontWeight: 750 }}>
          {formatCurrencyCompact(total)}
        </div>
      </div>

      <div style={{ display: 'flex', height: 20, borderRadius: 6, overflow: 'hidden', background: '#f3f4f6', marginBottom: 16 }}>
        {data.map((item) => (
          <div
            key={item.profile}
            title={`${item.profile}: ${formatCurrencyCompact(item.spend)} (${item.share.toFixed(1)}%)`}
            style={{
              width: `${Math.max(item.share, 0.2)}%`,
              background: item.color,
            }}
          />
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
        {data.map((item) => (
          <div key={item.profile} style={{ display: 'grid', gridTemplateColumns: 'minmax(140px, 210px) 1fr 112px', gap: 10, alignItems: 'center' }}>
            <div style={{ minWidth: 0, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 9, height: 9, borderRadius: 2, background: item.color, flex: '0 0 auto' }} />
              <span style={{ color: COLORS.text, fontSize: 12, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {item.profile}
              </span>
            </div>
            <div style={{ height: 14, background: '#f3f4f6', borderRadius: 5, overflow: 'hidden' }}>
              <div
                style={{
                  width: `${(item.spend / maxSpend) * 100}%`,
                  height: '100%',
                  background: item.color,
                  borderRadius: 5,
                }}
              />
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 700 }}>{formatCurrencyCompact(item.spend)}</div>
              <div style={{ color: COLORS.faint, fontSize: 11 }}>{item.share.toFixed(1)}%</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function BehaviorMetricGrid({
  metrics,
  labels,
}: {
  metrics: BehaviorMetric[];
  labels: Record<string, string>;
}) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))', gap: 10 }}>
      {metrics.map((metric) => (
        <div
          key={metric.key}
          style={{
            border: `1px solid ${COLORS.border}`,
            borderRadius: 8,
            padding: 12,
            background: '#fbfcff',
            minHeight: 74,
          }}
        >
          <div style={{ color: COLORS.text, fontSize: 22, lineHeight: 1, fontWeight: 750 }}>{metric.value}</div>
          <div style={{ color: COLORS.faint, fontSize: 11, lineHeight: 1.35, marginTop: 8 }}>{labels[metric.key] ?? metric.key}</div>
        </div>
      ))}
    </div>
  );
}

function AcpMessageRatioChart({
  data,
  acpLabel,
  messageLabel,
  ratioLabel,
}: {
  data: BehaviorTeamPattern[];
  acpLabel: string;
  messageLabel: string;
  ratioLabel: string;
}) {
  if (!data.length) return <EmptyChart />;
  const maxMessages = Math.max(...data.map((item) => item.messages));
  const maxAcp = Math.max(...data.map((item) => item.acp));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
      {data.map((item) => (
        <div key={item.team}>
          <div style={{ marginBottom: 6 }}>
            <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 650, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {item.team}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '170px 1fr 54px', gap: 10, alignItems: 'center' }}>
            <div style={{ minWidth: 0, color: COLORS.faint, fontSize: 11, whiteSpace: 'nowrap' }}>
              {item.ratio.toFixed(2)} {ratioLabel}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <div style={{ height: 10, background: '#f3f4f6', borderRadius: 4, overflow: 'hidden' }}>
                <div style={{ width: `${(item.messages / maxMessages) * 100}%`, height: '100%', background: COLORS.primary, borderRadius: 4 }} />
              </div>
              <div style={{ height: 8, background: '#f3f4f6', borderRadius: 4, overflow: 'hidden' }}>
                <div style={{ width: `${(item.acp / maxAcp) * 100}%`, height: '100%', background: COLORS.green, borderRadius: 4 }} />
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 700 }}>{item.messages}</div>
              <div style={{ color: COLORS.green, fontSize: 11, fontWeight: 650 }}>{item.acp}</div>
            </div>
          </div>
        </div>
      ))}
      <div style={{ display: 'flex', gap: 14, alignItems: 'center', color: COLORS.faint, fontSize: 11 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 9, height: 9, borderRadius: 2, background: COLORS.primary }} />
          {messageLabel}
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 9, height: 9, borderRadius: 2, background: COLORS.green }} />
          {acpLabel}
        </span>
      </div>
    </div>
  );
}

function BehaviorDistributionChart({
  data,
  userMessagesLabel,
}: {
  data: BehaviorTeamPattern[];
  userMessagesLabel: string;
}) {
  if (!data.length) return <EmptyChart />;
  const legend = data[0]?.categories ?? [];

  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
        {data.map((item) => (
          <div key={item.team}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, marginBottom: 6 }}>
              <div style={{ color: COLORS.text, fontSize: 12, fontWeight: 650 }}>{item.team}</div>
              <div style={{ color: COLORS.faint, fontSize: 11 }}>
                {item.userMessages} {userMessagesLabel}
              </div>
            </div>
            <div style={{ display: 'flex', height: 22, borderRadius: 6, overflow: 'hidden', background: '#f3f4f6' }}>
              {item.categories.map((category) => (
                <div
                  key={category.label}
                  title={`${category.label}: ${category.count} (${category.pct.toFixed(1)}%)`}
                  style={{
                    width: `${category.pct}%`,
                    minWidth: category.count > 0 ? 4 : 0,
                    background: category.color,
                  }}
                />
              ))}
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 12px', marginTop: 14 }}>
        {legend.map((category) => (
          <span key={category.label} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: COLORS.muted, fontSize: 11 }}>
            <span style={{ width: 9, height: 9, borderRadius: 2, background: category.color }} />
            {category.label}
          </span>
        ))}
      </div>
    </div>
  );
}

function WorkspaceModeChart({
  data,
  workspacesUnit,
  usersUnit,
}: {
  data: WorkspaceMode[];
  workspacesUnit: string;
  usersUnit: string;
}) {
  if (!data.length) return <EmptyChart />;
  const maxWorkspaces = Math.max(...data.map((mode) => mode.workspaces));

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 12 }}>
      {data.map((mode) => (
        <div
          key={mode.label}
          style={{
            border: `1px solid ${COLORS.border}`,
            borderRadius: 9,
            padding: 14,
            background: '#fbfcff',
          }}
        >
          <div style={{ color: COLORS.text, fontSize: 13, fontWeight: 700 }}>{mode.label}</div>
          <div style={{ color: COLORS.faint, fontSize: 11, marginTop: 4 }}>{mode.description}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 14 }}>
            <span style={{ color: COLORS.text, fontSize: 26, fontWeight: 750 }}>{mode.workspaces}</span>
            <span style={{ color: COLORS.muted, fontSize: 12 }}>{workspacesUnit}</span>
          </div>
          <div style={{ height: 8, background: '#eef0f5', borderRadius: 4, overflow: 'hidden', marginTop: 10 }}>
            <div style={{ width: `${(mode.workspaces / maxWorkspaces) * 100}%`, height: '100%', background: mode.color }} />
          </div>
          <div style={{ color: COLORS.muted, fontSize: 12, marginTop: 8 }}>{mode.users} {usersUnit}</div>
        </div>
      ))}
    </div>
  );
}

function ScenarioList({ data }: { data: ScenarioSlice[] }) {
  if (!data.length) return <EmptyChart />;
  const max = Math.max(...data.map((item) => item.value));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      {data.map((item) => (
        <div key={item.label} style={{ display: 'grid', gridTemplateColumns: 'minmax(140px, 230px) 1fr 72px', gap: 10, alignItems: 'center' }}>
          <div style={{ minWidth: 0, color: COLORS.text, fontSize: 12, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.label}
          </div>
          <div style={{ height: 16, background: '#f3f4f6', borderRadius: 5, overflow: 'hidden' }}>
            <div style={{ width: `${(item.value / max) * 100}%`, height: '100%', background: item.color, borderRadius: 5 }} />
          </div>
          <div style={{ color: COLORS.muted, fontSize: 12, textAlign: 'right' }}>
            {item.value} · {item.pct.toFixed(1)}%
          </div>
        </div>
      ))}
    </div>
  );
}

function withScenarioDisplayLabels(data: ScenarioSlice[], uncategorizedLabel: string) {
  return data.map((item) => ({
    ...item,
    label: item.label === 'uncategorized_or_mixed' ? uncategorizedLabel : item.label,
  }));
}

function EmptyChart() {
  return (
    <div
      style={{
        minHeight: 120,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: COLORS.faint,
        fontSize: 12,
        border: `1px dashed ${COLORS.border}`,
        borderRadius: 8,
        background: '#fbfcff',
      }}
    />
  );
}

function DateRangeControl({
  startDate,
  endDate,
  onStartDateChange,
  onEndDateChange,
  labels,
  defaultStartDate,
  defaultEndDate,
}: {
  startDate: string;
  endDate: string;
  onStartDateChange: (value: string) => void;
  onEndDateChange: (value: string) => void;
  labels: {
    start: string;
    end: string;
    reset: string;
    available: string;
  };
  defaultStartDate: string;
  defaultEndDate: string;
}) {
  const min = defaultStartDate;
  const max = defaultEndDate;
  const inputStyle = {
    height: 34,
    border: `1px solid ${COLORS.border}`,
    borderRadius: 7,
    padding: '0 10px',
    color: COLORS.text,
    background: '#fff',
    fontSize: 12,
    fontFamily: FONT,
  };

  return (
    <div
      style={{
        marginTop: 14,
        display: 'flex',
        flexWrap: 'wrap',
        alignItems: 'center',
        gap: 10,
      }}
    >
      <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: COLORS.muted, fontSize: 12, fontWeight: 650 }}>
        {labels.start}
        <input
          type="date"
          min={min}
          max={max}
          value={startDate}
          disabled={!min}
          onChange={(event) => onStartDateChange(event.target.value)}
          onInput={(event) => onStartDateChange(event.currentTarget.value)}
          onBlur={(event) => onStartDateChange(event.currentTarget.value)}
          style={inputStyle}
        />
      </label>
      <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: COLORS.muted, fontSize: 12, fontWeight: 650 }}>
        {labels.end}
        <input
          type="date"
          min={min}
          max={max}
          value={endDate}
          disabled={!min}
          onChange={(event) => onEndDateChange(event.target.value)}
          onInput={(event) => onEndDateChange(event.currentTarget.value)}
          onBlur={(event) => onEndDateChange(event.currentTarget.value)}
          style={inputStyle}
        />
      </label>
      <button
        type="button"
        onClick={() => {
          onStartDateChange(defaultStartDate);
          onEndDateChange(defaultEndDate);
        }}
        style={{
          height: 34,
          border: `1px solid ${COLORS.border}`,
          borderRadius: 7,
          padding: '0 12px',
          background: COLORS.primarySoft,
          color: COLORS.primary,
          fontSize: 12,
          fontWeight: 700,
          fontFamily: FONT,
          cursor: 'pointer',
        }}
      >
        {labels.reset}
      </button>
      <span style={{ color: COLORS.faint, fontSize: 12 }}>
        {labels.available}
      </span>
    </div>
  );
}

function dateFromQueryParam(value: string | null, minDate: string, maxDate: string) {
  if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return '';
  if (minDate && value < minDate) return '';
  if (maxDate && value > maxDate) return '';
  return value;
}

function SlowCaseTable({
  headers,
}: {
  headers: {
    case: string;
    total: string;
    diagnosis: string;
    routing: string;
    elapsed: string;
  };
}) {
  const slowCases = [...evalCaseScores].sort((a, b) => b.elapsedSeconds - a.elapsedSeconds).slice(0, 5);
  const columns = [
    { key: 'case', label: headers.case },
    { key: 'total', label: headers.total },
    { key: 'diagnosis', label: headers.diagnosis },
    { key: 'routing', label: headers.routing },
    { key: 'elapsed', label: headers.elapsed },
  ];
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
        <thead>
          <tr style={{ borderBottom: `1px solid ${COLORS.border}` }}>
            {columns.map((column) => (
              <th key={column.key} style={{ textAlign: column.key === 'case' ? 'left' : 'right', padding: '8px 10px', color: COLORS.muted, fontWeight: 700 }}>
                {column.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {slowCases.map((item) => (
            <tr key={item.caseName} style={{ borderBottom: '1px solid #f5f5f5' }}>
              <td style={{ padding: '9px 10px', color: COLORS.text, fontWeight: 600 }}>{item.caseName}</td>
              <td style={{ padding: '9px 10px', textAlign: 'right', color: COLORS.text }}>{item.total}</td>
              <td style={{ padding: '9px 10px', textAlign: 'right', color: item.diagnosis < 15 ? COLORS.red : COLORS.muted }}>{item.diagnosis}/50</td>
              <td style={{ padding: '9px 10px', textAlign: 'right', color: COLORS.muted }}>{item.evidenceRouting}/5</td>
              <td style={{ padding: '9px 10px', textAlign: 'right', color: COLORS.muted }}>{Math.round(item.elapsedSeconds)}s</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default function WeeklyReportChartsPage() {
  const { t } = useTranslation();
  const [usageSource, setUsageSource] = useState<UsageDataSource | null>(null);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const usageDates = useMemo(() => getUsageDates(usageSource ?? undefined), [usageSource]);
  const usageData = useMemo(() => {
    if (!usageSource || !startDate || !endDate) return emptyAggregatedUsageData(usageSource ?? undefined);
    return buildUsageData(usageSource, startDate, endDate);
  }, [usageSource, startDate, endDate]);

  useEffect(() => {
    let ignore = false;
    fetchWithAuth('/api/admin/weekly-report/usage-data')
      .then((response) => {
        if (!response.ok) throw new Error(`Failed to load weekly report usage data: HTTP ${response.status}`);
        return response.json() as Promise<UsageDataSource>;
      })
      .then((source) => {
        if (ignore) return;
        const dates = getUsageDates(source);
        const params = new URLSearchParams(window.location.search);
        const queryStartDate = dateFromQueryParam(params.get('start'), dates.defaultStartDate, dates.defaultEndDate);
        const queryEndDate = dateFromQueryParam(params.get('end'), dates.defaultStartDate, dates.defaultEndDate);
        setUsageSource(source);
        setStartDate(queryStartDate || dates.defaultStartDate);
        setEndDate(queryEndDate || dates.defaultEndDate);
      })
      .catch((error) => {
        console.error(error);
      });
    return () => {
      ignore = true;
    };
  }, []);

  useEffect(() => {
    if (!startDate || !endDate) return;
    const url = new URL(window.location.href);
    url.searchParams.set('start', startDate);
    url.searchParams.set('end', endDate);
    window.history.replaceState(null, '', `${url.pathname}${url.search}`);
  }, [startDate, endDate]);

  const kpis = useMemo(() => {
    return [
      {
        label: t('weeklyReportCharts.kpiEval'),
        value: '65.7%',
        hint: t('weeklyReportCharts.kpiEvalHint'),
        sparkline: evalScoreItems.map((item) => item.rate),
        color: COLORS.primary,
      },
      {
        label: t('weeklyReportCharts.kpiDiagnosis'),
        value: '30.8%',
        hint: t('weeklyReportCharts.kpiDiagnosisHint'),
        sparkline: evalCaseScores.map((item) => item.diagnosis),
        color: COLORS.red,
      },
      {
        label: t('weeklyReportCharts.kpiCost'),
        value: formatCurrency(usageData.totals.cost),
        hint: t('weeklyReportCharts.kpiCostHint'),
        sparkline: usageData.weeklyTrends.map((point) => point.cost),
        color: COLORS.amber,
      },
      {
        label: t('weeklyReportCharts.kpiWorkspace'),
        value: String(usageData.totals.newWorkspaces),
        hint: t('weeklyReportCharts.kpiWorkspaceHint', { interactions: usageData.totals.acpInteractions }),
        sparkline: usageData.weeklyTrends.map((point) => point.workspaces),
        color: COLORS.green,
      },
    ];
  }, [t, usageData]);
  const diagnosticScenarios = useMemo(
    () => withScenarioDisplayLabels(usageData.diagnosticScenarios, t('weeklyReportCharts.scenarioUncategorizedMixed')),
    [t, usageData.diagnosticScenarios],
  );
  const nonDiagnosticScenarios = useMemo(
    () => withScenarioDisplayLabels(usageData.nonDiagnosticScenarios, t('weeklyReportCharts.scenarioUncategorizedMixed')),
    [t, usageData.nonDiagnosticScenarios],
  );
  const nonDiagnosticRatio = useMemo(() => {
    const nonDiagnosis = usageData.scenarioTotals.nonDiagnosisWorkspaces;
    const other = Math.max(usageData.scenarioTotals.totalWorkspaces - nonDiagnosis, 0);
    return [
      { label: t('weeklyReportCharts.scenarioNonDiagnosticLabel'), value: nonDiagnosis, color: COLORS.primary },
      { label: t('weeklyReportCharts.scenarioOtherWorkspaceLabel'), value: other, color: '#e5e7eb' },
    ].filter((item) => item.value > 0);
  }, [t, usageData.scenarioTotals]);
  const nonDiagnosticSubtitle = useMemo(
    () => t('weeklyReportCharts.nonDiagnosticSubtitle', {
      nonDiagnosis: usageData.scenarioTotals.nonDiagnosisWorkspaces,
      total: usageData.scenarioTotals.totalWorkspaces,
      nonDiagnosisPct: formatPct(usageData.scenarioTotals.nonDiagnosisWorkspaces, usageData.scenarioTotals.totalWorkspaces),
      unknown: usageData.scenarioTotals.unknownWorkspaces,
      unknownPct: formatPct(usageData.scenarioTotals.unknownWorkspaces, usageData.scenarioTotals.totalWorkspaces),
    }),
    [t, usageData.scenarioTotals],
  );

  return (
    <div style={{ fontFamily: FONT }}>
      <div style={{ marginBottom: 20 }}>
        <h2 style={{ margin: 0, fontSize: 22, fontWeight: 750, color: COLORS.text }}>
          {t('weeklyReportCharts.title')}
        </h2>
        <p style={{ margin: '6px 0 0', color: COLORS.muted, fontSize: 13, lineHeight: 1.6 }}>
          {t('weeklyReportCharts.subtitle')}
        </p>
        <DateRangeControl
          startDate={startDate}
          endDate={endDate}
          onStartDateChange={setStartDate}
          onEndDateChange={setEndDate}
          defaultStartDate={usageDates.defaultStartDate}
          defaultEndDate={usageDates.defaultEndDate}
          labels={{
            start: t('weeklyReportCharts.rangeStart'),
            end: t('weeklyReportCharts.rangeEnd'),
            reset: t('weeklyReportCharts.rangeReset'),
            available: t('weeklyReportCharts.rangeAvailable', {
              start: usageDates.defaultStartDate,
              end: t('home.group.day.today'),
            }),
          }}
        />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 12, marginBottom: 14 }}>
        {kpis.map((kpi) => (
          <KpiCard key={kpi.label} {...kpi} />
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(320px, 0.72fr)', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('weeklyReportCharts.evalScoresTitle')} subtitle={t('weeklyReportCharts.evalScoresSubtitle')}>
          <ScoreBars />
        </SectionCard>
        <SectionCard title={t('weeklyReportCharts.slowCasesTitle')} subtitle={t('weeklyReportCharts.slowCasesSubtitle')}>
          <SlowCaseTable
            headers={{
              case: t('weeklyReportCharts.caseColumn'),
              total: t('weeklyReportCharts.totalColumn'),
              diagnosis: t('weeklyReportCharts.diagnosisColumn'),
              routing: t('weeklyReportCharts.routingColumn'),
              elapsed: t('weeklyReportCharts.elapsedColumn'),
            }}
          />
        </SectionCard>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('weeklyReportCharts.weeklyTrendTitle')} subtitle={t('weeklyReportCharts.weeklyTrendSubtitle')}>
          <WeeklyTrendChart
            data={usageData.weeklyTrends}
            workspaceLabel={t('weeklyReportCharts.legendWorkspace')}
            activeUsersLabel={t('weeklyReportCharts.legendActiveUsers')}
            costLabel={t('weeklyReportCharts.legendCost')}
          />
        </SectionCard>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 14, marginBottom: 14 }}>
        <SectionCard
          title={t('weeklyReportCharts.profileSpendTitle')}
          subtitle={usageData.profileLastFactDate ? t('weeklyReportCharts.profileSpendSubtitleWithDate', { date: usageData.profileLastFactDate }) : t('weeklyReportCharts.profileSpendSubtitle')}
        >
          <ProfileSpendChart data={usageData.profileSpend} totalLabel={t('weeklyReportCharts.profileSpendTotal')} />
        </SectionCard>
      </div>

      <SectionCard title={t('weeklyReportCharts.behaviorTitle')} subtitle={t('weeklyReportCharts.behaviorSubtitle')}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <BehaviorMetricGrid
            metrics={usageData.behaviorMetrics}
            labels={{
              csvWs: t('weeklyReportCharts.behaviorMetricCsvWs'),
              wsWithMessages: t('weeklyReportCharts.behaviorMetricWsWithMessages'),
              messages: t('weeklyReportCharts.behaviorMetricMessages'),
              ratio: t('weeklyReportCharts.behaviorMetricRatio'),
            }}
          />
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 0.92fr) minmax(360px, 1.08fr)', gap: 18 }}>
            <AcpMessageRatioChart
              data={usageData.behaviorTeamPatterns}
              acpLabel={t('weeklyReportCharts.behaviorAcp')}
              messageLabel={t('weeklyReportCharts.behaviorMessages')}
              ratioLabel={t('weeklyReportCharts.behaviorRatioUnit')}
            />
            <BehaviorDistributionChart
              data={usageData.behaviorTeamPatterns}
              userMessagesLabel={t('weeklyReportCharts.behaviorUserMessages')}
            />
          </div>
        </div>
      </SectionCard>

      <div style={{ height: 14 }} />

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.08fr) minmax(300px, 0.92fr)', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('weeklyReportCharts.teamUsageTitle')} subtitle={t('weeklyReportCharts.teamUsageSubtitle')}>
          <TeamUsageChart teams={usageData.teamUsage} />
        </SectionCard>
        <SectionCard title={t('weeklyReportCharts.workspaceModesTitle')} subtitle={t('weeklyReportCharts.workspaceModesSubtitle')}>
          <WorkspaceModeChart
            data={usageData.workspaceModes}
            workspacesUnit={t('weeklyReportCharts.workspacesUnit')}
            usersUnit={t('weeklyReportCharts.usersUnit')}
          />
        </SectionCard>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(300px, 0.85fr)', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('weeklyReportCharts.diagnosticScenarioTitle')} subtitle={t('weeklyReportCharts.diagnosticScenarioSubtitle')}>
          <ScenarioList data={diagnosticScenarios} />
        </SectionCard>
        <SectionCard title={t('weeklyReportCharts.nonDiagnosticTitle')} subtitle={nonDiagnosticSubtitle}>
          <DonutChart data={nonDiagnosticRatio} size={150} />
          <div style={{ marginTop: 16 }}>
            <ScenarioList data={nonDiagnosticScenarios} />
          </div>
        </SectionCard>
      </div>
    </div>
  );
}
