'use client';

import type { LegendEntry, OverlayMeta } from '@/lib/overlays';

interface OverlayPanelProps {
  overlays: OverlayMeta[];
  activeSlug: string | null;
  onSelect: (slug: string | null) => void;
  isLoading: boolean;
  error: string | null;
  /** Category key for the active overlay; empty when it has no categories. */
  legend: LegendEntry[];
}

/**
 * Overlay chooser (M1C).
 *
 * Deliberately radio-style, not checkboxes: SRS 3.2.1 allows "no, or only one
 * overlay" at a time. Bill confirmed on 18 August that he wants to keep it
 * that way rather than the multiple-simultaneous wording briefly agreed in
 * June -- his reasoning being that more than one at a time is too much for the
 * general visitor to read. Picking one replaces the other; "None" clears.
 *
 * Overlays that are agreed but whose file has not arrived yet are listed and
 * visibly pending rather than hidden, so the catalogue reflects what the
 * project has committed to rather than only what happens to be loaded.
 */
export default function OverlayPanel({
  overlays,
  activeSlug,
  onSelect,
  isLoading,
  error,
  legend,
}: OverlayPanelProps) {
  const active = overlays.find((o) => o.slug === activeSlug) ?? null;

  return (
    <div className="absolute right-3 top-14 z-10 w-60 rounded-lg bg-zinc-900/85 p-3 text-zinc-100 shadow-lg backdrop-blur-sm">
      <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-zinc-400">
        Overlay
      </div>

      {isLoading && <p className="py-1 text-xs text-zinc-400">Loading overlays…</p>}

      {error && (
        <p className="py-1 text-xs text-amber-300">
          {error}
          <span className="mt-0.5 block text-zinc-400">
            Drawing is unaffected — the basemap and your areas work as normal.
          </span>
        </p>
      )}

      {!isLoading && !error && overlays.length === 0 && (
        <p className="py-1 text-xs text-zinc-400">No overlays available yet.</p>
      )}

      {overlays.length > 0 && (
        <div className="flex flex-col gap-1">
          <button
            type="button"
            onClick={() => onSelect(null)}
            aria-pressed={activeSlug === null}
            className={`rounded px-2 py-1.5 text-left text-xs transition-colors ${
              activeSlug === null
                ? 'bg-zinc-100 text-zinc-900'
                : 'bg-zinc-800/60 text-zinc-100 hover:bg-zinc-700'
            }`}
          >
            None
          </button>

          {overlays.map((overlay) => {
            const isActive = overlay.slug === activeSlug;
            const pending = !overlay.hasData;
            return (
              <button
                key={overlay.slug}
                type="button"
                disabled={pending}
                onClick={() => onSelect(isActive ? null : overlay.slug)}
                aria-pressed={isActive}
                title={overlay.description ?? overlay.title}
                className={`rounded px-2 py-1.5 text-left text-xs transition-colors ${
                  isActive
                    ? 'bg-zinc-100 text-zinc-900'
                    : pending
                      ? 'cursor-not-allowed bg-zinc-800/30 text-zinc-500'
                      : 'bg-zinc-800/60 text-zinc-100 hover:bg-zinc-700'
                }`}
              >
                <span className="block leading-snug">{overlay.title}</span>
                {pending && (
                  <span className="mt-0.5 block text-[10px] text-zinc-500">
                    Awaiting source data
                  </span>
                )}
              </button>
            );
          })}
        </div>
      )}

      {/* Key to the active overlay's categories. An eight-way division like
          Areas A/B/C cannot be read without it. */}
      {active && legend.length > 1 && (
        <ul className="mt-2 flex flex-col gap-1 border-t border-zinc-700 pt-2" aria-label="Overlay legend">
          {legend.map((entry) => (
            <li key={entry.label} className="flex items-center gap-2 text-[11px] leading-tight text-zinc-200">
              <span
                aria-hidden="true"
                className="h-3 w-3 shrink-0 rounded-sm border border-white/40"
                style={{ backgroundColor: entry.color, opacity: Math.max(0.6, active.opacity) }}
              />
              {entry.label}
            </li>
          ))}
        </ul>
      )}

      {/* Attribution for whatever is currently shown. SRS 5.1 wants every
          non-public-domain asset's provenance documented, and the honest place
          for it is next to the thing it applies to. */}
      {active && (active.sourceName || active.licence) && (
        <div className="mt-2 border-t border-zinc-700 pt-2 text-[10px] leading-snug text-zinc-400">
          {active.sourceName && <div>Source: {active.sourceName}</div>}
          {active.licence && <div>Licence: {active.licence}</div>}
        </div>
      )}
    </div>
  );
}
