<script>
  import { getSystemInfo, reboot, getOTAStatus, getUpcomingTasks } from "./lib/api.js";
  import { formatUptime, formatBytes, formatRelativeDate, isOverdue } from "./lib/utils.js";
  import OTAUpdate from "./lib/OTAUpdate.svelte";
  import Sidebar from "./lib/Sidebar.svelte";
  import TaskManager from "./lib/TaskManager.svelte";
  import UserManager from "./lib/UserManager.svelte";
  import DeviceManager from "./lib/DeviceManager.svelte";
  import Spinner from "./lib/Spinner.svelte";

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

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

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

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

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

  let isFetching = false; // mutex, not reactive
  let lastKnownFirmware = null;
  let lastKnownSlot = null;
  async function fetchAll(silent = false) {
    if (isFetching) return;
    isFetching = true;
    try {
      if (!silent) status = "loading";
      const [sys, ota, upcoming] = await Promise.all([
        getSystemInfo(),
        getOTAStatus(),
        getUpcomingTasks().catch(() => ({ users: [] }))
      ]);
      // Detect any OTA update: firmware version change OR www partition flip
      const fwChanged = lastKnownFirmware && sys.firmware !== lastKnownFirmware;
      const slotChanged = lastKnownSlot !== null && ota.active_slot !== lastKnownSlot;
      if (fwChanged || slotChanged) {
        console.log(`OTA detected (fw: ${fwChanged}, slot: ${slotChanged}). Reloading...`);
        window.location.href = window.location.pathname + '?t=' + Date.now();
        return;
      }
      lastKnownFirmware = sys.firmware;
      lastKnownSlot = ota.active_slot;
      systemInfo = sys;
      otaStatus = ota;
      upcomingData = upcoming;
      status = "ok";
      errorMsg = "";
    } catch (e) {
      if (!isRecovering) {
        status = "error";
        errorMsg = e.message || "Connection failed";
      }
    } finally {
      isFetching = false;
    }
  }

  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 (silently to avoid flashing)
    const interval = setInterval(() => fetchAll(true), 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="flex min-h-screen bg-bg-primary">
  <Sidebar 
    {currentView} 
    isOpen={mobileMenuOpen}
    onNavigate={(view) => { currentView = view; mobileMenuOpen = false; }} 
    onToggle={() => mobileMenuOpen = !mobileMenuOpen}
  />

  {#if mobileMenuOpen}
    <button 
      class="fixed inset-0 bg-black/40 backdrop-blur z-[999] border-none p-0 cursor-pointer" 
      onclick={() => mobileMenuOpen = false}
      aria-label="Close menu"
    ></button>
  {/if}

  <main class="main-gradient-bg flex-1 p-8 h-screen overflow-y-auto max-md:p-4 max-md:h-auto">
    <!-- Mobile Top Bar -->
    <header class="hidden max-md:flex items-center justify-between px-4 py-3 bg-bg-card border-b border-border sticky top-0 z-50 backdrop-blur-[10px] max-md:-mx-4 max-md:-mt-4 max-md:mb-5">
      <!-- svelte-ignore a11y_consider_explicit_label -->
      <button class="bg-transparent border-none text-text-primary p-2 cursor-pointer" onclick={() => mobileMenuOpen = true}>
        <svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
          <line x1="3" y1="6" x2="21" y2="6"></line>
          <line x1="3" y1="12" x2="21" y2="12"></line>
          <line x1="3" y1="18" x2="21" y2="18"></line>
        </svg>
      </button>
      <span class="font-bold text-base tracking-[-0.02em] text-accent">Calendink</span>
      <div class="w-10"></div> <!-- Spacer -->
    </header>

    <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}
          {@const periodNames = ['Morning', 'Afternoon', 'Evening']}
          {@const periodIcons = ['🌅', '☀️', '🌙']}
          <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">
                📋 Today's Routine
              </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}
                {@const routineTasks = user.tasks.filter(t => t.recurrence > 0)}
                <div class="p-4">
                  <h3 class="text-xs font-bold text-accent mb-3 uppercase tracking-wider">{user.name}</h3>
                  {#if routineTasks.length === 0}
                    <p class="text-[11px] text-text-secondary italic">No routine tasks</p>
                  {:else}
                    {#each [0, 1, 2] as periodIdx}
                      {@const tasksForPeriod = routineTasks.filter(t => t.period & (1 << periodIdx))}
                      {#if tasksForPeriod.length > 0}
                        <div class="mb-2">
                          <div class="text-[10px] uppercase tracking-wider text-text-secondary font-semibold mb-1">
                            {periodIcons[periodIdx]} {periodNames[periodIdx]}
                          </div>
                          {#each tasksForPeriod as task}
                            <div class="flex items-center gap-2 py-0.5 pl-3">
                              <span class="text-xs text-text-primary leading-tight">• {task.title}</span>
                              {#if task.recurrence > 0}
                                <span class="text-[9px] text-accent font-mono">
                                  {task.recurrence === 0x7F ? '∞' : task.recurrence === 0x1F ? 'wk' : ''}
                                </span>
                              {:else if task.due_date > 0}
                                <span class="text-[9px] {isOverdue(task.due_date) ? 'text-danger' : 'text-text-secondary'} font-mono">
                                  {formatRelativeDate(task.due_date)}
                                </span>
                              {/if}
                            </div>
                          {/each}
                        </div>
                      {/if}
                    {/each}
                  {/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 otaInfo={otaStatus} {systemInfo} 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>
      {:else if currentView === 'users'}
        <!-- User Management View -->
        <div class="bg-bg-card border border-border rounded-xl p-8 shadow-xl">
          <UserManager mode="manager" />
        </div>
      {:else if currentView === 'devices'}
        <!-- Device Management View -->
        <div class="bg-bg-card border border-border rounded-xl p-6 shadow-xl">
          <DeviceManager />
        </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>

<Spinner />
