"use client";

import { useEffect, useState } from "react";
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

type Props = {
  data: { distanceKm: number; altM: number }[];
};

export function ElevationChart({ data }: Props) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  if (!mounted) {
    return <div className="h-[140px] animate-pulse rounded-lg border border-muted/40 bg-surface" />;
  }

  const altitudes = data.map((p) => p.altM);
  const minAlt = Math.min(...altitudes);
  const maxAlt = Math.max(...altitudes);
  const pad = Math.max(5, Math.round((maxAlt - minAlt) * 0.15));

  return (
    <div className="rounded-lg border border-muted/40 bg-surface p-4">
      <div className="mb-2 text-sm text-fg/60">Profil wysokości</div>
      <ResponsiveContainer width="100%" height={110}>
        <AreaChart data={data} margin={{ top: 4, right: 8, left: 0, bottom: 0 }}>
          <defs>
            <linearGradient id="elevGradient" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="var(--color-accent)" stopOpacity={0.25} />
              <stop offset="95%" stopColor="var(--color-accent)" stopOpacity={0} />
            </linearGradient>
          </defs>
          <CartesianGrid stroke="var(--color-muted)" opacity={0.3} vertical={false} />
          <XAxis
            dataKey="distanceKm"
            stroke="var(--color-fg)"
            opacity={0.5}
            fontSize={11}
            tickFormatter={(v) => `${Number(v).toFixed(1)} km`}
            interval={Math.max(0, Math.floor(data.length / 5) - 1)}
          />
          <YAxis
            stroke="var(--color-fg)"
            opacity={0.5}
            fontSize={11}
            width={44}
            tickFormatter={(v) => `${Math.round(v)} m`}
            domain={[minAlt - pad, maxAlt + pad]}
          />
          <Tooltip
            contentStyle={{
              background: "var(--color-bg)",
              border: "1px solid var(--color-muted)",
              borderRadius: 8,
              fontSize: 12,
              color: "var(--color-fg)",
            }}
            formatter={(value) => [`${Math.round(Number(value))} m n.p.m.`, "Wysokość"]}
            labelFormatter={(label) => `${Number(label).toFixed(2)} km`}
          />
          <Area
            type="monotone"
            dataKey="altM"
            stroke="var(--color-accent)"
            strokeWidth={2}
            fill="url(#elevGradient)"
            dot={false}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}
