import type { Meta, StoryObj } from '@storybook/react';
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
  ChartCard,
  DashboardBarChart,
  DashboardLineChart,
  HorizontalBarChart,
  InteractiveTimeSeriesChart,
  ComboMetricChart,
  DonutBreakdownChart,
  SparklineChart,
  RadarMetricChart,
  PieMetricChart,
  RadialBarMetricChart,
  GaugeChart,
  type ChartConfig,
  type GaugeChartThreshold,
} from './chart';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, LineChart, Line } from 'recharts';
import { Card, CardHeader, CardTitle, CardContent } from '../card';
import React from 'react';
import { TrendingUp, TrendingDown, Minus } from 'lucide-react';

const meta: Meta<typeof DashboardBarChart> = {
  title: 'UI/Chart',
  component: DashboardBarChart,
  render: args => <DashboardBarChart {...args} />,
  parameters: {
    layout: 'fullscreen',
  },
  decorators: [
    Story => (
      <div className="w-full min-w-0 p-8">
        <Story />
      </div>
    ),
  ],
  argTypes: {
    barSize: {
      control: 'select',
      options: ['sm', 'md', 'lg', 'xl'],
      description: 'Controls only the bar thickness.',
    },
    stacked: { control: 'boolean' },
    showGrid: { control: 'boolean' },
    showLegend: { control: 'boolean' },
  },
};

export default meta;
type Story = StoryObj<typeof DashboardBarChart>;

// ─── Shared data ──────────────────────────────────────────────────────────────

const data = [
  { month: 'Jan', revenue: 4000, expenses: 2400 },
  { month: 'Feb', revenue: 3000, expenses: 1398 },
  { month: 'Mar', revenue: 6000, expenses: 3200 },
  { month: 'Apr', revenue: 2780, expenses: 3908 },
  { month: 'May', revenue: 1890, expenses: 4800 },
  { month: 'Jun', revenue: 2390, expenses: 3800 },
];

const chartConfig: ChartConfig = {
  revenue: { label: 'Revenue', color: 'var(--chart-1)' },
  expenses: { label: 'Expenses', color: 'var(--chart-5)' },
};

const richChartConfig: ChartConfig = {
  revenue: { label: 'Revenue', color: 'var(--chart-1)' },
  pipeline: { label: 'Pipeline', color: 'var(--chart-4)' },
  conversion: { label: 'Conversion', color: 'var(--chart-2)' },
  churn: { label: 'Churn', color: 'var(--chart-5)' },
};

const richData = [
  { date: 'Apr 01', revenue: 4200, pipeline: 2600, conversion: 32, churn: 8 },
  { date: 'Apr 08', revenue: 5200, pipeline: 3200, conversion: 38, churn: 7 },
  { date: 'Apr 15', revenue: 6100, pipeline: 3900, conversion: 42, churn: 6 },
  { date: 'Apr 22', revenue: 5600, pipeline: 4300, conversion: 41, churn: 9 },
  { date: 'Apr 29', revenue: 7200, pipeline: 4700, conversion: 48, churn: 5 },
  { date: 'May 06', revenue: 7900, pipeline: 5300, conversion: 52, churn: 4 },
  { date: 'May 13', revenue: 8400, pipeline: 5800, conversion: 55, churn: 3 },
  { date: 'May 20', revenue: 9100, pipeline: 6200, conversion: 58, churn: 4 },
];

const breakdownConfig: ChartConfig = {
  enterprise: { label: 'Enterprise', color: 'var(--chart-1)' },
  midmarket: { label: 'Mid-market', color: 'var(--chart-4)' },
  startup: { label: 'Startup', color: 'var(--chart-2)' },
};

const breakdownData = [
  { name: 'enterprise', value: 52 },
  { name: 'midmarket', value: 31 },
  { name: 'startup', value: 17 },
];

// ─── Primitive stories ────────────────────────────────────────────────────────

export const BarChartExample: Story = {
  name: 'Primitive / Bar Chart',
  render: () => (
    <Card className="w-full max-w-4xl">
      <CardHeader>
        <CardTitle>Monthly Performance</CardTitle>
      </CardHeader>
      <CardContent>
        <ChartContainer config={chartConfig} className="h-[300px] w-full">
          <BarChart data={data}>
            <CartesianGrid vertical={false} strokeDasharray="3 3" />
            <XAxis dataKey="month" tickLine={false} axisLine={false} />
            <ChartTooltip content={<ChartTooltipContent />} />
            <ChartLegend content={<ChartLegendContent />} />
            <Bar dataKey="revenue" fill="var(--color-revenue)" radius={[4, 4, 0, 0]} />
            <Bar dataKey="expenses" fill="var(--color-expenses)" radius={[4, 4, 0, 0]} />
          </BarChart>
        </ChartContainer>
      </CardContent>
    </Card>
  ),
};

