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

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

  /** @type {'dashboard' | 'tasks'} */
  let currentView = $state("dashboard");

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

  let otaStatus = $state({
    partitions: [],
    active_partition: "—",
    running_firmware_label: "—"
  });

  let upcomingData = $state({ users: [] });

  /** 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`;
  }

  function formatRelativeDate(timestamp) {
    const now = Date.now() / 1000;
    const diff = timestamp - now;
    const absDiff = Math.abs(diff);

    if (absDiff < 3600) {
      const mins = Math.round(absDiff / 60);
      return diff < 0 ? `${mins}m ago` : `in ${mins}m`;
    }
    if (absDiff < 86400) {
      const hours = Math.round(absDiff / 3600);
      return diff < 0 ? `${hours}h ago` : `in ${hours}h`;
    }
    const days = Math.round(absDiff / 86400);
    return diff < 0 ? `${days}d ago` : `in ${days}d`;
  }

  function isOverdue(timestamp) {
    return timestamp < Date.now() / 1000;
  }

  async function fetchAll() {
    try {
      const [sys, ota, upcoming] = await Promise.all([
        getSystemInfo(),
        getOTAStatus(),
        getUpcomingTasks().catch(() => ({ users: [] }))
      ]);
      systemInfo = sys;
      otaStatus = ota;
      upcomingData = upcoming;
      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(() => {
    fetchAll();
    // Poll for status updates every 5 seconds
    const interval = setInterval(fetchAll, 5000);
    return () => clearInterval(interval);
  });

  // 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>

<div class="app-layout">
  <Sidebar {currentView} onNavigate={(view) => currentView = view} />

  <main class="main-content">
    <div class="w-full max-w-6xl mx-auto space-y-8">
      <!-- Header -->
      <div class="text-center">
        <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>
        
        <!-- Status Badge -->
        <div class="flex justify-center mt-4">
          {#if status === "loading"}
            <div class="inline-flex items-center gap-2 bg-accent/10 border border-accent/20 rounded-full px-4 py-1.5 text-xs text-accent">
              <span class="w-2 h-2 rounded-full bg-accent animate-pulse"></span>
              <span>Connecting...</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-1.5 text-xs 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-1.5 text-xs 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-1.5 text-xs text-danger">
              <span class="w-2 h-2 rounded-full bg-danger"></span>
              <span>Offline — {errorMsg}</span>
            </div>
          {/if}
        </div>
      </div>

      {#if currentView === 'dashboard'}
        <!-- Dashboard View -->

        <!-- Upcoming Tasks Section (top priority) -->
        {#if upcomingData.users.length > 0}
          <div class="bg-bg-card border border-border rounded-xl overflow-hidden shadow-xl">
            <div class="px-5 py-3 border-b border-border">
              <h2 class="text-sm font-semibold text-text-primary uppercase tracking-wider">
                📋 Upcoming Tasks
              </h2>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-0 divide-y md:divide-y-0 md:divide-x divide-border">
              {#each upcomingData.users as user}
                <div class="p-4">
                  <h3 class="text-xs font-bold text-accent mb-3 uppercase tracking-wider">{user.name}</h3>
                  {#if user.tasks.length === 0}
                    <p class="text-[11px] text-text-secondary italic">No pending tasks</p>
                  {:else}
                    <div class="space-y-2">
                      {#each user.tasks as task}
                        <div class="flex items-start gap-2">
                          <span class="text-[10px] mt-0.5 {isOverdue(task.due_date) ? 'text-danger' : 'text-text-secondary'} font-mono whitespace-nowrap">
                            {formatRelativeDate(task.due_date)}
                          </span>
                          <span class="text-xs text-text-primary leading-tight">{task.title}</span>
                        </div>
                      {/each}
                    </div>
                  {/if}
                </div>
              {/each}
            </div>
          </div>
        {/if}

        <!-- 2-Column Grid Layout -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8 items-start">
          
          <!-- Left Column: System Info & Partition Table -->
          <div class="space-y-8">
            <!-- System Info Card -->
            <div class="bg-bg-card border border-border rounded-xl overflow-hidden shadow-xl">
              <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>

            <!-- Partition Table Card -->
            <div class="bg-bg-card border border-border rounded-xl overflow-hidden shadow-xl">
              <div class="px-5 py-3 border-b border-border flex items-center justify-between">
                <h2 class="text-sm font-semibold text-text-primary uppercase tracking-wider">
                  Partition Table
                </h2>
                <span class="text-[10px] text-text-secondary font-mono">Flash: 16MB</span>
              </div>
              <div class="divide-y divide-border">
                {#if status === "loading"}
                  <div class="p-5 text-center text-xs text-text-secondary animate-pulse">Loading memory layout...</div>
                {:else}
                  {#each otaStatus.partitions as part}
                    <div class="px-5 py-2.5 flex items-center justify-between hover:bg-bg-card-hover transition-colors">
                      <div class="flex flex-col">
                        <div class="flex items-center gap-2">
                          <span class="text-[11px] font-mono font-bold {part.label === otaStatus.active_partition || part.label === otaStatus.running_firmware_label ? 'text-accent' : 'text-text-primary'}">
                            {part.label}
                          </span>
                          {#if part.label === otaStatus.active_partition || part.label === otaStatus.running_firmware_label}
                            <span class="text-[8px] bg-accent/20 text-accent px-1 rounded uppercase tracking-tighter">Active</span>
                          {/if}
                        </div>
                        <span class="text-[9px] text-text-secondary uppercase">
                           Type {part.type} / Sub {part.subtype}
                        </span>
                      </div>
                      <div class="text-right flex flex-col items-end">
                        <div class="text-[11px] font-mono text-text-primary">{formatBytes(part.size)}</div>
                        <div class="flex items-center gap-1.5 mt-0.5">
                          {#if part.app_version}
                            <span class="text-[9px] text-accent font-bold">v{part.app_version}</span>
                          {/if}
                          {#if part.free !== undefined}
                            <span class="text-[9px] {part.free > 1024 ? 'text-success' : 'text-text-secondary'} font-bold">
                              {formatBytes(part.free)} free
                            </span>
                          {/if}
                        </div>
                      </div>
                    </div>
                  {/each}
                {/if}
              </div>
            </div>
          </div>

          <!-- Right Column: Device Control & OTA Updates -->
          <div class="space-y-8">
            <!-- Device Control Card -->
            <div class="bg-bg-card border border-border rounded-xl p-5 shadow-xl">
              <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>

            <!-- Updates & Maintenance Card -->
            <OTAUpdate onReboot={() => { status = "rebooting"; isRecovering = true; }} />
          </div>

        </div>

      {:else if currentView === 'tasks'}
        <!-- Task Manager View -->
        <div class="bg-bg-card border border-border rounded-xl p-6 shadow-xl">
          <TaskManager />
        </div>
      {/if}

      <!-- Reboot Confirmation Modal -->
      {#if showRebootConfirm}
        <div class="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
          <div class="bg-bg-card border border-border rounded-xl p-6 max-w-sm w-full space-y-4 shadow-2xl">
            <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 shadow-lg shadow-danger/20"
              >
                Reboot Now
              </button>
            </div>
          </div>
        </div>
      {/if}

    </div>
  </main>
</div>

<style>
  .app-layout {
    display: flex;
    min-height: 100vh;
    background: var(--color-bg-primary);
  }

  .main-content {
    flex: 1;
    padding: 16px 32px;
    overflow-y: auto;
  }

  @media (max-width: 768px) {
    .main-content {
      padding: 16px;
    }
  }
</style>
