<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import Artboard from './Artboard.vue';
import { useProjectStore } from '../stores/projectStore';

const projectStore = useProjectStore();

// --- Viewport State ---
const zoom = ref(1);
const pan = reactive({ x: 0, y: 0 });
const viewportRef = ref(null);

// --- Computed style for the content wrapper ---
const contentStyle = computed(() => ({
  transform: `scale(${zoom.value}) translate(${pan.x}px, ${pan.y}px)`,
  transformOrigin: 'top left',
}));

// --- Zoom Logic ---
function handleWheel(event) {
  event.preventDefault();
  const scaleDelta = event.deltaY > 0 ? 0.9 : 1.1;
  const newZoom = Math.max(0.1, Math.min(zoom.value * scaleDelta, 4));

  const viewportRect = viewportRef.value.getBoundingClientRect();
  const mouseX = event.clientX - viewportRect.left;
  const mouseY = event.clientY - viewportRect.top;
  
  // Adjust pan to zoom towards the mouse pointer
  const newPanX = pan.x * scaleDelta + (mouseX / zoom.value) * (1 - scaleDelta);
  const newPanY = pan.y * scaleDelta + (mouseY / zoom.value) * (1 - scaleDelta);

  zoom.value = newZoom;
  pan.x = newPanX;
  pan.y = newPanY;
}

// --- Pan Logic ---
function handlePan(event) {
    // Only pan with middle mouse button
    if (event.button !== 1) return;
    event.preventDefault();
    
    const startX = event.clientX;
    const startY = event.clientY;
    const initialPan = { ...pan };

    const onMouseMove = (e) => {
        pan.x = initialPan.x + (e.clientX - startX) / zoom.value;
        pan.y = initialPan.y + (e.clientY - startY) / zoom.value;
    };

    const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
        viewportRef.value.style.cursor = 'default';
    };

    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
    viewportRef.value.style.cursor = 'grabbing';
}

// --- Fit to Screen Logic ---
function fitToScreen() {
    const page = projectStore.activePage;
    if (!page || !viewportRef.value) return;

    const viewportWidth = viewportRef.value.clientWidth;
    const viewportHeight = viewportRef.value.clientHeight;
    
    const padding = 50; // pixels
    const scaleX = (viewportWidth - padding * 2) / page.width;
    const scaleY = (viewportHeight - padding * 2) / page.height;
    const newZoom = Math.min(scaleX, scaleY, 1); // Do not zoom in more than 100%

    // Center the artboard
    const newX = (viewportWidth / newZoom - page.width) / 2;
    const newY = (viewportHeight / newZoom - page.height) / 2;

    zoom.value = newZoom;
    pan.x = newX;
    pan.y = newY;
}

onMounted(() => {
    fitToScreen();
});

// Re-fit when the active page changes
watch(() => projectStore.activePageId, () => {
    // Use nextTick to ensure the new artboard dimensions are in the DOM if they changed
    setTimeout(fitToScreen, 50);
});

</script>

<template>
  <main 
    ref="viewportRef"
    class="canvas-area"
    @wheel="handleWheel"
    @mousedown="handlePan"
  >
    <div class="content-wrapper" :style="contentStyle">
      <Artboard v-if="projectStore.activePage" :zoom="zoom" :pan="pan" />
    </div>
    
    <div v-if="!projectStore.activePage" class="placeholder">
      <p>Select a project and page to begin.</p>
    </div>
  </main>
</template>

<style scoped>
.canvas-area {
  flex-grow: 1;
  background-color: var(--bg-color);
  position: relative;
  overflow: hidden; /* Important: hide overflow for panning */
  cursor: default;
}
.content-wrapper {
    width: 100%;
    height: 100%;
}
.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
