<script>
  import { getSystemInfo, reboot } from "./lib/api.js";
  import OTAUpdate from "./lib/OTAUpdate.svelte";

  /** @type {'loading' | 'ok' | 'error' | 'rebooting'} */
  let status = $state("loading");
  let errorMsg = $state("");
  let showRebootConfirm = $state(false);
  let isRecovering = $state(false);

  let systemInfo = $state({
    chip: "—",
    freeHeap: 0,
    uptime: 0,
    firmware: "—",
    connection: "—",
  });

  /** Format uptime seconds into human-readable string */
  function formatUptime(seconds) {
    const d = Math.floor(seconds / 86400);
    const h = Math.floor((seconds % 86400) / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    const parts = [];
    if (d > 0) parts.push(`${d}d`);
    if (h > 0) parts.push(`${h}h`);
    if (m > 0) parts.push(`${m}m`);
    parts.push(`${s}s`);
    return parts.join(" ");
  }

  /** Format bytes into human-readable string */
  function formatBytes(bytes) {
    if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1)} MB`;
    if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${bytes} B`;
  }

  async function fetchInfo() {
    try {
      systemInfo = await getSystemInfo();
      status = "ok";
      errorMsg = "";
    } catch (e) {
      if (!isRecovering) {
        status = "error";
        errorMsg = e.message || "Connection failed";
      }
    }
  }

  async function handleReboot() {
    showRebootConfirm = false;
    status = "rebooting";
    isRecovering = true;
    try {
      await reboot();
    } catch (e) {
      // Expected — ESP32 won't reply after restarting
    }
  }

  $effect(() => {
    fetchInfo();
  });

  // Resilient recovery polling: Only poll when we are waiting for a reboot
  $effect(() => {
    if (isRecovering) {
      const interval = setInterval(async () => {
        try {
          const info = await getSystemInfo();
          if (info) {
             console.log("Device back online! Refreshing UI...");
             window.location.reload();
          }
        } catch (e) {
          // Still offline or rebooting, just keep waiting
          console.log("Waiting for device...");
        }
      }, 2000);
      return () => clearInterval(interval);
    }
  });

  const infoItems = $derived([
    { label: "Chip", value: systemInfo.chip, icon: "🔧" },
    { label: "Free Heap", value: formatBytes(systemInfo.freeHeap), icon: "💾" },
    { label: "Uptime", value: formatUptime(systemInfo.uptime), icon: "⏱️" },
    { label: "Firmware", value: systemInfo.firmware, icon: "📦" },
    { label: "Connection", value: systemInfo.connection, icon: "🌐" },
  ]);
</script>

<main class="min-h-screen bg-bg-primary flex items-center justify-center p-4">
  <div class="w-full max-w-xl space-y-4">
    <!-- Header -->
    <div class="text-center mb-6">
      <h1 class="text-2xl font-bold text-accent">Calendink Provider 🚀</h1>
      <p class="text-text-secondary text-sm">ESP32-S3 System Dashboard v{__APP_VERSION__}</p>
    </div>

    <!-- Status Badge -->
    <div class="flex justify-center">
      {#if status === "loading"}
        <div
          class="inline-flex items-center gap-2 bg-accent/10 border border-accent/20 rounded-full px-4 py-2 text-sm text-accent"
        >
          <span class="w-2 h-2 rounded-full bg-accent animate-pulse"></span>
          <span>Connecting to ESP32...</span>
        </div>
      {:else if status === "ok"}
        <div
          class="inline-flex items-center gap-2 bg-success/10 border border-success/20 rounded-full px-4 py-2 text-sm text-success"
        >
          <span class="w-2 h-2 rounded-full bg-success animate-pulse"></span>
          <span>Connected</span>
        </div>
      {:else if status === "rebooting"}
        <div
          class="inline-flex items-center gap-2 bg-amber-500/10 border border-amber-500/20 rounded-full px-4 py-2 text-sm text-amber-400"
        >
          <span class="w-2 h-2 rounded-full bg-amber-400 animate-pulse"></span>
          <span>Rebooting...</span>
        </div>
      {:else}
        <div
          class="inline-flex items-center gap-2 bg-danger/10 border border-danger/20 rounded-full px-4 py-2 text-sm text-danger"
        >
          <span class="w-2 h-2 rounded-full bg-danger"></span>
          <span>Offline — {errorMsg}</span>
        </div>
      {/if}
    </div>

    <!-- System Info Card -->
    <div class="bg-bg-card border border-border rounded-xl overflow-hidden">
      <div class="px-5 py-3 border-b border-border">
        <h2
          class="text-sm font-semibold text-text-primary uppercase tracking-wider"
        >
          System Info
        </h2>
      </div>
      <div class="divide-y divide-border">
        {#each infoItems as item}
          <div
            class="flex items-center justify-between px-5 py-3 hover:bg-bg-card-hover transition-colors"
          >
            <div class="flex items-center gap-3">
              <span class="text-base">{item.icon}</span>
              <span class="text-sm text-text-secondary">{item.label}</span>
            </div>
            <span class="text-sm font-mono text-text-primary">
              {#if status === "loading"}
                <span
                  class="inline-block w-16 h-4 bg-border rounded animate-pulse"
                ></span>
              {:else}
                {item.value}
              {/if}
            </span>
          </div>
        {/each}
      </div>
    </div>

    <!-- Device Control Section (Reboot) -->
    <div class="bg-bg-card border border-border rounded-xl p-5">
      <div class="flex items-center justify-between">
        <div>
          <h2 class="text-sm font-semibold text-text-primary uppercase tracking-wider">
            Device Control
          </h2>
          <p class="text-xs text-text-secondary mt-1">
            Restart the ESP32 microcontroller
          </p>
        </div>
        <button
          onclick={() => (showRebootConfirm = true)}
          disabled={status === "rebooting" || status === "loading"}
          class="px-4 py-2 text-sm font-medium rounded-lg transition-colors
                 bg-danger/10 text-danger border border-danger/20
                 hover:bg-danger/20 hover:border-danger/30
                 disabled:opacity-40 disabled:cursor-not-allowed"
        >
          Reboot
        </button>
      </div>
    </div>

    <!-- Frontend Info & OTA Section -->
    <OTAUpdate onReboot={() => (status = "rebooting")} />

    <!-- Reboot Confirmation Modal -->
    {#if showRebootConfirm}
      <div
        class="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4"
      >
        <div
          class="bg-bg-card border border-border rounded-xl p-6 max-w-sm w-full space-y-4"
        >
          <h3 class="text-lg font-semibold text-text-primary">
            Confirm Reboot
          </h3>
          <p class="text-sm text-text-secondary">
            Are you sure you want to reboot the ESP32? The device will be
            temporarily unavailable.
          </p>
          <div class="flex gap-3 justify-end">
            <button
              onclick={() => (showRebootConfirm = false)}
              class="px-4 py-2 text-sm rounded-lg bg-border/30 text-text-secondary hover:bg-border/50 transition-colors"
            >
              Cancel
            </button>
            <button
              onclick={handleReboot}
              class="px-4 py-2 text-sm font-medium rounded-lg bg-danger text-white hover:bg-danger-hover transition-colors"
            >
              Reboot Now
            </button>
          </div>
        </div>
      </div>
    {/if}

  </div>
</main>
