<template>
  <div class="h-full flex flex-col bg-slate-900 rounded-lg border border-slate-800 overflow-hidden shadow-xl">
    <!-- Header with Action -->
    <div class="px-6 py-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
      <div class="flex items-center space-x-3">
        <div class="bg-indigo-500/20 p-2 rounded-lg">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-indigo-400" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M3 5a2 2 0 012-2h10a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2V5zm11 1H6v8h8V6z" clip-rule="evenodd" />
          </svg>
        </div>
        <div>
          <h2 class="text-sm font-bold text-slate-100 uppercase tracking-wider">Device Information</h2>
          <p class="text-[10px] text-slate-500 font-medium">REAL-TIME HARDWARE DIAGNOSTICS</p>
        </div>
      </div>
      <div class="flex items-center space-x-2">
        <button 
          v-if="chipInfo"
          @click="downloadAllInfo"
          class="flex items-center space-x-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold rounded-lg transition-all shadow-lg shadow-emerald-900/40"
        >
          <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
          <span>DOWNLOAD INFO</span>
        </button>
        <button 
          @click="readChipInfo"
          :disabled="isReading"
          class="flex items-center space-x-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-xs font-bold rounded-lg transition-all shadow-lg shadow-indigo-900/40"
        >
          <svg v-if="isReading" class="animate-spin h-3 w-3 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span>{{ isReading ? 'READING...' : 'REFRESH INFO' }}</span>
        </button>
      </div>
    </div>

    <!-- Tab Navigation -->
    <div class="px-6 flex border-b border-slate-800 bg-slate-900/30">
      <button 
        v-for="tab in tabs" 
        :key="tab.id"
        @click="activeTab = tab.id"
        class="px-4 py-3 text-xs font-bold transition-all relative"
        :class="activeTab === tab.id ? 'text-indigo-400' : 'text-slate-500 hover:text-slate-300'"
      >
        {{ tab.label }}
        <div v-if="activeTab === tab.id" class="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-500"></div>
      </button>
    </div>

    <!-- Tab Content -->
    <div class="flex-1 overflow-y-auto p-6 bg-slate-900/20">
      <div v-if="!chipInfo" class="h-full flex flex-col items-center justify-center text-slate-600 space-y-4">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 opacity-20" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <p class="text-sm font-medium">No information available. Click refresh to read from device.</p>
      </div>

      <div v-else class="space-y-6 animate-in fade-in duration-300">
        <!-- Chip Tab -->
        <div v-if="activeTab === 'chip'" class="grid grid-cols-1 gap-4">
           <InfoCard title="Chip Identity" icon="cpu">
             <InfoRow label="Model" :value="chipInfo.chip.model" />
             <InfoRow label="Revision" :value="chipInfo.chip.revision" />
             <InfoRow label="MAC Address" :value="chipInfo.chip.mac" class="font-mono text-indigo-300" />
           </InfoCard>
           <InfoCard title="Supported Features" icon="lightning" v-if="chipInfo.chip.features">
             <div class="flex flex-wrap gap-2 mt-1">
               <template v-for="feat in chipInfo.chip.features.split(',')" :key="feat">
                 <span v-if="feat.trim()" class="px-2 py-1 bg-slate-800 border border-slate-700 rounded text-[10px] text-slate-300 uppercase font-bold">
                   {{ feat.trim() }}
                 </span>
               </template>
             </div>
           </InfoCard>
           <InfoCard title="Raw Output" icon="code" v-if="chipInfo.chip.raw">
             <div class="bg-slate-950/50 rounded-lg p-3 font-mono text-[10px] text-slate-500 overflow-x-auto whitespace-pre-wrap">
               {{ chipInfo.chip.raw }}
             </div>
           </InfoCard>
        </div>

        <!-- Flash Tab -->
        <div v-if="activeTab === 'flash'" class="grid grid-cols-1 gap-4">
           <InfoCard title="Flash Hardware" icon="chip">
             <InfoRow label="Manufacturer ID" :value="chipInfo.flash.manufacturer_id" />
             <InfoRow label="Device ID" :value="chipInfo.flash.device_id" />
             <InfoRow label="Detected Size" :value="chipInfo.flash.size" class="text-emerald-400" />
           </InfoCard>
           <InfoCard title="Status Register" icon="status">
             <div class="font-mono text-xl text-indigo-400 mt-2">{{ chipInfo.flash.status || 'N/A' }}</div>
           </InfoCard>
           <InfoCard title="Raw Output" icon="code" v-if="chipInfo.flash.raw">
             <div class="bg-slate-950/50 rounded-lg p-3 font-mono text-[10px] text-slate-500 overflow-x-auto whitespace-pre-wrap">
               {{ chipInfo.flash.raw }}
             </div>
           </InfoCard>
        </div>

        <!-- ADC Tab -->
        <div v-if="activeTab === 'adc'" class="h-full">
           <div class="bg-slate-950/50 rounded-lg p-4 font-mono text-xs text-slate-300 border border-slate-800 leading-relaxed whitespace-pre-wrap">
             {{ chipInfo.adc || 'No ADC calibration data found.' }}
           </div>
        </div>

        <!-- EFuse Tab -->
        <div v-if="activeTab === 'efuse'" class="h-full">
          <div class="bg-slate-950/50 rounded-lg p-4 font-mono text-xs text-slate-300 border border-slate-800 leading-relaxed whitespace-pre-wrap max-h-[400px] overflow-y-auto">
             {{ chipInfo.efuse || 'No eFuse summary available.' }}
           </div>
        </div>

        <!-- Security Tab -->
        <div v-if="activeTab === 'security'" class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
              <SecurityIndicator label="Flash Encryption" :status="chipInfo.security.flash_encryption" />
              <SecurityIndicator label="Secure Boot" :status="chipInfo.security.secure_boot" />
            </div>
            <InfoCard title="Security Details" icon="lock">
              <div class="bg-slate-950/50 rounded-lg p-4 font-mono text-[10px] text-slate-400 overflow-x-auto whitespace-pre-wrap">
                {{ chipInfo.security.raw }}
              </div>
            </InfoCard>
        </div>

        <!-- Progress Bar (Visible during long ops) -->
        <div v-if="isFirmwareOperationActive && firmwareProgress.progress > 0" class="mb-6 p-4 bg-slate-900/50 rounded-xl border border-indigo-500/30 animate-in fade-in slide-in-from-top-4 duration-500">
          <div class="flex justify-between items-center mb-2">
            <span class="text-[10px] font-black uppercase tracking-widest text-indigo-400">
              {{ firmwareProgress.operation || 'Firmware Operation' }}
            </span>
            <span class="text-[10px] font-black text-indigo-300">{{ firmwareProgress.progress }}%</span>
          </div>
          <div class="h-2 w-full bg-slate-800 rounded-full overflow-hidden border border-slate-700/50">
            <div 
              class="h-full bg-gradient-to-r from-indigo-600 to-emerald-500 transition-all duration-300 ease-out"
              :style="{ width: `${firmwareProgress.progress}%` }"
            ></div>
          </div>
        </div>

        <!-- Partitions Tab -->
        <div v-if="activeTab === 'partitions'" class="space-y-4">
           <div class="flex justify-end">
              <button 
                @click="refreshPartitions"
                :disabled="isReadingDetail || isFirmwareOperationActive"
                class="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-50 text-slate-300 text-[10px] font-bold rounded border border-slate-700 transition-all"
              >
                REFRESH PARTITIONS
              </button>
           </div>
           <div v-if="!partitionTable" class="flex items-center justify-center p-12 text-slate-500 animate-pulse">
              <span class="text-xs font-bold uppercase tracking-widest">Reading Flash Partition Table...</span>
           </div>
           <div v-else-if="partitionTable.status === 'error'" class="p-4 bg-rose-900/10 border border-rose-800/30 rounded-xl text-rose-400 text-xs">
              Error reading partition table: {{ partitionTable.error }}
           </div>
           <div v-else class="bg-slate-950/40 rounded-xl border border-slate-800 overflow-hidden">
              <table class="w-full text-left text-[11px] border-collapse">
                <thead>
                  <tr class="bg-slate-800/50 text-slate-400 uppercase font-black tracking-tighter">
                    <th class="px-4 py-3">Label</th>
                    <th class="px-4 py-3">Type</th>
                    <th class="px-4 py-3">Sub</th>
                    <th class="px-4 py-3">Offset</th>
                    <th class="px-4 py-3 text-right">Size</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-slate-800/50">
                  <tr v-for="p in partitionTable.partitions" :key="p.offset" class="hover:bg-indigo-500/5 transition-colors">
                    <td class="px-4 py-3 font-black text-slate-200">{{ p.label }}</td>
                    <td class="px-4 py-3">
                      <span class="px-1.5 py-0.5 rounded" :class="p.type === 'app' ? 'bg-indigo-500/20 text-indigo-400' : 'bg-slate-700/50 text-slate-500'">
                        {{ p.type }}
                      </span>
                    </td>
                    <td class="px-4 py-3 text-slate-500 font-mono">{{ p.subtype }}</td>
                    <td class="px-4 py-3 text-emerald-500/80 font-mono">{{ p.offset }}</td>
                    <td class="px-4 py-3 text-right text-slate-300 font-mono">{{ p.size }}</td>
                  </tr>
                </tbody>
              </table>
           </div>
        </div>

        <!-- App Info Tab -->
        <div v-if="activeTab === 'app'" class="space-y-4">
           <div class="flex justify-between items-center">
              <span class="text-[10px] text-slate-500 font-bold uppercase tracking-widest pl-2">App & Firmware</span>
              <div class="flex space-x-2">
                 <button 
                   @click="downloadFullFlash"
                   :disabled="isReadingDetail || isFirmwareOperationActive"
                   class="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-[10px] font-bold rounded border border-indigo-500 transition-all flex items-center space-x-1"
                 >
                   <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                   <span>DOWNLOAD FULL FLASH</span>
                 </button>
                 <button 
                   @click="refreshAppInfo"
                   :disabled="isReadingDetail || isFirmwareOperationActive"
                   class="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 disabled:opacity-50 text-slate-300 text-[10px] font-bold rounded border border-slate-700 transition-all"
                 >
                   REFRESH APP INFO
                 </button>
              </div>
           </div>

           <!-- Full Flash Download Ready Notification -->
           <div v-if="latestFirmwareRead && latestFirmwareRead.status === 'success'" class="p-3 bg-emerald-900/20 border border-emerald-500/30 rounded-xl animate-in fade-in slide-in-from-top-2 flex flex-col sm:flex-row items-center justify-between gap-3">
               <div class="flex items-center space-x-3">
                 <div class="p-2 rounded-full bg-emerald-500/20 text-emerald-400">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                 </div>
                 <div>
                    <p class="text-xs text-emerald-400 font-bold">Full Flash Dump Ready</p>
                    <p class="text-[10px] text-emerald-500/70">Saved as {{ latestFirmwareRead.filename }}</p>
                 </div>
               </div>
               <div class="flex space-x-2">
                 <a 
                    :href="`/dumps/${latestFirmwareRead.filename}`" 
                    :download="latestFirmwareRead.filename"
                    class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-[10px] font-bold rounded-lg transition-all shadow-lg whitespace-nowrap flex items-center gap-1"
                  >
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                    DOWNLOAD .BIN
                 </a>
                 <a 
                    v-if="latestFirmwareRead.json_filename"
                    :href="`/dumps/${latestFirmwareRead.json_filename}`" 
                    :download="latestFirmwareRead.json_filename"
                    class="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-slate-200 text-[10px] font-bold rounded-lg transition-all shadow-lg whitespace-nowrap flex items-center gap-1"
                  >
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                    BIN INFO
                 </a>
               </div>
           </div>

           <div v-if="!appInfo" class="flex items-center justify-center p-12 text-slate-500 animate-pulse">
              <span class="text-xs font-bold uppercase tracking-widest">Extracting App Header(s)...</span>
           </div>
           <div v-else-if="appInfo.status === 'error'" class="p-4 bg-rose-900/10 border border-rose-800/30 rounded-xl text-rose-400 text-xs">
              Error reading app info: {{ appInfo.error }}
           </div>
           <div v-else class="space-y-6">
                <div v-for="(info, idx) in appInfo.apps" :key="idx" class="grid grid-cols-1 md:grid-cols-2 gap-4 bg-slate-900/40 p-4 border border-slate-800/60 rounded-xl relative">
                   <div class="absolute top-0 right-0 px-2 py-0.5 bg-indigo-500/20 border-b border-l border-indigo-500/30 text-[9px] text-indigo-400 font-bold uppercase rounded-bl-lg rounded-tr-xl">
                       {{ info.label || 'factory' }}
                   </div>
                   <InfoCard title="Firmware Metadata" icon="info">
                      <InfoRow label="Project Name" :value="info.project_name" />
                      <InfoRow label="Version" :value="info.app_version" class="text-indigo-400" />
                      <InfoRow label="Compile Time" :value="info.compile_time" />
                      <InfoRow label="Offset" :value="info.offset" class="font-mono text-slate-500" />
                   </InfoCard>
                   <InfoCard title="Application Output" icon="code">
                     <div class="bg-slate-950/50 rounded-lg p-3 font-mono text-[9px] text-slate-500 h-[100px] overflow-y-auto whitespace-pre-wrap">
                       {{ info.raw }}
                     </div>
                   </InfoCard>
                </div>
           </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { chipInfo, partitionTable, appInfo, sendCommand, latestFirmwareRead, availablePorts, isFirmwareOperationActive, firmwareProgress } from '../services/backend';
