"use client";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Legend, Line, ComposedChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

/** Brand-derived categorical palette: Tempest red, violet, ink, plus supporting hues with adequate contrast in both themes. */
export const PALETTE = ["#2563EB", "#8B7CF6", "#0F172A", "#38BDF8", "#16A36A", "#F59E0B", "#E13D48", "#94A3B8"];

const axis = { stroke: "rgb(var(--ink-3))", fontSize: 11, tickLine: false, axisLine: false } as const;
const tooltip = {
  contentStyle: { background: "rgb(var(--panel))", border: "0.5px solid rgb(var(--line))", borderRadius: 10, boxShadow: "0 8px 24px rgb(0 0 0 / .12)", fontSize: 12, color: "rgb(var(--ink))" },
  labelStyle: { color: "rgb(var(--ink-2))", fontWeight: 600 }, cursor: { fill: "rgb(var(--ink) / .04)" },
};

export function TrendChart({ data, currency }: { data: { date: string; leads: number; spend: number; won: number }[]; currency: string }) {
  return (
    <ResponsiveContainer width="100%" height={260}>
      <ComposedChart data={data} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
        <defs><linearGradient id="spendFill" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#7C6CF0" stopOpacity={0.25} /><stop offset="100%" stopColor="#7C6CF0" stopOpacity={0} /></linearGradient></defs>
        <CartesianGrid vertical={false} stroke="rgb(var(--line))" strokeDasharray="0" />
        <XAxis dataKey="date" {...axis} tickFormatter={(d) => d.slice(5)} minTickGap={24} />
        <YAxis yAxisId="l" {...axis} allowDecimals={false} />
        <YAxis yAxisId="s" orientation="right" {...axis} tickFormatter={(v) => new Intl.NumberFormat("en", { notation: "compact" }).format(v)} />
        <Tooltip {...tooltip} formatter={(v: number, n: string) => (n === "Spend" ? [new Intl.NumberFormat("en", { style: "currency", currency, maximumFractionDigits: 0 }).format(v), n] : [v, n])} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
        <Area yAxisId="s" type="monotone" dataKey="spend" name="Spend" stroke="#7C6CF0" strokeWidth={1.5} fill="url(#spendFill)" />
        <Bar yAxisId="l" dataKey="leads" name="Leads" fill="#2563EB" radius={[3, 3, 0, 0]} maxBarSize={14} />
        <Line yAxisId="l" type="monotone" dataKey="won" name="Won" stroke="#2F9E6E" strokeWidth={2} dot={false} />
      </ComposedChart>
    </ResponsiveContainer>
  );
}

export function FunnelBars({ stages }: { stages: { label: string; count: number; costLabel?: string; cost?: string }[] }) {
  const max = Math.max(1, ...stages.map((s) => s.count));
  return (
    <div className="space-y-2.5">
      {stages.map((s, i) => (
        <div key={s.label}>
          <div className="mb-1 flex items-baseline justify-between text-[12.5px]">
            <span className="font-medium">{s.label}</span>
            <span className="text-ink-3">{i > 0 && stages[0]!.count ? `${((s.count / stages[0]!.count) * 100).toFixed(0)}% · ` : ""}<b className="text-ink">{s.count}</b>{s.cost ? <> · {s.costLabel} <b className="text-ink">{s.cost}</b></> : null}</span>
          </div>
          <div className="h-2.5 overflow-hidden rounded-full bg-ink/[.06]"><div className="h-full rounded-full" style={{ width: `${(s.count / max) * 100}%`, background: PALETTE[i % PALETTE.length] }} /></div>
        </div>
      ))}
    </div>
  );
}

export function SimpleBars({ data, xKey, yKey, height = 240, color = "#2563EB", format }: { data: any[]; xKey: string; yKey: string; height?: number; color?: string; format?: (v: number) => string }) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} margin={{ top: 8, right: 8, left: -8, bottom: 0 }}>
        <CartesianGrid vertical={false} stroke="rgb(var(--line))" />
        <XAxis dataKey={xKey} {...axis} interval={0} tickFormatter={(v: string) => (String(v).length > 14 ? String(v).slice(0, 13) + "…" : v)} />
        <YAxis {...axis} tickFormatter={(v) => (format ? format(v) : new Intl.NumberFormat("en", { notation: "compact" }).format(v))} />
        <Tooltip {...tooltip} formatter={(v: number) => (format ? format(v) : v)} />
        <Bar dataKey={yKey} radius={[4, 4, 0, 0]} maxBarSize={40}>{data.map((_, i) => <Cell key={i} fill={i === 0 ? color : `${color}B3`} />)}</Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}

export function MultiLine({ data, lines, height = 220 }: { data: any[]; lines: { key: string; name: string; color?: string; axis?: "l" | "r" }[]; height?: number }) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <AreaChart data={data} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
        <CartesianGrid vertical={false} stroke="rgb(var(--line))" />
        <XAxis dataKey="date" {...axis} tickFormatter={(d) => String(d).slice(5)} minTickGap={24} />
        <YAxis yAxisId="l" {...axis} />
        <YAxis yAxisId="r" orientation="right" {...axis} />
        <Tooltip {...tooltip} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
        {lines.map((l, i) => <Area key={l.key} yAxisId={l.axis ?? "l"} type="monotone" dataKey={l.key} name={l.name} stroke={l.color ?? PALETTE[i]} fill={l.color ?? PALETTE[i]} fillOpacity={0.08} strokeWidth={1.8} />)}
      </AreaChart>
    </ResponsiveContainer>
  );
}

export function Sparkline({ values, color = "#2563EB" }: { values: number[]; color?: string }) {
  const max = Math.max(1, ...values), min = Math.min(0, ...values);
  const pts = values.map((v, i) => `${(i / Math.max(1, values.length - 1)) * 100},${30 - ((v - min) / (max - min || 1)) * 28}`).join(" ");
  return <svg viewBox="0 0 100 32" className="h-8 w-24" preserveAspectRatio="none"><polyline points={pts} fill="none" stroke={color} strokeWidth="2" vectorEffect="non-scaling-stroke" /></svg>;
}

/** Won vs lost by month (the "Sales overview" bars): lavender for won, ink for lost. */
export function WonLostBars({ data, height = 230 }: { data: { month: string; won: number; lost: number }[]; height?: number }) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} margin={{ top: 8, right: 4, left: -18, bottom: 0 }} barGap={4}>
        <CartesianGrid vertical={false} stroke="rgb(var(--line))" strokeDasharray="3 4" />
        <XAxis dataKey="month" {...axis} />
        <YAxis {...axis} allowDecimals={false} />
        <Tooltip {...tooltip} />
        <Bar dataKey="won" name="Won" fill="#8B7CF6" radius={[8, 8, 8, 8]} maxBarSize={22} />
        <Bar dataKey="lost" name="Lost" fill="rgb(var(--ink))" radius={[8, 8, 8, 8]} maxBarSize={22} />
      </BarChart>
    </ResponsiveContainer>
  );
}
