<template>
  <div
    ref="panelRef"
    :class="[
      'resizable-panel',
      `resizable-panel-${position}`,
      { 'collapsed': isCollapsed }
    ]"
    :style="panelStyle"
    :aria-label="`${position} panel`"
  >
    <!-- Resize Handle -->
    <div
      v-if="!isCollapsed"
      :class="['resize-handle', `resize-handle-${position}`]"
      @mousedown="startResize"
      @touchstart="startResize"
      :aria-label="`Resize ${position} panel`"
      role="separator"
      :aria-orientation="position === 'bottom' ? 'horizontal' : 'vertical'"
      tabindex="0"
      @keydown="handleKeyboardResize"
    >
      <div class="resize-handle-indicator"></div>
    </div>

    <!-- Collapse Toggle Button -->
    <button
      :class="['collapse-toggle', `collapse-toggle-${position}`]"
      @click="toggleCollapse"
      :title="isCollapsed ? `Expand ${position} panel` : `Collapse ${position} panel`"
      :aria-label="isCollapsed ? `Expand ${position} panel` : `Collapse ${position} panel`"
      type="button"
    >
      <span class="sr-only">{{ isCollapsed ? `Expand ${position} panel` : `Collapse ${position} panel` }}</span>
      <i :class="getToggleIcon()" aria-hidden="true"></i>
    </button>

    <!-- Panel Content -->
    <div v-if="!isCollapsed" class="panel-content">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';

interface Props {
  position: 'left' | 'right' | 'bottom';
  defaultSize?: number;
  minSize?: number;
  maxSize?: number;
  collapsed?: boolean;
  leftPanelSize?: number;
  rightPanelSize?: number;
  leftPanelCollapsed?: boolean;
  rightPanelCollapsed?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  defaultSize: 250,
  minSize: 100,
  maxSize: 800,
  collapsed: false,
  leftPanelSize: 250,
  rightPanelSize: 300,
  leftPanelCollapsed: false,
  rightPanelCollapsed: false,
});

const emit = defineEmits<{
  'update:collapsed': [value: boolean];
  'resize': [size: number];
}>();

const panelRef = ref<HTMLElement | null>(null);
const isCollapsed = ref(props.collapsed);
const size = ref(props.defaultSize);
const isResizing = ref(false);
const startPos = ref(0);
const startSize = ref(0);
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;

// Watch for external collapsed changes
watch(() => props.collapsed, (newVal) => {
  isCollapsed.value = newVal;
});

const panelStyle = computed(() => {
  if (isCollapsed.value) {
    if (props.position === 'left' || props.position === 'right') {
      return {
        width: '0px',
        height: '100%',
      };
    } else {
      return {
        width: '100%',
        height: '0px',
      };
    }
  }

  if (props.position === 'left' || props.position === 'right') {
    return { 
      width: `${size.value}px`, 
      height: '100%',
    };
  } else {
    // Bottom panel: sandwiched between left and right panels
    const left = props.leftPanelCollapsed ? 0 : props.leftPanelSize;
    const right = props.rightPanelCollapsed ? 0 : props.rightPanelSize;
    
    return { 
      left: `${left}px`,
      right: `${right}px`,
      width: 'auto',
      height: `${size.value}px`,
    };
  }
});

const getToggleIcon = (): string => {
  if (isCollapsed.value) {
    if (props.position === 'left') return 'fas fa-chevron-right';
    if (props.position === 'right') return 'fas fa-chevron-left';
    return 'fas fa-chevron-up';
  } else {
    if (props.position === 'left') return 'fas fa-chevron-left';
    if (props.position === 'right') return 'fas fa-chevron-right';
    return 'fas fa-chevron-down';
  }
};

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
  emit('update:collapsed', isCollapsed.value);
  savePanelState();
};

