<script setup lang="ts">
import { defineAsyncComponent, onUnmounted, ref, watch } from 'vue';
import RequestPanel from './components/RequestPanel.vue';
import ResponsePanel from './components/ResponsePanel.vue';
import Sidebar from './components/Sidebar.vue';

const SettingsModal = defineAsyncComponent(() => import('./components/SettingsModal.vue'));
const PANEL_HEIGHT_STORAGE_KEY = 'topPanelHeight';
const DEFAULT_TOP_PANEL_HEIGHT = 50;

const clampPanelHeight = (value: number) => {
  if (Number.isNaN(value)) return DEFAULT_TOP_PANEL_HEIGHT;
  return Math.min(80, Math.max(20, value));
};

const showSettings = ref(false);
const topPanelHeight = ref(
  clampPanelHeight(Number(localStorage.getItem(PANEL_HEIGHT_STORAGE_KEY)) || DEFAULT_TOP_PANEL_HEIGHT)
);
const isDragging = ref(false);

const startDrag = (event: MouseEvent) => {
  event.preventDefault();
  isDragging.value = true;
  window.addEventListener('mousemove', onDrag);
  window.addEventListener('mouseup', stopDrag);
};

const onDrag = (e: MouseEvent) => {
  if (!isDragging.value) return;
  
  const containerHeight = window.innerHeight;
  const newPercentage = (e.clientY / containerHeight) * 100;
  topPanelHeight.value = clampPanelHeight(newPercentage);
};

const stopDrag = () => {
  isDragging.value = false;
  window.removeEventListener('mousemove', onDrag);
  window.removeEventListener('mouseup', stopDrag);
};

onUnmounted(() => {
  window.removeEventListener('mousemove', onDrag);
  window.removeEventListener('mouseup', stopDrag);
});

watch(topPanelHeight, (value) => {
  localStorage.setItem(PANEL_HEIGHT_STORAGE_KEY, clampPanelHeight(value).toString());
});
</script>

<template>
  <div class="flex h-screen w-full bg-slate-950 text-slate-200 font-sans overflow-hidden">
    <!-- Sidebar -->
    <Sidebar @open-settings="showSettings = true" />

    <!-- Main Workspace -->
    <main class="flex-1 flex flex-col min-w-0 bg-slate-900 h-full relative">
      <!-- Request Panel (Top) -->
      <div class="min-h-0" :style="{ height: topPanelHeight + '%' }">
        <RequestPanel />
      </div>

      <!-- Resizer Handle -->
      <div 
        class="h-1 bg-slate-800 hover:bg-indigo-500 cursor-row-resize transition-colors z-10 flex-shrink-0"
        @mousedown="startDrag"
      ></div>

      <!-- Response Panel (Bottom) -->
      <div class="flex-1 min-h-0 overflow-hidden">
        <ResponsePanel />
      </div>
    </main>

    <SettingsModal v-if="showSettings" @close="showSettings = false" />
  </div>
</template>