export const LineChartExample: Story = {
  name: 'Primitive / Line Chart',
  render: () => (
    <Card className="w-full max-w-4xl">
      <CardHeader>
        <CardTitle>Revenue Trends</CardTitle>
      </CardHeader>
      <CardContent>
        <ChartContainer config={chartConfig} className="h-[300px] w-full">
          <LineChart data={data}>
            <CartesianGrid vertical={false} strokeDasharray="3 3" />
            <XAxis dataKey="month" tickLine={false} axisLine={false} />
            <ChartTooltip content={<ChartTooltipContent />} />
            <Line
              type="monotone"
              dataKey="revenue"
              stroke="var(--color-revenue)"
              strokeWidth={3}
              dot={{ r: 4, fill: 'var(--color-revenue)', strokeWidth: 0 }}
              activeDot={{ r: 6, strokeWidth: 0 }}
            />
          </LineChart>
        </ChartContainer>
      </CardContent>
    </Card>
  ),
};

// ─── Dashboard chart stories ──────────────────────────────────────────────────

export const DashboardBarChartExample: Story = {
  name: 'Bar Chart',
  args: {
    data: richData,
    indexKey: 'date',
    config: richChartConfig,
    colors: {
      revenue: 'var(--chart-1)',
      pipeline: 'var(--chart-4)',
    },
    barSize: 'lg',
    series: [
      { key: 'revenue', stackId: 'money' },
      { key: 'pipeline', stackId: 'money' },
    ],
    stacked: true,
  },
  render: args => (
    <ChartCard title="Revenue by Week" description="Stacked dashboard-ready comparison">
      <DashboardBarChart {...args} />
    </ChartCard>
  ),
};

export const DashboardLineChartExample: Story = {
  name: 'Line Chart',
  render: () => (
    <ChartCard title="Growth Trend" description="Multi-series line chart with smooth curves">
      <DashboardLineChart
        data={richData}
        indexKey="date"
        config={richChartConfig}
        colors={{
          revenue: 'var(--chart-1)',
          pipeline: 'var(--chart-4)',
          conversion: 'var(--chart-2)',
        }}
        series={[
          { key: 'revenue', label: 'Revenue' },
          { key: 'pipeline', label: 'Pipeline' },
          { key: 'conversion', label: 'Conversion' },
        ]}
        showDots
        curveType="monotone"
        strokeWidth={2.5}
      />
    </ChartCard>
  ),
};

export const HorizontalBarChartExample: Story = {
  name: 'Horizontal Bar Chart',
  render: () => (
    <ChartCard title="Top Segments" description="Ranking chart for dashboard comparisons">
      <HorizontalBarChart
        data={[
          { segment: 'Enterprise', revenue: 7600 },
          { segment: 'Mid-market', revenue: 5400 },
          { segment: 'Startup', revenue: 3100 },
          { segment: 'Partners', revenue: 2200 },
        ]}
        indexKey="segment"
        config={{ revenue: { label: 'Revenue', color: 'var(--chart-1)' } }}
        colors={{ revenue: 'var(--chart-1)' }}
        barSize="xl"
        categoryWidth={110}
        showLegend={false}
      />
    </ChartCard>
  ),
};

export const InteractiveTimeSeriesExample: Story = {
  name: 'Interactive Time Series',
  render: () => (
    <ChartCard
      title="Executive Trend"
      description="Switch metric and period without leaving the card"
    >
      <InteractiveTimeSeriesChart
        data={richData}
        indexKey="date"
        config={richChartConfig}
        colors={['var(--chart-1)', 'var(--chart-4)', 'var(--chart-2)']}
        series={[
          { key: 'revenue', label: 'Revenue' },
          { key: 'pipeline', label: 'Pipeline' },
          { key: 'conversion', label: 'Conversion' },
        ]}
        gradientFill
      />
    </ChartCard>
  ),
};

export const GradientAreaChartExample: Story = {
  name: 'Gradient Area Chart',
  render: () => (
    <ChartCard
      title="Revenue Over Time"
      description="Area chart with gradient fill for a modern look"
    >
      <InteractiveTimeSeriesChart
        data={richData}
        indexKey="date"
        config={{ revenue: { label: 'Revenue', color: 'var(--chart-1)' } }}
        colors={['var(--chart-1)']}
        series={[{ key: 'revenue', label: 'Revenue' }]}
        gradientFill
        showDots
        periods={[
          { value: '7d', label: '7 days' },
          { value: '30d', label: '30 days' },
        ]}
      />
    </ChartCard>
  ),
};

export const ComboMetricChartExample: Story = {
  name: 'Combo Metric Chart',
  render: () => (
    <ChartCard title="Pipeline Health" description="Bars for volume with a line for rate">
      <ComboMetricChart
        data={richData}
        indexKey="date"
        config={richChartConfig}
        colors={{
          pipeline: 'var(--chart-4)',
          conversion: 'var(--chart-2)',
        }}
        barSize="lg"
        series={[
          { key: 'pipeline', type: 'bar' },
          { key: 'conversion', type: 'line' },
        ]}
      />
    </ChartCard>
  ),
};