const savePanelState = () => {
  // Debounce localStorage writes
  if (resizeTimeout) {
    clearTimeout(resizeTimeout);
  }
  resizeTimeout = setTimeout(() => {
    localStorage.setItem(`panel-size-${props.position}`, size.value.toString());
    localStorage.setItem(`panel-collapsed-${props.position}`, isCollapsed.value.toString());
  }, 300);
};

const startResize = (e: MouseEvent | TouchEvent) => {
  e.preventDefault();
  e.stopPropagation();
  isResizing.value = true;
  
  if (e instanceof MouseEvent) {
    startPos.value = props.position === 'bottom' ? e.clientY : e.clientX;
  } else {
    startPos.value = props.position === 'bottom' ? e.touches[0].clientY : e.touches[0].clientX;
  }
  
  startSize.value = size.value;
  
  document.addEventListener('mousemove', handleResize, { passive: false });
  document.addEventListener('mouseup', stopResize, { once: true });
  document.addEventListener('touchmove', handleResize, { passive: false });
  document.addEventListener('touchend', stopResize, { once: true });
  
  document.body.style.cursor = props.position === 'bottom' ? 'row-resize' : 'col-resize';
  document.body.style.userSelect = 'none';
  document.body.style.pointerEvents = 'none';
};

const handleResize = (e: MouseEvent | TouchEvent) => {
  if (!isResizing.value) return;
  e.preventDefault();
  
  let currentPos: number;
  if (e instanceof MouseEvent) {
    currentPos = props.position === 'bottom' ? e.clientY : e.clientX;
  } else {
    currentPos = props.position === 'bottom' ? e.touches[0].clientY : e.touches[0].clientX;
  }
  
  const delta = props.position === 'left' 
    ? currentPos - startPos.value
    : props.position === 'right'
    ? startPos.value - currentPos
    : startPos.value - currentPos;
  
  let newSize = startSize.value + delta;
  newSize = Math.max(props.minSize, Math.min(props.maxSize, newSize));
  
  size.value = newSize;
  emit('resize', newSize);
};

const handleKeyboardResize = (e: KeyboardEvent) => {
  if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;
  
  e.preventDefault();
  const step = e.shiftKey ? 10 : 1;
  let newSize = size.value;
  
  if (props.position === 'left') {
    if (e.key === 'ArrowRight') newSize += step;
    if (e.key === 'ArrowLeft') newSize -= step;
  } else if (props.position === 'right') {
    if (e.key === 'ArrowLeft') newSize += step;
    if (e.key === 'ArrowRight') newSize -= step;
  } else {
    if (e.key === 'ArrowUp') newSize += step;
    if (e.key === 'ArrowDown') newSize -= step;
  }
  
  newSize = Math.max(props.minSize, Math.min(props.maxSize, newSize));
  size.value = newSize;
  emit('resize', newSize);
  savePanelState();
};

const stopResize = () => {
  isResizing.value = false;
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('touchmove', handleResize);
  document.body.style.cursor = '';
  document.body.style.userSelect = '';
  document.body.style.pointerEvents = '';
  savePanelState();
};

onMounted(() => {
  // Load saved size and collapsed state from localStorage
  const savedSize = localStorage.getItem(`panel-size-${props.position}`);
  const savedCollapsed = localStorage.getItem(`panel-collapsed-${props.position}`);
  
  if (savedSize) {
    const parsedSize = parseInt(savedSize, 10);
    if (!isNaN(parsedSize) && parsedSize >= props.minSize && parsedSize <= props.maxSize) {
      size.value = parsedSize;
    }
  }
  
  if (savedCollapsed === 'true') {
    isCollapsed.value = true;
    emit('update:collapsed', true);
  }
});

onUnmounted(() => {
  // Cleanup
  if (resizeTimeout) {
    clearTimeout(resizeTimeout);
  }
  stopResize();
});

// Watch for size changes and debounce saves
watch(size, () => {
  savePanelState();
});
</script>

<style scoped>
/* Panel styles moved to panels.css for consistency and optimization */
</style>
