<script lang="ts">
  import { onMount } from 'svelte';
  import { buzzer } from '../lib/buzzerStore';
  import { connectToPort, initSerialListeners } from '../lib/buzzerActions';
  import { PlugsIcon, PlugsConnectedIcon } from 'phosphor-svelte';

  onMount(() => {
    initSerialListeners();
  });

  async function handleConnectClick() {
    try {
      // Wenn wir schon gekoppelt sind, aber nicht verbunden, 
      // wird navigator.serial.requestPort() den Picker zeigen.
      const port = await navigator.serial.requestPort();
      await connectToPort(port);
    } catch (e) {
      console.error("Verbindung abgebrochen", e);
    }
  }
</script>

<button 
  on:click={handleConnectClick}
  class="flex items-center gap-2 px-4 py-2 rounded-xl transition-all
  {$buzzer.connected 
    ? 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/50' 
    : 'bg-slate-700 hover:bg-slate-600 text-slate-200 border border-slate-600'}"
>
  {#if $buzzer.connected}
    <PlugsConnectedIcon size={18} weight="fill" />
    <span class="text-xs font-bold uppercase tracking-wider text-emerald-300">Verbunden</span>
  {:else}
    <PlugsIcon size={18} weight="bold" />
    <span class="text-xs font-bold uppercase tracking-wider">Verbinden</span>
  {/if}
</button>