<template>
  <div class="h-full flex flex-col bg-slate-900 rounded-lg p-4 shadow-lg overflow-hidden">
    <div class="flex justify-between items-center mb-4 flex-shrink-0">
      <h2 class="text-xl font-semibold text-slate-100">Control Panel</h2>
      <button 
        @click="refreshParams"
        :disabled="isRefreshing"
        class="p-1.5 bg-slate-800 hover:bg-slate-700 rounded-md text-slate-400 hover:text-indigo-400 transition-colors disabled:opacity-50"
        title="Refresh Parameters"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" :class="{'animate-spin': isRefreshing}" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
        </svg>
      </button>
    </div>
    
    <div v-if="isRefreshing" class="mb-4 text-[10px] text-indigo-400 font-bold uppercase tracking-widest text-center animate-pulse">
      Syncing Parameters...
    </div>

    <div class="flex-1 overflow-y-auto pr-2 space-y-6 custom-scrollbar">
      <!-- Group parameters by their 'group' attribute -->
      <div v-for="(params, groupName) in groupedParams" :key="groupName" class="bg-slate-800 rounded-lg p-3 border border-slate-700">
        <h3 class="text-sm font-semibold uppercase tracking-wider text-slate-400 mb-3">{{ groupName }}</h3>
        
        <div class="space-y-4">
          <div v-for="param in params" :key="param.id" class="flex flex-col space-y-2">
            
            <!-- Label & Value Display -->
            <div class="flex justify-between items-center">
              <label :for="'param-' + param.id" class="text-sm font-medium text-slate-300">
                {{ param.label || param.id }}
              </label>
              
              <!-- Value display for sliders -->
              <span v-if="param.widget === 'slider'" class="bg-indigo-900/50 text-indigo-300 text-xs px-2 py-1 rounded font-mono">
                {{ paramValues[param.id] }}
              </span>
            </div>
            
            <!-- Type: Slider -->
            <input 
              v-if="param.widget === 'slider' || !param.widget" 
              :id="'param-' + param.id"
              type="range" 
              :min="param.min || 0" 
              :max="param.max || 100" 
              v-model.number="paramValues[param.id]"
              @change="onParamChange(param)"
              class="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-indigo-500"
            />
            
            <!-- Type: Spinbox -->
            <input 
              v-else-if="param.widget === 'spinbox'" 
              :id="'param-' + param.id"
              type="number" 
              :step="param.type === 'float' ? '0.01' : '1'"
              :min="param.min" 
              :max="param.max" 
              v-model.number="paramValues[param.id]"
              @change="onParamChange(param)"
              class="bg-slate-950 border border-slate-700 text-slate-200 text-sm rounded-md focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2"
            />
            
            <!-- Type: ComboBox -->
            <select 
              v-else-if="param.widget === 'combo'" 
              :id="'param-' + param.id"
              v-model="paramValues[param.id]"
              @change="onParamChange(param)"
              class="bg-slate-950 border border-slate-700 text-slate-200 text-sm rounded-md focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2"
            >
              <option v-for="(label, val) in param.options" :key="val" :value="val">
                {{ label }}
              </option>
            </select>
            
          </div>
        </div>
      </div>
      
      <!-- Placeholder when no profile -->
      <div v-if="Object.keys(groupedParams).length === 0" class="text-center text-slate-500 mt-10">
        No parameters defined in profile.
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { profileConfig, sendCommand } from '../services/backend';

// State to hold current UI values locally
const paramValues = ref({});
const isRefreshing = ref(false);

// Derived state: Group parameters by their 'group' field (defaulting to 'General')
const groupedParams = computed(() => {
    if (!profileConfig.value || !profileConfig.value.parameters) return {};
    
    return profileConfig.value.parameters.reduce((acc, param) => {
        const groupName = param.group || 'General';
        if (!acc[groupName]) {
            acc[groupName] = [];
        }
        acc[groupName].push(param);
        return acc;
    }, {});
});

// Initialize paramValues when profile loads
watch(profileConfig, (newProfile) => {
    isRefreshing.value = false;
    if (newProfile && newProfile.parameters) {
        newProfile.parameters.forEach(param => {
            if (paramValues.value[param.id] === undefined) {
                paramValues.value[param.id] = param.default !== undefined ? param.default : 0;
            }
        });
    }
}, { immediate: true });

function refreshParams() {
    isRefreshing.value = true;
    sendCommand('FETCH_PROFILE');
}

function onParamChange(param) {
    const newVal = paramValues.value[param.id];
    // Send command back to Python backend
    sendCommand('SET_PARAM', {
        id: param.id,
        value: newVal
    });
}
</script>

<style scoped>
/* Custom Scrollbar for better dark mode blend */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #334155;
  border-radius: 10px;
}
</style>
