import { cn } from "@/lib/utils";
import type { Trend } from "@/lib/dashboard-data";

// Stretched SVG area + line chart. `gradientId` must be unique per instance.
export function AreaChart({
  data,
  gradientId,
  className,
}: {
  data: Trend[];
  gradientId: string;
  className?: string;
}) {
  const w = 100;
  const h = 42;
  const values = data.map((d) => d.value);
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;

  const pts = data.map((d, i) => {
    const x = data.length > 1 ? (i / (data.length - 1)) * w : 0;
    const y = h - 4 - ((d.value - min) / range) * (h - 8);
    return [x, y] as const;
  });

  const line = pts
    .map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(2)} ${p[1].toFixed(2)}`)
    .join(" ");
  const area = `${line} L ${w} ${h} L 0 ${h} Z`;

  return (
    <svg
      viewBox={`0 0 ${w} ${h}`}
      preserveAspectRatio="none"
      className={cn("w-full", className)}
    >
      <defs>
        <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#5c7cfa" stopOpacity="0.38" />
          <stop offset="100%" stopColor="#5c7cfa" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((g) => (
        <line
          key={g}
          x1="0"
          y1={h * g}
          x2={w}
          y2={h * g}
          stroke="rgba(255,255,255,0.05)"
          strokeWidth="0.4"
        />
      ))}
      <path d={area} fill={`url(#${gradientId})`} />
      <path
        d={line}
        fill="none"
        stroke="#7c9bff"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
        vectorEffect="non-scaling-stroke"
      />
    </svg>
  );
}

// Stretched SVG bar chart.
export function BarChart({ data, className }: { data: Trend[]; className?: string }) {
  const max = Math.max(...data.map((d) => d.value), 1);
  return (
    <div className={cn("flex h-full items-end gap-[2px]", className)}>
      {data.map((d, i) => (
        <div
          key={i}
          className="flex-1 rounded-t-[2px] bg-gradient-to-t from-brand/30 to-brand"
          style={{ height: `${Math.max(4, (d.value / max) * 100)}%` }}
          title={`${d.value}`}
        />
      ))}
    </div>
  );
}

// Doughnut showing `value/total` as a percentage ring.
export function Donut({
  value,
  total,
  label,
  color = "#10B981",
  size = 132,
}: {
  value: number;
  total: number;
  label: string;
  color?: string;
  size?: number;
}) {
  const r = 40;
  const c = 2 * Math.PI * r;
  const pct = total ? value / total : 0;
  const dash = c * pct;

  return (
    <svg viewBox="0 0 100 100" width={size} height={size} className="shrink-0">
      <circle cx="50" cy="50" r={r} fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="11" />
      <circle
        cx="50"
        cy="50"
        r={r}
        fill="none"
        stroke={color}
        strokeWidth="11"
        strokeLinecap="round"
        strokeDasharray={`${dash} ${c - dash}`}
        transform="rotate(-90 50 50)"
      />
      <text x="50" y="48" textAnchor="middle" fontSize="19" fontWeight="700" fill="#fff">
        {Math.round(pct * 100)}%
      </text>
      <text x="50" y="63" textAnchor="middle" fontSize="7.5" fill="#94A3B8">
        {label}
      </text>
    </svg>
  );
}

// Decorative activity heatmap (deterministic). Stands in for a map widget until
// real geo data is wired.
export function Heatmap({ cols = 14, rows = 6 }: { cols?: number; rows?: number }) {
  return (
    <div
      className="grid gap-1"
      style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}
    >
      {Array.from({ length: rows * cols }).map((_, i) => {
        const intensity = (Math.sin(i * 1.7) + Math.cos(i * 0.6) + 2) / 4; // 0..1
        return (
          <div
            key={i}
            className="aspect-square rounded-[3px]"
            style={{ background: `rgba(92,124,250,${(0.06 + intensity * 0.7).toFixed(3)})` }}
          />
        );
      })}
    </div>
  );
}

// Deterministic decorative QR (finder patterns + seeded module field).
export function QrCode({ value, className }: { value: string; className?: string }) {
  const n = 21;
  let seed = 7;
  for (const ch of value) seed = (seed * 33 + ch.charCodeAt(0)) >>> 0;
  const next = () => {
    seed = (seed * 1664525 + 1013904223) >>> 0;
    return seed / 0xffffffff;
  };
  const isFinder = (x: number, y: number) =>
    (x < 7 && y < 7) || (x >= n - 7 && y < 7) || (x < 7 && y >= n - 7);

  const modules: { x: number; y: number }[] = [];
  for (let y = 0; y < n; y++) {
    for (let x = 0; x < n; x++) {
      if (!isFinder(x, y) && next() > 0.55) modules.push({ x, y });
    }
  }
  const finders = [
    { x: 0, y: 0 },
    { x: n - 7, y: 0 },
    { x: 0, y: n - 7 },
  ];

  return (
    <svg
      viewBox={`-1 -1 ${n + 2} ${n + 2}`}
      className={cn("h-28 w-28", className)}
      role="img"
      aria-label={`QR code for ${value}`}
    >
      <rect x={-1} y={-1} width={n + 2} height={n + 2} fill="#fff" rx={2} />
      {modules.map((m) => (
        <rect key={`${m.x}-${m.y}`} x={m.x} y={m.y} width={1} height={1} fill="#0A0E17" />
      ))}
      {finders.map((f, i) => (
        <g key={i}>
          <rect x={f.x} y={f.y} width={7} height={7} rx={1.4} fill="#0A0E17" />
          <rect x={f.x + 1} y={f.y + 1} width={5} height={5} rx={1} fill="#fff" />
          <rect x={f.x + 2} y={f.y + 2} width={3} height={3} rx={0.6} fill="#3b5bdb" />
        </g>
      ))}
    </svg>
  );
}
