import { useState } from 'preact/hooks';
import type { Bar } from '@wutzcalc/shared';
import { getTheme, setTheme } from '../api';
import { VersionFooter } from '../VersionFooter';

interface Props {
  bars: Bar[] | null;
  onPick: (id: number) => void;
}

export function BarPicker({ bars, onPick }: Props) {
  const [theme, setThemeState] = useState(getTheme());

  function toggleTheme() {
    const next = theme === 'dark' ? 'light' : 'dark';
    setTheme(next);
    setThemeState(next);
  }

  return (
    <div class="bar-picker">
      <h1>Bar auswählen</h1>
      {bars == null ? (
        <p>Lade…</p>
      ) : bars.length === 0 ? (
        // A fresh install (or every bar deleted) otherwise renders nothing
        // but the header here — indistinguishable from "still loading".
        <p class="muted">Keine Bars angelegt — bitte im Backoffice anlegen.</p>
      ) : (
        bars.map(b => (
          <button key={b.id} onClick={() => onPick(b.id)}>
            {b.name}
          </button>
        ))
      )}
      <button class="theme-toggle" onClick={toggleTheme}>
        {theme === 'dark' ? '☀ Heller Modus' : '🌙 Dunkler Modus'}
      </button>
      <VersionFooter />
    </div>
  );
}
