<script setup lang="ts">
import { useGalleryStore } from "../stores/gallery";
import { convertFileSrc } from "@tauri-apps/api/core";
import { ref, computed, onMounted, onUnmounted, watch } from "vue";

const store = useGalleryStore();
const isDragging = ref(false);
const dragStart = ref({ x: 0, y: 0 });
const imgRef = ref<HTMLImageElement | null>(null);
const renderHeight = ref(0);

let resizeObserver: ResizeObserver | null = null;

const updateHeight = () => {
    if (imgRef.value) {
        renderHeight.value = imgRef.value.clientHeight;
    }
};

onMounted(() => {
    resizeObserver = new ResizeObserver(() => {
        updateHeight();
    });
});

onUnmounted(() => {
    if (resizeObserver) resizeObserver.disconnect();
});

// Watch for image ref availability
watch(imgRef, (el) => {
    if (el && resizeObserver) {
        resizeObserver.disconnect(); // clear old
        resizeObserver.observe(el);
        // Force update immediately
        // Wait for load? ResizeObserver usually handles layout shifts
    }
});

// Use either manual position (if override is true) or ZCA suggestion
const position = computed(() => {
    if (store.watermarkSettings.manual_override) {
        return store.watermarkSettings.manual_position;
    }
    return store.selectedImage?.zcaSuggestion ? { x: store.selectedImage.zcaSuggestion.x, y: store.selectedImage.zcaSuggestion.y } : { x: 0.5, y: 0.5 };
});

const onMouseDown = (e: MouseEvent) => {
    e.preventDefault();
    isDragging.value = true;
    dragStart.value = { x: e.clientX, y: e.clientY };
};

const onMouseMove = (e: MouseEvent) => {
    if (!isDragging.value || !store.selectedImage) return;
    
    // Calculate delta in percentage relative to the image container
    const container = (e.currentTarget as HTMLElement).closest('.image-container');
    if (!container) return;

    const rect = container.getBoundingClientRect();
    const deltaX = (e.clientX - dragStart.value.x) / rect.width;
    const deltaY = (e.clientY - dragStart.value.y) / rect.height;

    // Update manual position
    let newX = position.value.x + deltaX;
    let newY = position.value.y + deltaY;
    
    // Clamp
    newX = Math.max(0, Math.min(1, newX));
    newY = Math.max(0, Math.min(1, newY));

    // Set store to manual mode immediately
    store.updateWatermarkSettings({
        manual_override: true,
        manual_position: { x: newX, y: newY }
    });

    dragStart.value = { x: e.clientX, y: e.clientY };
};

const onMouseUp = () => {
    isDragging.value = false;
};

const onMouseLeave = () => {
    isDragging.value = false;
};
</script>

<template>
  <div 
    class="w-full h-full flex items-center justify-center bg-black relative p-4 overflow-hidden"
    @mousemove="onMouseMove"
    @mouseup="onMouseUp"
    @mouseleave="onMouseLeave"
  >
    <div 
        v-if="store.selectedImage" 
        class="relative inline-flex justify-center items-center image-container" 
        style="max-width: 100%; max-height: 100%;"
    >
      <img 
        ref="imgRef"
        :src="convertFileSrc(store.selectedImage.path)" 
        class="max-w-full max-h-full w-auto h-auto block shadow-lg select-none pointer-events-none"
        style="max-height: calc(100vh - 10rem);" 
        alt="Hero Image"
        loading="eager"
        decoding="sync"
        fetchpriority="high"
        @load="updateHeight"
        @error="(e) => console.error('Hero Image Load Error:', e)"
      />
      
      <!-- Text Watermark Overlay -->
      <div 
        v-if="store.watermarkSettings.text"
        class="absolute cursor-move select-none whitespace-nowrap font-sans font-medium"
        :style="{
            left: (position.x * 100) + '%',
            top: (position.y * 100) + '%',
            transform: 'translate(-50%, -50%)',
            opacity: store.watermarkSettings.opacity,
            color: store.watermarkSettings.color,
            fontSize: (renderHeight * store.watermarkSettings.scale) + 'px',
            height: '0px', 
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
        }"
        @mousedown="onMouseDown"
      >
        <span> 
            {{ store.watermarkSettings.text }}
        </span>
        
        <!-- Selection Ring when dragging -->
        <div v-if="isDragging" class="absolute -inset-2 border border-blue-500 rounded-sm"></div>
      </div>
    </div>
    <div v-else class="text-gray-500 flex flex-col items-center">
      <p>No image selected</p>
    </div>
  </div>
</template>

<style scoped>
.image-container {
    /* Removed container-type: size to prevent layout collapse */
}

span {
    text-shadow: 0 1px 3px rgba(0,0,0,0.5);
}
</style>