import InfoRow from './InfoRow.vue';
import InfoCard from './InfoCard.vue';
import SecurityIndicator from './SecurityIndicator.vue';

const baseOrigin = (typeof window !== 'undefined' && window.location) ? window.location.origin : '';

const activeTab = ref('chip');
const isReading = ref(false);

const tabs = [
  { id: 'chip', label: 'CHIP' },
  { id: 'flash', label: 'FLASH' },
  { id: 'adc', label: 'ADC' },
  { id: 'efuse', label: 'EFUSE' },
  { id: 'security', label: 'SECURITY' },
  { id: 'partitions', label: 'PARTITIONS' },
  { id: 'app', label: 'APP INFO' }
];
const isReadingDetail = ref(false);

watch(activeTab, (newTab) => {
  // We no longer auto-fetch every time if data is already there.
  // The user should use the manual refresh button if they suspect the state changed.
});

function refreshPartitions() {
  isReadingDetail.value = true;
  sendCommand('GET_PARTITION_TABLE');
}

const isRefreshingAppInfo = ref(false);

function downloadFullFlash() {
  isReadingDetail.value = true;
  isFirmwareOperationActive.value = true;
  
  if (!partitionTable.value && !chipInfo.value) {
    sendCommand('GET_CHIP_INFO');
  }

  let size = "0x400000"; // default 4MB
  if (chipInfo.value && chipInfo.value.flash && chipInfo.value.flash.size) {
    let sizeStr = String(chipInfo.value.flash.size);
    let mb = parseInt(sizeStr.replace("MB", ""));
    if (!isNaN(mb)) {
      size = "0x" + (mb * 1024 * 1024).toString(16);
    }
  }
  
  let pName = "full_flash";
  if (appInfo.value && appInfo.value.apps && appInfo.value.apps.length > 0) {
      pName = appInfo.value.apps[0].project_name || pName;
  }
  sendCommand('READ_FIRMWARE', { offset: "0x0", size: size, filename: `${pName}_full_flash.bin` });
}

