/**
 * Color-accurate RF signal legend that uses the exact same
 * gradient pipeline as the heatmap renderer.
 *
 * Renders a smooth continuous gradient bar + labeled RSRP thresholds.
 * Steps below the Min Signal threshold are dimmed to indicate
 * they fall outside the visible coverage zone.
 */

import { normalizeRSRP, valueToColor } from '@/utils/colorGradient.ts';
import { useCoverageStore } from '@/store/coverage.ts';
import { useSitesStore } from '@/store/sites.ts';

const LEGEND_STEPS = [
  { rsrp: -130, label: 'No Service' },
  { rsrp: -110, label: 'Very Weak' },
  { rsrp: -100, label: 'Weak' },
  { rsrp: -90, label: 'Fair' },
  { rsrp: -80, label: 'Good' },
  { rsrp: -70, label: 'Strong' },
  { rsrp: -50, label: 'Excellent' },
];

/** Build a CSS linear-gradient string matching the heatmap gradient exactly. */
function buildGradientCSS(): string {
  const stops: string[] = [];
  const steps = 20;
  for (let i = 0; i <= steps; i++) {
    const value = i / steps; // 0–1
    const [r, g, b] = valueToColor(value);
    const pct = (i / steps) * 100;
    stops.push(`rgb(${r},${g},${b}) ${pct.toFixed(0)}%`);
  }
  return `linear-gradient(to top, ${stops.join(', ')})`;
}

const gradientCSS = buildGradientCSS();

export default function HeatmapLegend() {
  const result = useCoverageStore((s) => s.result);
  const heatmapVisible = useCoverageStore((s) => s.heatmapVisible);
  const toggleHeatmap = useCoverageStore((s) => s.toggleHeatmap);
  const settings = useCoverageStore((s) => s.settings);
  const sites = useSitesStore((s) => s.sites);

  if (!result) return null;

  const areaKm2 =
    (result.totalPoints * settings.resolution * settings.resolution) / 1e6;

  const threshold = settings.rsrpThreshold;

  // Split legend into above/below threshold
  const aboveThreshold = LEGEND_STEPS.filter((s) => s.rsrp >= threshold);
  const belowThreshold = LEGEND_STEPS.filter((s) => s.rsrp < threshold);

  return (
    <div className="absolute bottom-6 right-2 z-[1000] bg-white dark:bg-dark-surface rounded-lg shadow-lg border border-gray-200 dark:border-dark-border p-3 min-w-[180px]">
      {/* Header with toggle */}
      <div className="flex items-center justify-between mb-2">
        <h3 className="text-xs font-semibold text-gray-700 dark:text-dark-text">
          Signal (RSRP)
        </h3>
        <button
          onClick={toggleHeatmap}
          className={`w-8 h-4 rounded-full transition-colors relative
            ${heatmapVisible ? 'bg-blue-500' : 'bg-gray-300 dark:bg-dark-border'}`}
        >
          <span
            className={`absolute top-0.5 w-3 h-3 rounded-full bg-white shadow transition-transform
              ${heatmapVisible ? 'left-4' : 'left-0.5'}`}
          />
        </button>
      </div>

      {/* Gradient bar + labels */}
      <div className="flex gap-2">
        {/* Continuous gradient bar */}
        <div
          className="w-3 rounded-sm flex-shrink-0"
          style={{
            background: gradientCSS,
            minHeight: `${aboveThreshold.length * 18}px`,
          }}
        />

        {/* Labels — above threshold (visible coverage) */}
        <div className="flex flex-col justify-between flex-1 py-0.5">
          {[...aboveThreshold].reverse().map((step) => {
            const norm = normalizeRSRP(step.rsrp);
            const [r, g, b] = valueToColor(norm);
            return (
              <div key={step.rsrp} className="flex items-center gap-1.5">
                <div
                  className="w-2.5 h-2.5 rounded-sm flex-shrink-0"
                  style={{ backgroundColor: `rgb(${r},${g},${b})` }}
                />
                <span className="text-[10px] text-gray-600 dark:text-gray-400 leading-tight">
                  {step.rsrp} dBm {step.label}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Cutoff indicator + below-threshold (dimmed) */}
      {belowThreshold.length > 0 && (
        <div className="mt-1.5 pt-1.5 border-t border-dashed border-purple-400 dark:border-purple-500">
          <div className="flex items-center gap-1 mb-1">
            <span className="text-[9px] text-purple-500 dark:text-purple-400 font-medium">
              ─ ─ Coverage boundary ({threshold} dBm)
            </span>
          </div>
          {[...belowThreshold].reverse().map((step) => {
            const norm = normalizeRSRP(step.rsrp);
            const [r, g, b] = valueToColor(norm);
            return (
              <div key={step.rsrp} className="flex items-center gap-1.5 opacity-35">
                <div
                  className="w-2.5 h-2.5 rounded-sm flex-shrink-0"
                  style={{ backgroundColor: `rgb(${r},${g},${b})` }}
                />
                <span className="text-[10px] text-gray-500 dark:text-gray-500 leading-tight">
                  {step.rsrp} dBm {step.label}
                </span>
              </div>
            );
          })}
        </div>
      )}

      {/* Stats */}
      <div className="mt-2 pt-2 border-t border-gray-100 dark:border-dark-border text-[10px] text-gray-400 dark:text-dark-muted space-y-0.5">
        <div>Points: {result.totalPoints.toLocaleString()}</div>
        <div>Time: {(result.calculationTime / 1000).toFixed(2)}s</div>
        <div>Area: ~{areaKm2.toFixed(1)} km²</div>
        <div>Sites: {sites.length}</div>
      </div>
    </div>
  );
}