export const ComboWithGradientAreaExample: Story = {
  name: 'Combo Chart with Gradient Area',
  render: () => (
    <ChartCard
      title="Revenue & Pipeline"
      description="Gradient area for revenue, line for conversion rate"
    >
      <ComboMetricChart
        data={richData}
        indexKey="date"
        config={richChartConfig}
        colors={{
          revenue: 'var(--chart-1)',
          conversion: 'var(--chart-2)',
        }}
        series={[
          { key: 'revenue', type: 'area' },
          { key: 'conversion', type: 'line' },
        ]}
        gradientFill
        curveType="monotone"
      />
    </ChartCard>
  ),
};

export const DonutBreakdownExample: Story = {
  name: 'Donut Chart',
  render: () => (
    <ChartCard title="Customer Mix" description="Interactive segment breakdown">
      <DonutBreakdownChart
        data={breakdownData}
        config={breakdownConfig}
        colors={['var(--chart-1)', 'var(--chart-4)', 'var(--chart-2)']}
        centerValue="100%"
        centerLabel="Accounts"
      />
    </ChartCard>
  ),
};

// ─── Sparkline stories ────────────────────────────────────────────────────────

const sparkData = [
  { v: 12 },
  { v: 18 },
  { v: 14 },
  { v: 22 },
  { v: 19 },
  { v: 28 },
  { v: 24 },
  { v: 31 },
  { v: 27 },
  { v: 35 },
];

const sparkDataDown = [
  { v: 35 },
  { v: 30 },
  { v: 28 },
  { v: 22 },
  { v: 25 },
  { v: 18 },
  { v: 20 },
  { v: 14 },
  { v: 12 },
  { v: 8 },
];

