<script>
  import { getDevices, updateDeviceLayout, registerDevice } from './api.js';

  let devices = $state([]);
  let loading = $state(true);
  let error = $state('');

  // Track XML edits per device (keyed by MAC)
  let editingXml = $state({});
  let savingMac = $state('');
  let saveResult = $state('');

  let defaultXml = $state('');

  // Debug states
  let debugRegistering = $state(false);

  async function loadDevices() {
    loading = true;
    error = '';
    try {
      const data = await getDevices();
      devices = data.devices;
      defaultXml = data.default_layout;
    } catch (e) {
      error = e.message || 'Failed to load devices';
    } finally {
      loading = false;
    }
  }

  async function handleDebugRegister() {
    debugRegistering = true;
    try {
      // Generate a fake MAC like "DE:BU:G0:xx:xx:xx"
      const hex = () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0').toUpperCase();
      const fakeMac = `DE:BU:G0:${hex()}:${hex()}:${hex()}`;
      await registerDevice(fakeMac);
      await loadDevices();
    } catch (e) {
      error = e.message || 'Failed to register debug device';
    } finally {
      debugRegistering = false;
    }
  }

  async function handleSaveLayout(device) {
    savingMac = device.mac;
    saveResult = '';
    try {
      await updateDeviceLayout(device.mac, editingXml[device.mac] ?? device.xml_layout);
      saveResult = 'ok';
      await loadDevices();
    } catch (e) {
      saveResult = e.message || 'Save failed';
    } finally {
      savingMac = '';
    }
  }

  // Runs once on mount — no reactive deps
  $effect(() => {
    loadDevices();
  });
</script>

<div class="space-y-6">
  <div class="flex items-center justify-between">
    <div>
      <h2 class="text-lg font-bold text-text-primary">Device Manager</h2>
      <p class="text-xs text-text-secondary mt-1">
        Manage registered e-ink devices and their screen layouts.
      </p>
    </div>
    <button
      onclick={loadDevices}
      class="px-3 py-1.5 text-xs font-medium rounded-lg bg-accent/10 text-accent border border-accent/20 hover:bg-accent/20 transition-colors"
    >
      Refresh
    </button>
  </div>

  {#if loading}
    <div class="text-center text-sm text-text-secondary py-8 animate-pulse">
      Loading devices...
    </div>
  {:else if error}
    <div class="text-center text-sm text-danger py-8">
      {error}
    </div>
  {:else if devices.length === 0}
    <div class="bg-bg-card-hover/50 border border-border rounded-xl p-8 text-center">
      <p class="text-text-secondary text-sm">No devices registered yet.</p>
      <p class="text-text-secondary text-xs mt-2">
        Use <code class="bg-bg-card px-1.5 py-0.5 rounded text-[11px] font-mono text-accent">
          curl -X POST -d '{{"mac":"AA:BB:CC:DD:EE:FF"}}' http://calendink.local/api/devices/register
        </code> to register a device.
      </p>
    </div>
  {:else}
    <div class="grid grid-cols-1 gap-4">
      {#each devices as device}
        <div class="bg-bg-card border border-border rounded-xl overflow-hidden shadow-lg">
          <!-- Device Header -->
          <div class="px-5 py-3 border-b border-border flex items-center justify-between">
            <div class="flex items-center gap-3">
              <span class="text-base">📺</span>
              <span class="text-sm font-mono font-bold text-text-primary">{device.mac}</span>
            </div>
            <div class="flex items-center gap-2">
              {#if device.has_layout}
                {#if device.xml_layout === defaultXml}
                  <span class="text-[10px] bg-accent/20 text-accent px-2 py-0.5 rounded-full uppercase tracking-wider font-semibold">
                    Default Layout
                  </span>
                {:else}
                  <span class="text-[10px] bg-success/20 text-success px-2 py-0.5 rounded-full uppercase tracking-wider font-semibold">
                    Layout Set
                  </span>
                {/if}
              {:else}
                <span class="text-[10px] bg-border/50 text-text-secondary px-2 py-0.5 rounded-full uppercase tracking-wider font-semibold">
                  No Layout
                </span>
              {/if}
            </div>
          </div>

          <!-- XML Editor -->
          <div class="p-5 space-y-3">
            <label for="xml-{device.mac}" class="text-xs font-semibold text-text-secondary uppercase tracking-wider">
              LVGL XML Layout
            </label>
            <!-- svelte-ignore a11y_autofocus -->
            <textarea
              id="xml-{device.mac}"
              class="w-full h-32 bg-bg-primary border border-border rounded-lg p-3 text-xs font-mono text-text-primary resize-y focus:border-accent focus:outline-none transition-colors placeholder:text-text-secondary/50"
              placeholder={defaultXml}
              value={editingXml[device.mac] ?? device.xml_layout}
              oninput={(e) => editingXml[device.mac] = e.currentTarget.value}
            ></textarea>

            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                  <a
                    href="/api/devices/screen.png?mac={device.mac}"
                    target="_blank"
                    class="text-xs text-accent hover:text-accent/80 transition-colors underline"
                  >
                    Preview PNG →
                  </a>
              </div>
              <button
                onclick={() => handleSaveLayout(device)}
                disabled={savingMac === device.mac}
                class="px-4 py-2 text-xs font-medium rounded-lg transition-colors
                       bg-accent/10 text-accent border border-accent/20
                       hover:bg-accent/20 hover:border-accent/30
                       disabled:opacity-40 disabled:cursor-not-allowed"
              >
                {savingMac === device.mac ? 'Saving...' : 'Save Layout'}
              </button>
            </div>

            {#if saveResult === 'ok' && savingMac === ''}
              <div class="text-xs text-success">✓ Layout saved successfully</div>
            {:else if saveResult && saveResult !== 'ok'}
              <div class="text-xs text-danger">✗ {saveResult}</div>
            {/if}
          </div>
        </div>
      {/each}
    </div>
  {/if}

  <details class="mt-8 border text-xs border-border rounded-lg bg-bg-card opacity-50 hover:opacity-100 transition-opacity">
    <summary class="px-4 py-3 cursor-pointer font-medium text-text-secondary select-none">
      Debug Tools
    </summary>
    <div class="p-4 border-t border-border border-dashed space-y-4">
      <p class="text-text-secondary">
        Quickly register a new device to format layouts.
      </p>
      <button
        onclick={handleDebugRegister}
        disabled={debugRegistering}
        class="px-4 py-2 font-medium rounded-lg transition-colors
               bg-accent/10 text-accent border border-accent/20
               hover:bg-accent/20 hover:border-accent/30
               disabled:opacity-40 disabled:cursor-not-allowed"
      >
        {debugRegistering ? 'Registering...' : 'Add Fake Device'}
      </button>
    </div>
  </details>
</div>
