<script>
    import { uploadOTAFrontend, uploadOTAFirmware, uploadOTABundle } from "./api.js";

    // otaInfo and systemInfo are passed from App.svelte (already fetched there every 5s)
    let { 
      onReboot = null,
      otaInfo = { active_slot: -1, active_partition: "—", target_partition: "—", partitions: [], running_firmware_label: "—" },
      systemInfo = { firmware: "—" }
    } = $props();

    const IS_DEV = import.meta.env.DEV;

    /** @type {'idle' | 'uploading' | 'success' | 'error'} */
    let status = $state("idle");
    let errorMsg = $state("");
    let uploadProgress = $state(0);
  
    let selectedFile = $state(null);
    let showAdvanced = $state(false);
    /** @type {'frontend' | 'firmware' | 'bundle'} */
    let updateMode = $state("frontend");
    let isDragging = $state(false);
  
    function handleFileChange(event) {
      const files = event.target.files;
      if (files && files.length > 0) processFile(files[0]);
    }

    function handleDrop(event) {
      event.preventDefault();
      isDragging = false;
      const files = event.dataTransfer.files;
      if (files && files.length > 0) processFile(files[0]);
    }

    function processFile(file) {
      if (updateMode === 'bundle') {
        if (file.name.endsWith('.bundle')) {
          selectedFile = file;
          errorMsg = "";
        } else {
          selectedFile = null;
          errorMsg = "Please select a valid .bundle file";
        }
      } else if (file.name.endsWith('.bin')) {
        selectedFile = file;
        errorMsg = "";
      } else {
        selectedFile = null;
        errorMsg = "Please select a valid .bin file";
      }
    }
  
    async function handleUpload() {
      if (!selectedFile) return;
      
      status = "uploading";
      errorMsg = "";
      uploadProgress = 0;
  
      const progressInterval = setInterval(() => {
          if (uploadProgress < 90) uploadProgress += 5;
      }, 500);
  
      try {
        if (updateMode === "frontend") {
            await uploadOTAFrontend(selectedFile);
        } else if (updateMode === "firmware") {
            await uploadOTAFirmware(selectedFile);
        } else {
            await uploadOTABundle(selectedFile);
        }
        clearInterval(progressInterval);
        uploadProgress = 100;
        status = "success";
        if (onReboot) onReboot();
      } catch (e) {
        clearInterval(progressInterval);
        uploadProgress = 0;
        status = "error";
        errorMsg = e.message;
      }
    }

    function toggleMode(mode) {
        if (showAdvanced && updateMode === mode) {
            showAdvanced = false;
        } else {
            showAdvanced = true;
            updateMode = mode;
            selectedFile = null;
            errorMsg = "";
        }
    }

    const currentTarget = $derived.by(() => {
        if (updateMode === 'bundle') return 'FW + UI';
        if (updateMode === 'frontend') return otaInfo.target_partition;
        // For firmware, target is the slot that is NOT the running one
        const runningLabel = otaInfo.running_firmware_label || 'ota_0';
        return runningLabel === 'ota_0' ? 'ota_1' : 'ota_0';
    });
</script>
  