export const SparklineExample: Story = {
  name: 'Sparkline Chart',
  render: () => (
    <div className="space-y-6 max-w-2xl">
      <p className="text-sm text-muted-foreground">
        Sparklines are minimal inline charts designed for stat cards and table cells.
      </p>

      {/* Stat cards with sparklines */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card className="p-4">
          <div className="flex items-start justify-between mb-3">
            <div>
              <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
                Revenue
              </p>
              <p className="text-2xl font-bold mt-0.5">$35.2K</p>
            </div>
            <span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-600 bg-emerald-50 dark:bg-emerald-950 dark:text-emerald-400 px-2 py-0.5 rounded-full">
              <TrendingUp className="size-3" />
              +12%
            </span>
          </div>
          <SparklineChart
            data={sparkData}
            dataKey="v"
            color="var(--chart-2)"
            filled
            showEndDot
            className="h-12"
          />
        </Card>

        <Card className="p-4">
          <div className="flex items-start justify-between mb-3">
            <div>
              <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
                Churn
              </p>
              <p className="text-2xl font-bold mt-0.5">8.4%</p>
            </div>
            <span className="inline-flex items-center gap-1 text-xs font-medium text-red-600 bg-red-50 dark:bg-red-950 dark:text-red-400 px-2 py-0.5 rounded-full">
              <TrendingDown className="size-3" />
              -3%
            </span>
          </div>
          <SparklineChart
            data={sparkDataDown}
            dataKey="v"
            color="var(--chart-5)"
            filled
            showEndDot
            className="h-12"
          />
        </Card>

        <Card className="p-4">
          <div className="flex items-start justify-between mb-3">
            <div>
              <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
                Pipeline
              </p>
              <p className="text-2xl font-bold mt-0.5">$128K</p>
            </div>
            <span className="inline-flex items-center gap-1 text-xs font-medium text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
              <Minus className="size-3" />
              0%
            </span>
          </div>
          <SparklineChart
            data={[
              { v: 20 },
              { v: 22 },
              { v: 19 },
              { v: 23 },
              { v: 21 },
              { v: 24 },
              { v: 22 },
              { v: 25 },
              { v: 23 },
              { v: 24 },
            ]}
            dataKey="v"
            color="var(--chart-4)"
            filled
            showEndDot
            className="h-12"
          />
        </Card>
      </div>

      {/* Sparkline variants */}
      <ChartCard title="Sparkline Variants" description="Line-only vs filled area">
        <div className="space-y-4 py-2">
          <div className="flex items-center gap-4">
            <span className="text-xs text-muted-foreground w-24 shrink-0">Filled (default)</span>
            <SparklineChart
              data={sparkData}
              dataKey="v"
              color="var(--chart-1)"
              filled
              className="h-10 flex-1"
            />
          </div>
          <div className="flex items-center gap-4">
            <span className="text-xs text-muted-foreground w-24 shrink-0">Line only</span>
            <SparklineChart
              data={sparkData}
              dataKey="v"
              color="var(--chart-3)"
              filled={false}
              showEndDot={false}
              className="h-10 flex-1"
            />
          </div>
          <div className="flex items-center gap-4">
            <span className="text-xs text-muted-foreground w-24 shrink-0">Step curve</span>
            <SparklineChart
              data={sparkData}
              dataKey="v"
              color="var(--chart-6)"
              filled
              curveType="step"
              className="h-10 flex-1"
            />
          </div>
        </div>
      </ChartCard>
    </div>
  ),
};

// ─── Dashboard layout story ───────────────────────────────────────────────────

export const DashboardLayoutExample: Story = {
  name: 'Dashboard Layout',
  render: () => {
    const kpiData = [
      {
        label: 'Total Revenue',
        value: '$128.4K',
        trend: '+18%',
        up: true,
        sparkData: sparkData,
        color: 'var(--chart-1)',
      },
      {
        label: 'Active Pipeline',
        value: '$62.1K',
        trend: '+9%',
        up: true,
        sparkData: sparkData.map(d => ({ v: d.v * 0.7 })),
        color: 'var(--chart-4)',
      },
      {
        label: 'Conversion Rate',
        value: '58%',
        trend: '+4%',
        up: true,
        sparkData: sparkData.map(d => ({ v: d.v * 0.5 })),
        color: 'var(--chart-2)',
      },
      {
        label: 'Churn Rate',
        value: '3.2%',
        trend: '-1%',
        up: false,
        sparkData: sparkDataDown,
        color: 'var(--chart-5)',
      },
    ];

    return (
      <div className="space-y-6">
        {/* KPI row */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {kpiData.map(kpi => (
            <Card key={kpi.label} className="p-4">
              <div className="flex items-start justify-between mb-3">
                <div>
                  <p className="text-xs text-muted-foreground font-medium">{kpi.label}</p>
                  <p className="text-xl font-bold mt-0.5">{kpi.value}</p>
                </div>
                <span
                  className={`inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full ${
                    kpi.up
                      ? 'text-emerald-600 bg-emerald-50 dark:bg-emerald-950 dark:text-emerald-400'
                      : 'text-red-600 bg-red-50 dark:bg-red-950 dark:text-red-400'
                  }`}
                >
                  {kpi.up ? <TrendingUp className="size-3" /> : <TrendingDown className="size-3" />}
                  {kpi.trend}
                </span>
              </div>
              <SparklineChart
                data={kpi.sparkData}
                dataKey="v"
                color={kpi.color}
                filled
                showEndDot
                className="h-10"
              />
            </Card>
          ))}
        </div>

        {/* Main charts row */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="lg:col-span-2">
            <ChartCard title="Revenue & Pipeline" description="Weekly performance overview">
              <InteractiveTimeSeriesChart
                data={richData}
                indexKey="date"
                config={richChartConfig}
                colors={['var(--chart-1)', 'var(--chart-4)', 'var(--chart-2)']}
                series={[
                  { key: 'revenue', label: 'Revenue' },
                  { key: 'pipeline', label: 'Pipeline' },
                  { key: 'conversion', label: 'Conversion' },
                ]}
                gradientFill
                periods={[
                  { value: '7d', label: '7 days' },
                  { value: '30d', label: '30 days' },
                ]}
              />
            </ChartCard>
          </div>

          <ChartCard title="Customer Mix" description="Segment breakdown">
            <DonutBreakdownChart
              data={breakdownData}
              config={breakdownConfig}
              colors={['var(--chart-1)', 'var(--chart-4)', 'var(--chart-2)']}
              centerValue="100%"
              centerLabel="Accounts"
            />
          </ChartCard>
        </div>

        {/* Bottom row */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          <ChartCard title="Top Segments" description="Revenue by customer segment">
            <HorizontalBarChart
              data={[
                { segment: 'Enterprise', revenue: 7600 },
                { segment: 'Mid-market', revenue: 5400 },
                { segment: 'Startup', revenue: 3100 },
                { segment: 'Partners', revenue: 2200 },
              ]}
              indexKey="segment"
              config={{ revenue: { label: 'Revenue', color: 'var(--chart-1)' } }}
              colors={{ revenue: 'var(--chart-1)' }}
              barSize="xl"
              categoryWidth={110}
              showLegend={false}
            />
          </ChartCard>

          <ChartCard title="Pipeline Health" description="Volume vs conversion rate">
            <ComboMetricChart
              data={richData}
              indexKey="date"
              config={richChartConfig}
              colors={{
                pipeline: 'var(--chart-4)',
                conversion: 'var(--chart-2)',
              }}
              barSize="lg"
              series={[
                { key: 'pipeline', type: 'bar' },
                { key: 'conversion', type: 'line' },
              ]}
            />
          </ChartCard>
        </div>
      </div>
    );
  },
};

// ─── State stories ────────────────────────────────────────────────────────────

export const EmptyStateExample: Story = {
  name: 'State / Empty',
  render: () => (
    <ChartCard
      title="Revenue by Week"
      description="The empty state is rendered by the chart wrapper"
    >
      <DashboardBarChart
        data={[]}
        indexKey="date"
        config={richChartConfig}
        emptyDescription="No revenue events were found for the selected period."
      />
    </ChartCard>
  ),
};

export const ConnectionErrorExample: Story = {
  name: 'State / Connection Error',
  render: () => (
    <ChartCard title="Pipeline Health" description="Connection errors stay inside the chart panel">
      <ComboMetricChart
        data={richData}
        indexKey="date"
        config={richChartConfig}
        error="Unable to connect to the analytics service."
        onRetry={() => undefined}
      />
    </ChartCard>
  ),
};

export const LoadingStateExample: Story = {
  name: 'State / Loading',
  render: () => (
    <ChartCard title="Revenue by Week" description="Loading skeleton while data is fetched">
      <DashboardBarChart data={[]} indexKey="date" config={richChartConfig} isLoading />
    </ChartCard>
  ),
};

// ─── Variant stories ──────────────────────────────────────────────────────────

export const BarSizeVariantsExample: Story = {
  name: 'Variants / Bar Sizes',
  render: () => (
    <div className="space-y-6">
      <ChartCard title="Thin Bars" description='barSize="sm"'>
        <DashboardBarChart
          data={richData}
          indexKey="date"
          config={richChartConfig}
          series={[{ key: 'revenue' }]}
          barSize="sm"
          showLegend={false}
        />
      </ChartCard>
      <ChartCard title="Wide Bars" description='barSize="xl"'>
        <DashboardBarChart
          data={richData}
          indexKey="date"
          config={richChartConfig}
          series={[{ key: 'revenue' }]}
          barSize="xl"
          showLegend={false}
        />
      </ChartCard>
    </div>
  ),
};

export const CurveTypeVariantsExample: Story = {
  name: 'Variants / Curve Types',
  render: () => (
    <div className="space-y-6">
      {(['monotone', 'linear', 'step', 'natural', 'basis'] as const).map(curve => (
        <ChartCard
          key={curve}
          title={`curveType="${curve}"`}
          description="Line chart curve interpolation"
        >
          <DashboardLineChart
            data={richData}
            indexKey="date"
            config={{ revenue: { label: 'Revenue', color: 'var(--chart-1)' } }}
            series={[{ key: 'revenue' }]}
            curveType={curve}
            showLegend={false}
            showDots={curve === 'linear'}
          />
        </ChartCard>
      ))}
    </div>
  ),
};

export const ColorPaletteExample: Story = {
  name: 'Variants / Color Palette',
  render: () => {
    const paletteConfig: ChartConfig = {
      chart1: { label: 'chart-1 (indigo)', color: 'var(--chart-1)' },
      chart2: { label: 'chart-2 (emerald)', color: 'var(--chart-2)' },
      chart3: { label: 'chart-3 (amber)', color: 'var(--chart-3)' },
      chart4: { label: 'chart-4 (blue)', color: 'var(--chart-4)' },
      chart5: { label: 'chart-5 (red)', color: 'var(--chart-5)' },
      chart6: { label: 'chart-6 (purple)', color: 'var(--chart-6)' },
      chart7: { label: 'chart-7 (teal)', color: 'var(--chart-7)' },
      chart8: { label: 'chart-8 (rose)', color: 'var(--chart-8)' },
    };

    const paletteData = [
      {
        name: 'A',
        chart1: 80,
        chart2: 70,
        chart3: 60,
        chart4: 75,
        chart5: 55,
        chart6: 65,
        chart7: 72,
        chart8: 68,
      },
    ];

    return (
      <ChartCard
        title="Chart Color Palette"
        description="All 8 chart tokens — vibrant, accessible, harmonious"
      >
        <DashboardBarChart
          data={paletteData}
          indexKey="name"
          config={paletteConfig}
          barSize="xl"
          showGrid={false}
        />
      </ChartCard>
    );
  },
};

// ─── Radar Chart Stories ───────────────────────────────────────────────────────

const radarData = [
  { skill: 'Performance', score: 88 },
  { skill: 'Reliability', score: 72 },
  { skill: 'Security', score: 95 },
  { skill: 'Scalability', score: 65 },
  { skill: 'Usability', score: 80 },
  { skill: 'Maintainability', score: 58 },
];

const radarMultiData = [
  { skill: 'Performance', teamA: 88, teamB: 62 },
  { skill: 'Reliability', teamA: 72, teamB: 85 },
  { skill: 'Security', teamA: 95, teamB: 70 },
  { skill: 'Scalability', teamA: 65, teamB: 90 },
  { skill: 'Usability', teamA: 80, teamB: 55 },
  { skill: 'Maintainability', teamA: 58, teamB: 78 },
];

export const RadarChartFilled: Story = {
  name: 'Radar Chart / Filled',
  render: () => (
    <ChartCard title="System Health Score" description="Filled radar — single series">
      <RadarMetricChart
        data={radarData}
        labelKey="skill"
        series={[{ key: 'score', label: 'Score' }]}
        filled
        showLegend={false}
      />
    </ChartCard>
  ),
};

export const RadarChartOutline: Story = {
  name: 'Radar Chart / Outline',
  render: () => (
    <ChartCard title="System Health Score" description="Outline only — no fill">
      <RadarMetricChart
        data={radarData}
        labelKey="skill"
        series={[{ key: 'score', label: 'Score' }]}
        filled={false}
        showDots
        showLegend={false}
      />
    </ChartCard>
  ),
};

export const RadarChartMultiSeries: Story = {
  name: 'Radar Chart / Multi-Series',
  render: () => (
    <ChartCard title="Team Comparison" description="Two teams across 6 dimensions">
      <RadarMetricChart
        data={radarMultiData}
        labelKey="skill"
        series={[
          { key: 'teamA', label: 'Team Alpha' },
          { key: 'teamB', label: 'Team Beta' },
        ]}
        filled
        fillOpacity={0.2}
        showDots
      />
    </ChartCard>
  ),
};

export const RadarChartVariants: Story = {
  name: 'Radar Chart / All Variants',
  render: () => (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
      <ChartCard title="Filled" description="Default filled area">
        <RadarMetricChart
          data={radarData}
          labelKey="skill"
          series={[{ key: 'score', label: 'Score' }]}
          filled
          showLegend={false}
        />
      </ChartCard>
      <ChartCard title="Outline + Dots" description="No fill, with dots">
        <RadarMetricChart
          data={radarData}
          labelKey="skill"
          series={[{ key: 'score', label: 'Score' }]}
          filled={false}
          showDots
          showLegend={false}
        />
      </ChartCard>
      <ChartCard title="Multi-Series" description="Comparison overlay">
        <RadarMetricChart
          data={radarMultiData}
          labelKey="skill"
          series={[
            { key: 'teamA', label: 'Team A' },
            { key: 'teamB', label: 'Team B' },
          ]}
          filled
          fillOpacity={0.18}
        />
      </ChartCard>
    </div>
  ),
};

// ─── Pie Chart Stories ────────────────────────────────────────────────────────

const pieData = [
  { category: 'Infrastructure', spend: 42000 },
  { category: 'Engineering', spend: 31000 },
  { category: 'Marketing', spend: 18500 },
  { category: 'Operations', spend: 12000 },
  { category: 'Other', spend: 6500 },
];

export const PieChartSimple: Story = {
  name: 'Pie Chart / Simple',
  render: () => (
    <ChartCard title="Budget Breakdown" description="Simple pie — no labels">
      <PieMetricChart
        data={pieData}
        nameKey="category"
        valueKey="spend"
        valueFormatter={v => `$${(v as number).toLocaleString()}`}
      />
    </ChartCard>
  ),
};

export const PieChartWithLabels: Story = {
  name: 'Pie Chart / With Labels',
  render: () => (
    <ChartCard title="Budget Breakdown" description="Pie with percentage labels">
      <PieMetricChart
        data={pieData}
        nameKey="category"
        valueKey="spend"
        showLabels
        valueFormatter={v => `$${(v as number).toLocaleString()}`}
      />
    </ChartCard>
  ),
};

export const PieChartExploded: Story = {
  name: 'Pie Chart / Exploded Slice',
  render: () => (
    <ChartCard title="Budget Breakdown" description="Largest slice highlighted with drop shadow">
      <PieMetricChart
        data={pieData}
        nameKey="category"
        valueKey="spend"
        showLabels
        explodeIndex={0}
        valueFormatter={v => `$${(v as number).toLocaleString()}`}
      />
    </ChartCard>
  ),
};

export const PieChartDonutVariant: Story = {
  name: 'Pie Chart / Donut Variant',
  render: () => (
    <ChartCard title="Budget Breakdown" description="Pie with inner radius (donut style)">
      <PieMetricChart
        data={pieData}
        nameKey="category"
        valueKey="spend"
        innerRadius="45%"
        showLabels
        valueFormatter={v => `$${(v as number).toLocaleString()}`}
      />
    </ChartCard>
  ),
};

export const PieChartVariants: Story = {
  name: 'Pie Chart / All Variants',
  render: () => (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      <ChartCard title="Simple" description="No labels">
        <PieMetricChart data={pieData} nameKey="category" valueKey="spend" />
      </ChartCard>
      <ChartCard title="With Labels" description="Percentage labels">
        <PieMetricChart data={pieData} nameKey="category" valueKey="spend" showLabels />
      </ChartCard>
      <ChartCard title="Exploded" description="First slice highlighted">
        <PieMetricChart
          data={pieData}
          nameKey="category"
          valueKey="spend"
          showLabels
          explodeIndex={0}
        />
      </ChartCard>
      <ChartCard title="Donut" description="Inner radius 45%">
        <PieMetricChart
          data={pieData}
          nameKey="category"
          valueKey="spend"
          innerRadius="45%"
          showLabels
        />
      </ChartCard>
    </div>
  ),
};

// ─── Radial Bar Chart Stories ─────────────────────────────────────────────────

const radialData = [
  { name: 'Infrastructure', value: 78 },
  { name: 'Engineering', value: 62 },
  { name: 'Marketing', value: 45 },
  { name: 'Operations', value: 91 },
];

export const RadialBarChartSingle: Story = {
  name: 'Radial Bar / Single Bar',
  render: () => (
    <ChartCard title="Deployment Success Rate" description="Single radial bar — full circle">
      <RadialBarMetricChart
        data={[{ name: 'Success Rate', value: 87 }]}
        dataKey="value"
        nameKey="name"
        showLegend={false}
        innerRadius="60%"
        outerRadius="90%"
        valueFormatter={v => `${v}%`}
      />
    </ChartCard>
  ),
};

export const RadialBarChartMulti: Story = {
  name: 'Radial Bar / Multi-Bar',
  render: () => (
    <ChartCard title="Department KPIs" description="Multiple radial bars with background track">
      <RadialBarMetricChart
        data={radialData}
        dataKey="value"
        nameKey="name"
        innerRadius="20%"
        outerRadius="90%"
        valueFormatter={v => `${v}%`}
      />
    </ChartCard>
  ),
};

export const RadialBarChartSemiCircle: Story = {
  name: 'Radial Bar / Semi-Circle',
  render: () => (
    <ChartCard
      title="Department KPIs"
      description="Semi-circle layout (startAngle=180, endAngle=0)"
    >
      <RadialBarMetricChart
        data={radialData}
        dataKey="value"
        nameKey="name"
        innerRadius="30%"
        outerRadius="90%"
        startAngle={180}
        endAngle={0}
        valueFormatter={v => `${v}%`}
      />
    </ChartCard>
  ),
};

export const RadialBarChartVariants: Story = {
  name: 'Radial Bar / All Variants',
  render: () => (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
      <ChartCard title="Single Bar" description="Full circle">
        <RadialBarMetricChart
          data={[{ name: 'Success', value: 87 }]}
          dataKey="value"
          nameKey="name"
          showLegend={false}
          innerRadius="60%"
          outerRadius="90%"
          valueFormatter={v => `${v}%`}
        />
      </ChartCard>
      <ChartCard title="Multi-Bar" description="Stacked radial bars">
        <RadialBarMetricChart
          data={radialData}
          dataKey="value"
          nameKey="name"
          innerRadius="20%"
          outerRadius="90%"
          valueFormatter={v => `${v}%`}
        />
      </ChartCard>
      <ChartCard title="Semi-Circle" description="180° arc layout">
        <RadialBarMetricChart
          data={radialData}
          dataKey="value"
          nameKey="name"
          innerRadius="30%"
          outerRadius="90%"
          startAngle={180}
          endAngle={0}
          valueFormatter={v => `${v}%`}
        />
      </ChartCard>
    </div>
  ),
};

// ─── Gauge Chart Stories ──────────────────────────────────────────────────────

const gaugeThresholds: GaugeChartThreshold[] = [
  { value: 33, color: 'var(--chart-5)', label: 'Critical' },
  { value: 66, color: 'var(--chart-3)', label: 'Warning' },
  { value: 100, color: 'var(--chart-2)', label: 'Healthy' },
];

export const GaugeChartSimple: Story = {
  name: 'Gauge Chart / Simple',
  render: () => (
    <ChartCard
      title="CPU Usage"
      description="Simple gauge — single color"
      className="max-w-sm mx-auto"
    >
      <div className="flex justify-center py-4">
        <GaugeChart value={67} label="CPU Usage" />
      </div>
    </ChartCard>
  ),
};

export const GaugeChartWithThresholds: Story = {
  name: 'Gauge Chart / With Thresholds',
  render: () => (
    <ChartCard
      title="System Health"
      description="Color zones: critical / warning / healthy"
      className="max-w-sm mx-auto"
    >
      <div className="flex justify-center py-4">
        <GaugeChart value={72} label="Overall Health" thresholds={gaugeThresholds} />
      </div>
    </ChartCard>
  ),
};

export const GaugeChartNoNeedle: Story = {
  name: 'Gauge Chart / No Needle',
  render: () => (
    <ChartCard
      title="Memory Usage"
      description="Arc only — no needle indicator"
      className="max-w-sm mx-auto"
    >
      <div className="flex justify-center py-4">
        <GaugeChart value={45} label="Memory" showNeedle={false} thresholds={gaugeThresholds} />
      </div>
    </ChartCard>
  ),
};

export const GaugeChartVariants: Story = {
  name: 'Gauge Chart / All Variants',
  render: () => (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
      <ChartCard title="Low (22%)" description="Critical zone">
        <div className="flex justify-center py-2">
          <GaugeChart value={22} label="CPU" thresholds={gaugeThresholds} />
        </div>
      </ChartCard>
      <ChartCard title="Medium (55%)" description="Warning zone">
        <div className="flex justify-center py-2">
          <GaugeChart value={55} label="Memory" thresholds={gaugeThresholds} />
        </div>
      </ChartCard>
      <ChartCard title="High (88%)" description="Healthy zone">
        <div className="flex justify-center py-2">
          <GaugeChart value={88} label="Disk I/O" thresholds={gaugeThresholds} />
        </div>
      </ChartCard>
    </div>
  ),
};

export const GaugeChartDashboard: Story = {
  name: 'Gauge Chart / Infrastructure Dashboard',
  render: () => {
    const metrics = [
      { label: 'CPU', value: 34, unit: '%' },
      { label: 'Memory', value: 71, unit: '%' },
      { label: 'Disk', value: 58, unit: '%' },
      { label: 'Network', value: 22, unit: '%' },
    ];

    return (
      <div className="space-y-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {metrics.map(m => (
            <ChartCard key={m.label} title={m.label} description={`Current ${m.label} utilization`}>
              <div className="flex justify-center py-2">
                <GaugeChart
                  value={m.value}
                  label={m.label}
                  thresholds={gaugeThresholds}
                  valueFormatter={v => `${v}${m.unit}`}
                />
              </div>
            </ChartCard>
          ))}
        </div>
      </div>
    );
  },
};

// ─── Complete Chart Library Overview ─────────────────────────────────────────

export const CompleteLibraryOverview: Story = {
  name: 'Complete Library / All Chart Types',
  render: () => (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {/* Bar */}
        <ChartCard title="Bar Chart" description="Categorical comparison">
          <DashboardBarChart
            data={[
              { month: 'Jan', revenue: 42000 },
              { month: 'Feb', revenue: 38000 },
              { month: 'Mar', revenue: 51000 },
              { month: 'Apr', revenue: 47000 },
              { month: 'May', revenue: 55000 },
            ]}
            indexKey="month"
            config={{ revenue: { label: 'Revenue', color: 'var(--chart-1)' } }}
            series={[{ key: 'revenue', label: 'Revenue' }]}
            showLegend={false}
          />
        </ChartCard>

        {/* Line */}
        <ChartCard title="Line Chart" description="Trend over time">
          <DashboardLineChart
            data={[
              { month: 'Jan', users: 1200 },
              { month: 'Feb', users: 1450 },
              { month: 'Mar', users: 1380 },
              { month: 'Apr', users: 1620 },
              { month: 'May', users: 1890 },
            ]}
            indexKey="month"
            config={{ users: { label: 'Users', color: 'var(--chart-2)' } }}
            series={[{ key: 'users', label: 'Users' }]}
            showLegend={false}
          />
        </ChartCard>

        {/* Donut */}
        <ChartCard title="Donut Chart" description="Part-to-whole">
          <DonutBreakdownChart
            data={[
              { name: 'Active', value: 68 },
              { name: 'Idle', value: 22 },
              { name: 'Offline', value: 10 },
            ]}
            nameKey="name"
            valueKey="value"
            config={{
              Active: { label: 'Active', color: 'var(--chart-2)' },
              Idle: { label: 'Idle', color: 'var(--chart-3)' },
              Offline: { label: 'Offline', color: 'var(--chart-5)' },
            }}
            centerValue="68%"
            centerLabel="Active"
            showLegend={false}
          />
        </ChartCard>

        {/* Radar */}
        <ChartCard title="Radar Chart" description="Multi-dimensional">
          <RadarMetricChart
            data={radarData}
            labelKey="skill"
            series={[{ key: 'score', label: 'Score' }]}
            filled
            showLegend={false}
          />
        </ChartCard>

        {/* Pie */}
        <ChartCard title="Pie Chart" description="Proportional slices">
          <PieMetricChart
            data={pieData}
            nameKey="category"
            valueKey="spend"
            showLabels
            showLegend={false}
          />
        </ChartCard>

        {/* Radial Bar */}
        <ChartCard title="Radial Bar" description="Progress rings">
          <RadialBarMetricChart
            data={radialData}
            dataKey="value"
            nameKey="name"
            innerRadius="20%"
            outerRadius="90%"
            valueFormatter={v => `${v}%`}
          />
        </ChartCard>
      </div>

      {/* Gauge row */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {[
          { label: 'CPU', value: 34 },
          { label: 'Memory', value: 71 },
          { label: 'Disk', value: 58 },
        ].map(m => (
          <ChartCard key={m.label} title={`Gauge — ${m.label}`} description="Semicircle gauge">
            <div className="flex justify-center py-2">
              <GaugeChart value={m.value} label={m.label} thresholds={gaugeThresholds} />
            </div>
          </ChartCard>
        ))}
      </div>
    </div>
  ),
};
