'use client';

import {
  Area,
  AreaChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

import type { UmamiPageviewsSeries } from '@/lib/services/umami.service';

interface Props {
  data: UmamiPageviewsSeries | null;
}

/**
 * Stacks pageviews on top of sessions in a simple area chart. Umami's
 * timeseries comes pre-bucketed (the service picks bucket size based on
 * range span - minute/hour/day/month).
 *
 * X-axis labels are kept short to avoid overflow on dense ranges.
 */
export function PageviewsChart({ data }: Props) {
  if (!data || data.pageviews.length === 0) {
    return (
      <div className="flex h-[260px] items-center justify-center text-sm text-muted-foreground">
        No data in this range
      </div>
    );
  }

  // Merge the two series (Umami returns them separately) into one row per
  // bucket so we can drive a single chart.
  const byX = new Map<string, { x: string; pageviews: number; sessions: number }>();
  for (const p of data.pageviews) {
    byX.set(p.x, { x: p.x, pageviews: p.y, sessions: 0 });
  }
  for (const s of data.sessions) {
    const row = byX.get(s.x);
    if (row) row.sessions = s.y;
    else byX.set(s.x, { x: s.x, pageviews: 0, sessions: s.y });
  }
  const merged = Array.from(byX.values()).sort((a, b) => a.x.localeCompare(b.x));

  return (
    <ResponsiveContainer width="100%" height={260}>
      <AreaChart data={merged} margin={{ top: 8, right: 12, left: 0, bottom: 4 }}>
        <defs>
          <linearGradient id="pvFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="hsl(var(--chart-1))" stopOpacity={0.6} />
            <stop offset="100%" stopColor="hsl(var(--chart-1))" stopOpacity={0.05} />
          </linearGradient>
          <linearGradient id="sessFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="hsl(var(--chart-2))" stopOpacity={0.5} />
            <stop offset="100%" stopColor="hsl(var(--chart-2))" stopOpacity={0.04} />
          </linearGradient>
        </defs>
        <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
        <XAxis
          dataKey="x"
          fontSize={11}
          tick={{ fill: 'hsl(var(--muted-foreground))' }}
          tickFormatter={formatXTick}
        />
        <YAxis
          fontSize={11}
          tick={{ fill: 'hsl(var(--muted-foreground))' }}
          allowDecimals={false}
        />
        <Tooltip
          contentStyle={{
            background: 'hsl(var(--popover))',
            border: '1px solid hsl(var(--border))',
            borderRadius: '6px',
            fontSize: 12,
          }}
        />
        <Legend wrapperStyle={{ fontSize: 12 }} />
        <Area
          type="monotone"
          dataKey="pageviews"
          stroke="hsl(var(--chart-1))"
          fill="url(#pvFill)"
          strokeWidth={2}
          name="Pageviews"
        />
        <Area
          type="monotone"
          dataKey="sessions"
          stroke="hsl(var(--chart-2))"
          fill="url(#sessFill)"
          strokeWidth={2}
          name="Sessions"
        />
      </AreaChart>
    </ResponsiveContainer>
  );
}

/** Compact tick labels: full datetime → just MM-DD or MM-DD HH:00. */
function formatXTick(value: string): string {
  // Umami can return either "YYYY-MM-DD HH:mm:ss" or "YYYY-MM-DD".
  if (value.length >= 16) {
    return value.slice(5, 16); // "MM-DD HH:mm"
  }
  return value.slice(5); // "MM-DD"
}