function refreshAppInfo() {
  console.log("Refreshing App Info with baseOrigin:", baseOrigin);
  isReadingDetail.value = true;
  isFirmwareOperationActive.value = true;
  isRefreshingAppInfo.value = true;
  
  if (!partitionTable.value) {
    sendCommand('GET_PARTITION_TABLE');
  }

  let appParts = [];
  if (partitionTable.value && partitionTable.value.partitions) {
    appParts = partitionTable.value.partitions.filter(p => p.type === 'app');
  }
  
  sendCommand('GET_APP_INFO', { partitions: appParts });
}

function readChipInfo() {
  isReading.value = true;
  sendCommand('GET_CHIP_INFO');
}

function downloadAllInfo() {
  const allInfo = {
    chipInfo: chipInfo.value,
    partitionTable: partitionTable.value,
    appInfo: appInfo.value
  };
  const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(allInfo, null, 2));
  const filename = chipInfo.value?.chip?.model ? `${chipInfo.value.chip.model.replace(/\s+/g, '_')}_info.json` : "device_info.json";
  
  const downloadAnchorNode = document.createElement('a');
  downloadAnchorNode.setAttribute("href", dataStr);
  downloadAnchorNode.setAttribute("download", filename);
  document.body.appendChild(downloadAnchorNode);
  downloadAnchorNode.click();
  downloadAnchorNode.remove();
}

// Reset loading state when data arrives
watch(chipInfo, () => {
  isReading.value = false;
});



// Watch for app info completion
watch(appInfo, (val) => {
    if (val) {
        if (isRefreshingAppInfo.value) {
            isRefreshingAppInfo.value = false;
        }
        isReadingDetail.value = false;
        isFirmwareOperationActive.value = false;
    }
});

watch([partitionTable, appInfo], () => {
  isReadingDetail.value = false;
});

// Helper Components (Inline logic for simulation)
</script>



<style scoped>
/* Custom scrollbar for efuse/log text */
::-webkit-scrollbar {
  width: 4px;
}
::-webkit-scrollbar-track {
  background: rgba(15, 23, 42, 0.5);
}
::-webkit-scrollbar-thumb {
  background: #334155;
  border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
  background: #475569;
}
</style>
