<script setup>
import { ref } from 'vue';
import { useProjectStore } from '../stores/projectStore';
import Grid from './Grid.vue';
import componentMap from './componentMap'; // Import the component map

const props = defineProps({
  zoom: Number,
});

const projectStore = useProjectStore();
const artboardRef = ref(null);
const guides = ref([]); // For rendering smart guides

// --- MAIN DRAG/DROP/MOVE LOGIC ---

function getSnappedCoordinates(x, y, skipGrid = false) {
    if (projectStore.activePage?.snapToGrid && !skipGrid) {
        const gridSize = projectStore.gridSize;
        const artboardWidth = projectStore.activePage.width;
        const artboardHeight = projectStore.activePage.height;
        const gridPercentX = (gridSize / artboardWidth) * 100;
        const gridPercentY = (gridSize / artboardHeight) * 100;
        return {
            x: Math.round(x / gridPercentX) * gridPercentX,
            y: Math.round(y / gridPercentY) * gridPercentY,
        };
    }
    return { x, y };
}

function onDrop(event) {
  event.preventDefault();
  const type = event.dataTransfer.getData('text/plain');
  if (type !== 'new-component') return;
  
  const artboardRect = artboardRef.value.getBoundingClientRect();
  const pixelX = (event.clientX - artboardRect.left) / props.zoom;
  const pixelY = (event.clientY - artboardRect.top) / props.zoom;
  const percentX = (pixelX / projectStore.activePage.width) * 100;
  const percentY = (pixelY / projectStore.activePage.height) * 100;
  const snappedCoords = getSnappedCoordinates(percentX, percentY);
  const componentData = JSON.parse(event.dataTransfer.getData('application/json'));
  projectStore.addComponentToActivePage({ component: componentData, x: snappedCoords.x, y: snappedCoords.y });
}

function allowDrop(event) {
  event.preventDefault();
}