{#if !IS_DEV}
<div class="bg-bg-card border border-border rounded-xl overflow-hidden mt-4">
  <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">
        Updates & Maintenance
    </h2>
    <div class="flex gap-2">
        <button 
            onclick={() => toggleMode('frontend')}
            class="text-[10px] font-bold uppercase tracking-tight px-2 py-1 rounded transition-colors
                   {showAdvanced && updateMode === 'frontend' ? 'bg-accent text-white' : 'bg-border text-text-secondary hover:text-text-primary'}"
        >
            Frontend OTA
        </button>
        <button 
            onclick={() => toggleMode('firmware')}
            class="text-[10px] font-bold uppercase tracking-tight px-2 py-1 rounded transition-colors
                   {showAdvanced && updateMode === 'firmware' ? 'bg-accent text-white' : 'bg-border text-text-secondary hover:text-text-primary'}"
        >
            Firmware
        </button>
        <button 
            onclick={() => toggleMode('bundle')}
            class="text-[10px] font-bold uppercase tracking-tight px-2 py-1 rounded transition-colors
                   {showAdvanced && updateMode === 'bundle' ? 'bg-accent text-white' : 'bg-border text-text-secondary hover:text-text-primary'}"
        >
            Universal Bundle
        </button>
    </div>
  </div>

  <div class="p-5 space-y-4">
     <div class="grid grid-cols-2 gap-4">
       <div class="bg-bg-primary/30 p-3 rounded-lg border border-border/50">
         <div class="text-[10px] uppercase text-text-secondary font-bold mb-1">UI Version</div>
         <div class="text-sm font-mono text-accent">v{__APP_VERSION__}</div>
         <div class="text-[9px] text-text-secondary mt-1">
            Slot: {otaInfo.active_partition} 
            {#if otaInfo.partitions}
              ({(otaInfo.partitions.find(p => p.label === otaInfo.active_partition)?.free / 1024).toFixed(0)} KB free)
            {/if}
         </div>
       </div>
       <div class="bg-bg-primary/30 p-3 rounded-lg border border-border/50">
         <div class="text-[10px] uppercase text-text-secondary font-bold mb-1">FW Version</div>
         <div class="text-sm font-mono text-text-primary">{systemInfo.firmware}</div>
         <div class="text-[9px] text-text-secondary mt-1">
            Active: {otaInfo.active_slot === 0 ? 'ota_0' : 'ota_1'}
         </div>
       </div>
     </div>

     {#if showAdvanced}
       <div class="pt-2 border-t border-border/50 space-y-3">
          <div class="flex items-center justify-between">
            <h3 class="text-xs font-bold text-text-primary">
                OTA Upgrade ({updateMode === 'frontend' ? 'UI' : 'Firmware'})
            </h3>
            <div class="text-[10px] text-text-secondary">
              Target: <span class="font-mono text-accent">{currentTarget}</span>
              {#if updateMode === 'frontend' && otaInfo.partitions}
                <span class="ml-1">
                  ({(otaInfo.partitions.find(p => p.label === otaInfo.target_partition)?.size / 1024 / 1024).toFixed(1)} MB)
                </span>
              {/if}
            </div>
          </div>

          {#if status === "success"}
            <div class="bg-success/10 border border-success/20 text-success p-3 rounded-lg text-xs flex items-center gap-2">
              <span class="w-1.5 h-1.5 rounded-full bg-success"></span>
              Update successful! Rebooting device...
            </div>
          {:else}
            <div 
              role="button"
              aria-label="Upload data"
              tabindex="0"
              class="relative border-2 border-dashed rounded-xl p-6 transition-all duration-200 flex flex-col items-center justify-center gap-2
                     {isDragging ? 'border-accent bg-accent/5' : 'border-border hover:border-border-hover bg-bg-primary/20'}
                     {status === 'uploading' ? 'opacity-50 pointer-events-none' : ''}"
              ondragover={(e) => { e.preventDefault(); isDragging = true; }}
              ondragleave={() => isDragging = false}
              ondrop={handleDrop}
            >
              <input type="file" accept="{updateMode === 'bundle' ? '.bundle' : '.bin'}" onchange={handleFileChange} class="absolute inset-0 opacity-0 cursor-pointer" />
              <div class="text-2xl">{updateMode === 'frontend' ? '🎨' : '⚙️'}</div>
              {#if selectedFile}
                <div class="text-xs font-medium text-text-primary">{selectedFile.name}</div>
                <div class="text-[10px] text-text-secondary">{(selectedFile.size / 1024).toFixed(1)} KB</div>
              {:else}
                <div class="text-xs text-text-primary">Drop {updateMode === 'bundle' ? 'Universal .bundle' : updateMode === 'frontend' ? 'UI .bin' : 'Firmware .bin'} here</div>
                <div class="text-[10px] text-text-secondary">or click to browse</div>
              {/if}
            </div>

            {#if selectedFile}
              <button
                onclick={handleUpload}
                disabled={status === "uploading"}
                class="w-full py-2 text-xs font-bold rounded-lg transition-colors bg-accent text-white hover:brightness-110 disabled:opacity-40"
              >
                {status === "uploading" ? 'Flashing...' : `Update ${updateMode === 'bundle' ? 'Everything' : updateMode === 'frontend' ? 'UI' : 'Firmware'}`}
              </button>
            {/if}

            {#if status === "uploading"}
              <div class="w-full bg-border rounded-full h-1 mt-1 overflow-hidden">
                <div class="bg-accent h-1 rounded-full transition-all duration-300" style="width: {uploadProgress}%"></div>
              </div>
            {:else if status === "error"}
              <p class="text-[10px] text-danger mt-1 bg-danger/5 p-2 rounded border border-danger/10">{errorMsg}</p>
            {/if}
          {/if}
       </div>
     {/if}
  </div>
</div>
{/if}
  
