import { LayoutGrid, ZoomIn, ZoomOut } from 'lucide-react';
import { useDashboardState } from 'state/useDashboardState';
import { soulseekZoomKey, SOULSEEK_ZOOM_MIN, SOULSEEK_ZOOM_MAX, SOULSEEK_ZOOM_STEP } from './shared';

// Panel header for the right (soulseek-view) panel — icon + title plus +/- zoom controls. The zoom
// factor is persisted per-panel via useDashboardState (same store as the layout config) so it survives
// reloads; SoulseekView reads the same key to scale its content. This is the Workspace panel-header API:
// a `header` component (registered alongside `component`) rendered by PanelSlot with { panelId }.

const clamp = (z: number) => Math.min(SOULSEEK_ZOOM_MAX, Math.max(SOULSEEK_ZOOM_MIN, Math.round(z * 10) / 10));

type SoulseekViewHeaderProps = { panelId: string };

export const SoulseekViewHeader = ({ panelId }: SoulseekViewHeaderProps) => {
  const { value: zoom, setValue: setZoom } = useDashboardState<number>(soulseekZoomKey(panelId), 1);
  const level = zoom ?? 1;

  return (
    <>
      <LayoutGrid className="h-3.5 w-3.5 shrink-0" />
      <span className="flex-1 truncate text-xs font-medium">Soulseek</span>
      <div className="flex shrink-0 items-center gap-0.5">
        <button
          type="button"
          onClick={() => setZoom((z) => clamp((z ?? 1) - SOULSEEK_ZOOM_STEP))}
          disabled={level <= SOULSEEK_ZOOM_MIN}
          title="Zoom out"
          className="cursor-pointer rounded p-1 transition-colors hover:bg-black/10 disabled:cursor-default disabled:opacity-30"
        >
          <ZoomOut className="h-3.5 w-3.5" />
        </button>
        <button
          type="button"
          onClick={() => setZoom(1)}
          title="Reset zoom"
          className="w-9 cursor-pointer rounded px-1 text-center text-[11px] tabular-nums text-black/60 transition-colors hover:bg-black/10 hover:text-black"
        >
          {Math.round(level * 100)}%
        </button>
        <button
          type="button"
          onClick={() => setZoom((z) => clamp((z ?? 1) + SOULSEEK_ZOOM_STEP))}
          disabled={level >= SOULSEEK_ZOOM_MAX}
          title="Zoom in"
          className="cursor-pointer rounded p-1 transition-colors hover:bg-black/10 disabled:cursor-default disabled:opacity-30"
        >
          <ZoomIn className="h-3.5 w-3.5" />
        </button>
      </div>
    </>
  );
};