function handleMoveStart(event, component) {
  event.preventDefault();
  event.stopPropagation();
  projectStore.setSelectedComponent(component.id); // Select component immediately on mousedown
  
  const startX = event.clientX;
  const startY = event.clientY;
  const moveThreshold = 3; // pixels
  let hasMoved = false;

  const handleMouseMove = (e) => {
    const dx = e.clientX - startX;
    const dy = e.clientY - startY;

    if (!hasMoved) {
        if (Math.abs(dx) < moveThreshold && Math.abs(dy) < moveThreshold) {
            // console.log('Mouse moved within threshold, not a drag yet.');
            return; // Don't do anything until user moves past threshold
        }
        // console.log('Mouse moved past threshold, starting drag.');
        hasMoved = true; // Threshold passed, let's start the real drag
    }
    
    // --- Full Drag Logic (same as before, but only runs after threshold is met) ---
    const artboardWidth = projectStore.activePage.width;
    const artboardHeight = projectStore.activePage.height;
    const initialX = component.x;
    const initialY = component.y;
    let lockedAxis = null;

    const snapThreshold = (5 / artboardWidth) * 100;
    const hTargets = [0, 50, 100];
    const vTargets = [0, 50, 100];
    projectStore.activeComponents.forEach(c => {
        if (c.id === component.id) return;
        hTargets.push(c.x, c.x + c.width / 2, c.x + c.width);
        vTargets.push(c.y, c.y + c.height / 2, c.y + c.height);
    });

    guides.value = [];
    const mouseDx = (e.clientX - startX) / (artboardWidth * props.zoom) * 100;
    const mouseDy = (e.clientY - startY) / (artboardHeight * props.zoom) * 100;
    let newX = initialX + mouseDx;
    let newY = initialY + mouseDy;

    if (e.shiftKey) {
        if (!lockedAxis) lockedAxis = Math.abs(dx) > Math.abs(dy) ? 'h' : 'v';
        if (lockedAxis === 'h') newY = initialY;
        if (lockedAxis === 'v') newX = initialX;
    } else {
        lockedAxis = null;
    }

    // --- Enhanced Smart Guide Snapping ---
    const componentEdgesX = [newX, newX + component.width / 2, newX + component.width];
    const componentEdgesY = [newY, newY + component.height / 2, newY + component.height];

    let snappedX = false;
    for (const target of hTargets) {
        for (let i = 0; i < componentEdgesX.length; i++) {
            if (Math.abs(componentEdgesX[i] - target) < snapThreshold) {
                newX -= (componentEdgesX[i] - target);
                const isCenter = Math.abs(target - 50) < 0.1;
                guides.value.push({ type: 'v', position: target, center: isCenter });
                snappedX = true;
                break;
            }
        }
        if (snappedX) break;
    }

    let snappedY = false;
    for (const target of vTargets) {
        for (let i = 0; i < componentEdgesY.length; i++) {
            if (Math.abs(componentEdgesY[i] - target) < snapThreshold) {
                newY -= (componentEdgesY[i] - target);
                const isCenter = Math.abs(target - 50) < 0.1;
                guides.value.push({ type: 'h', position: target, center: isCenter });
                snappedY = true;
                break;
            }
        }
        if (snappedY) break;
    }

    const snappedCoords = getSnappedCoordinates(newX, newY, guides.value.length > 0);
    projectStore.updateComponentPosition({ id: component.id, x: snappedCoords.x, y: snappedCoords.y });
  };

  const handleMouseUp = () => {
    // console.log('Mouse up, hasMoved:', hasMoved);
    // Component is already selected on mousedown, so no need to re-select here
    guides.value = [];
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
}

function handleComponentResize(event, component, corner) {
  event.preventDefault();
  event.stopPropagation();
  
  const artboardWidth = projectStore.activePage.width;
  const artboardHeight = projectStore.activePage.height;
  
  const initialCompX = component.x;
  const initialCompY = component.y;
  const initialWidth = component.width;
  const initialHeight = component.height;
  
  const startX = event.clientX;
  const startY = event.clientY;

  const handleMousemove = (e) => {
    const dxPercent = (e.clientX - startX) / (artboardWidth * props.zoom) * 100;
    const dyPercent = (e.clientY - startY) / (artboardHeight * props.zoom) * 100;

    let newX = initialCompX;
    let newY = initialCompY;
    let newWidth = initialWidth;
    let newHeight = initialHeight;

    if (corner.includes('right')) {
      newWidth = initialWidth + dxPercent;
    }
    if (corner.includes('left')) {
      newWidth = initialWidth - dxPercent;
      newX = initialCompX + dxPercent;
    }
    if (corner.includes('bottom')) {
      newHeight = initialHeight + dyPercent;
    }
    if (corner.includes('top')) {
      newHeight = initialHeight - dyPercent;
      newY = initialCompY + dyPercent;
    }

    const payload = { id: component.id };
    if (newWidth > 2) {
      payload.width = newWidth;
      payload.x = newX;
    }
    if (newHeight > 2) {
      payload.height = newHeight;
      payload.y = newY;
    }

    projectStore.updateComponentProperties(payload);
  };

  const handleMouseup = () => {
    document.removeEventListener('mousemove', handleMousemove);
    document.removeEventListener('mouseup', handleMouseup);
  };
  
  document.addEventListener('mousemove', handleMousemove);
  document.addEventListener('mouseup', handleMouseup);
}
</script>

<template>
  <div 
    class="artboard-container" 
    @drop="onDrop"
    @dragover="allowDrop"
    @mousedown="projectStore.setSelectedComponent(null)"
  >
    <div 
      ref="artboardRef" <!-- artboardRef now points to the inner artboard -->
      class="artboard" 
      :style="{
        width: projectStore.activePage?.width + 'px', 
        height: projectStore.activePage?.height + 'px',
        transform: `scale(${props.zoom})`,
        transformOrigin: 'top left'
      }"
    >
      <Grid v-if="projectStore.activePage?.gridVisible" :zoom="props.zoom" />
      
      <div 
        v-for="component in projectStore.activeComponents" 
        :key="component.id" 
        class="dropped-component"
        :class="{ selected: component.id === projectStore.selectedComponentId }"
        :style="{
          position: 'absolute', 
          left: component.x + '%', 
          top: component.y + '%',
          width: component.width + '%',
          height: component.height + '%',
          backgroundColor: component.style.backgroundColor,
        }"
        @mousedown.stop="handleMoveStart($event, component)"
      >
        <!-- RENDERED COMPONENT CONTENT -->
        <component :is="componentMap[component.type]" :component="component" v-if="componentMap[component.type]" />
        <div v-else class="unsupported-component">
          Unsupported component type: {{ component.type }}
        </div>
        
        <template v-if="component.id === projectStore.selectedComponentId">
          <div class="resize-handle top-left" @mousedown.stop="handleComponentResize($event, component, 'top-left')"></div>
          <div class="resize-handle top-right" @mousedown.stop="handleComponentResize($event, component, 'top-right')"></div>
          <div class="resize-handle bottom-left" @mousedown.stop="handleComponentResize($event, component, 'bottom-left')"></div>
          <div class="resize-handle bottom-right" @mousedown.stop="handleComponentResize($event, component, 'bottom-right')"></div>
        </template>
      </div>

      <!-- Smart Guides -->
      <div 
        v-for="(guide, index) in guides" 
        :key="index"
        class="guide"
        :class="[guide.type, { center: guide.center }]"
        :style="guide.type === 'h' ? { top: guide.position + '%' } : { left: guide.position + '%' }"
      ></div>
    </div>
  </div>
</template>

<style scoped>
.artboard-container {
  flex-grow: 1; /* Allows it to take available space */
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto; /* Allows scrolling if scaled content exceeds container */
  background-color: var(--bg-color); /* Darker background for the container */
  padding: 20px; /* Some padding around the artboard */
  box-sizing: border-box;
}

.artboard {
  background-color: white; /* Actual design surface background */
  position: relative;
  box-shadow: 0 0 20px rgba(0,0,0,0.2); /* Darker shadow for dark theme */
  overflow: hidden; /* Important for containing percentage-based children */
  flex-shrink: 0;
  /* Will have transform: scale() applied directly in template */
}
.dropped-component {
  min-width: 20px; /* Ensure small components are still clickable/resizable */
  min-height: 20px; /* Ensure small components are still clickable/resizable */
  border: 1px solid transparent; /* Border is transparent unless selected */
  cursor: grab;
  overflow: hidden;
  box-sizing: border-box;
}
.dropped-component:active {
  cursor: grabbing;
}
.dropped-component.selected {
  border-color: var(--accent-color);
  z-index: 10;
}
.unsupported-component {
  background-color: var(--panel-color);
  color: var(--text-color-darker);
  border: 1px dashed var(--border-color);
  border-radius: var(--border-radius);
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 0.8em;
  padding: 5px;
  box-sizing: border-box;
}

/* Removed:
.toggle-switch { ... }
.rendered-card { ... }
.rendered-list { ... }
.rendered-avatar { ... }
.rendered-badge { ... }
.rendered-grid, .rendered-navbar, .rendered-sidebar, .rendered-breadcrumbs, .rendered-tabs, .rendered-pagination, .rendered-alert, .rendered-tooltip, .rendered-modal, .rendered-progress, .rendered-toast, .rendered-datepicker, .rendered-tags, .rendered-carousel, .rendered-chart { ... }
.rendered-tags span { ... }
*/

.resize-handle {
  position: absolute;
  width: 12px;
  height: 12px;
  background-color: var(--accent-color);
  border: 2px solid white;
  border-radius: 100%;
  z-index: 20;
}
.resize-handle.top-left {
  top: -6px;
  left: -6px;
  cursor: nwse-resize;
}
.resize-handle.top-right {
  top: -6px;
  right: -6px;
  cursor: nesw-resize;
}
.resize-handle.bottom-left {
  bottom: -6px;
  left: -6px;
  cursor: nesw-resize;
}
.resize-handle.bottom-right {
  bottom: -6px;
  right: -6px;
  cursor: nwse-resize;
}
.guide {
  position: absolute;
  background-color: #ff0000aa;
  z-index: 1000;
}
.guide.center {
  background-color: var(--accent-color);
}
.guide.h {
  width: 100%;
  height: 1px;
}
.guide.v {
  height: 100%;
  width: 1px;
}
</style>
