<template>
  <div 
    v-if="isVisible" 
    :class="['base-dialog', { 'modal-dialog': isModal, 'non-modal-dialog': !isModal }]"
    @click.self="handleOverlayClick"
  >
    <div 
      ref="dialogContainer"
      :class="['dialog-container', sizeClass]"
      :style="dialogStyle"
      @mousedown="handleMouseDown"
    >
      <!-- Header -->
      <div 
        class="dialog-header" 
        :class="{ draggable: isDraggable }"
        @mousedown="startDrag"
      >
        <h3 class="dialog-title">{{ title }}</h3>
        <slot name="header-actions"></slot>
        <div class="dialog-controls" @mousedown.stop>
          <button 
            v-if="minimizable" 
            type="button"
            @click="$emit('minimize')" 
            class="control-btn minimize-btn" 
            :title="$t('baseDialog.minimize')"
          >
            −
          </button>
          <button 
            v-if="closable" 
            type="button"
            @click="handleClose" 
            class="control-btn close-btn" 
            :title="$t('baseDialog.close')"
          >
            ×
          </button>
        </div>
      </div>

      <!-- Content -->
      <div class="dialog-body">
        <slot></slot>
      </div>

      <!-- Footer (optional) -->
      <div v-if="$slots.footer" class="dialog-footer">
        <slot name="footer"></slot>
      </div>

      <div
        v-if="!isModal && resizable"
        class="dialog-resize-handle"
        :title="$t('baseDialog.resize')"
        @mousedown.stop="startResize"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'BaseDialog',
  props: {
    // Sichtbarkeit
    modelValue: {
      type: Boolean,
      default: false
    },
    
    // Dialog-Typ
    isModal: {
      type: Boolean,
      default: true
    },
    
    // Titel
    title: {
      type: String,
      required: true
    },
    
    // Größe: 'small', 'medium', 'large', 'fullscreen'
    size: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large', 'fullscreen'].includes(value)
    },

    width: {
      type: [String, Number],
      default: null
    },

    maxWidth: {
      type: [String, Number],
      default: null
    },
    
    // Position für nicht-modale Dialoge
    position: {
      type: Object,
      default: () => ({ x: 100, y: 100 })
    },
    
    // z-Index
    zIndex: {
      type: Number,
      default: 1000
    },
    
    // Funktionalität
    closable: {
      type: Boolean,
      default: true
    },
    
    minimizable: {
      type: Boolean,
      default: false
    },
    
    draggable: {
      type: Boolean,
      default: true
    },

    /** Nicht-modale Dialoge: Ecke zum Vergrößern/Verkleinern */
    resizable: {
      type: Boolean,
      default: true
    },
    
    // Schließen bei Overlay-Klick (nur bei modalen Dialogen)
    closeOnOverlay: {
      type: Boolean,
      default: true
    }
  },
  
  data() {
    return {
      localPosition: { ...this.position },
      isDragging: false,
      dragStartX: 0,
      dragStartY: 0,
      localWidth: null,
      localHeight: null,
      isResizing: false,
      resizeStart: null,
    };
  },
  
  computed: {
    isVisible() {
      return this.modelValue;
    },
    
    sizeClass() {
      return `dialog-${this.size}`;
    },
    
    dialogStyle() {
      const style = {
        zIndex: this.zIndex
      };

      if (this.width !== null) {
        style.width = typeof this.width === 'number' ? `${this.width}px` : this.width;
      }

      if (this.maxWidth !== null) {
        style.maxWidth = typeof this.maxWidth === 'number' ? `${this.maxWidth}px` : this.maxWidth;
      }
      
      if (!this.isModal) {
        style.left = `${this.localPosition.x}px`;
        style.top = `${this.localPosition.y}px`;
        if (this.localWidth != null) {
          style.width = `${this.localWidth}px`;
          style.maxWidth = 'none';
        }
        if (this.localHeight != null) {
          style.height = `${this.localHeight}px`;
          style.maxHeight = 'none';
        }
      }
      
      return style;
    },
    
    isDraggable() {
      return this.draggable && !this.isModal;
    }
  },
  
  methods: {
    handleClose() {
      this.$emit('update:modelValue', false);
      this.$emit('close');
    },
    
    handleOverlayClick() {
      if (this.isModal && this.closeOnOverlay) {
        this.handleClose();
      }
    },
    
    handleMouseDown() {
      if (!this.isModal) {
        this.$emit('focus');
      }
    },
    
    startDrag(event) {
      if (!this.isDraggable) return;
      if (event.button !== 0) return;
      if (event.target.closest('button, a, input, select, textarea, [contenteditable="true"]')) {
        return;
      }

      this.isDragging = true;
      this.dragStartX = event.clientX - this.localPosition.x;
      this.dragStartY = event.clientY - this.localPosition.y;
      
      document.addEventListener('mousemove', this.onDrag);
      document.addEventListener('mouseup', this.stopDrag);
      
      event.preventDefault();
    },
    
    onDrag(event) {
      if (!this.isDragging) return;

      let nx = event.clientX - this.dragStartX;
      let ny = event.clientY - this.dragStartY;
      const el = this.$refs.dialogContainer;
      if (el && typeof window !== 'undefined') {
        const w = el.offsetWidth;
        const h = el.offsetHeight;
        const pad = 8;
        nx = Math.min(Math.max(pad, nx), window.innerWidth - w - pad);
        ny = Math.min(Math.max(pad, ny), window.innerHeight - h - pad);
      }

      this.localPosition.x = nx;
      this.localPosition.y = ny;
      
      this.$emit('update:position', { ...this.localPosition });
    },
    
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
    },

    startResize(event) {
      if (this.isModal || !this.resizable) return;
      if (event.button !== 0) return;
      const el = this.$refs.dialogContainer;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      this.isResizing = true;
      this.resizeStart = {
        mouseX: event.clientX,
        mouseY: event.clientY,
        width: rect.width,
        height: rect.height,
      };
      document.addEventListener('mousemove', this.onResizeMove);
      document.addEventListener('mouseup', this.stopResize);
      event.preventDefault();
    },

    onResizeMove(event) {
      if (!this.isResizing || !this.resizeStart || typeof window === 'undefined') return;
      const dx = event.clientX - this.resizeStart.mouseX;
      const dy = event.clientY - this.resizeStart.mouseY;
      let w = this.resizeStart.width + dx;
      let h = this.resizeStart.height + dy;
      const minW = 260;
      const minH = 160;
      const maxW = window.innerWidth - this.localPosition.x - 8;
      const maxH = window.innerHeight - this.localPosition.y - 8;
      w = Math.min(Math.max(minW, w), maxW);
      h = Math.min(Math.max(minH, h), maxH);
      this.localWidth = w;
      this.localHeight = h;
    },

    stopResize() {
      this.isResizing = false;
      this.resizeStart = null;
      document.removeEventListener('mousemove', this.onResizeMove);
      document.removeEventListener('mouseup', this.stopResize);
    },
  },
  
  watch: {
    position: {
      handler(newPos) {
        this.localPosition = { ...newPos };
      },
      deep: true
    }
  },
  
  beforeUnmount() {
    if (this.isDragging) {
      this.stopDrag();
    }
    if (this.isResizing) {
      this.stopResize();
    }
  }
};
</script>

<style scoped>
/* Base Dialog Wrapper */
.base-dialog {
  position: fixed;
  pointer-events: none;
}

/* Modal Dialog (mit Overlay) */
.modal-dialog {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  pointer-events: auto;
}

/* Non-Modal Dialog (ohne Overlay) */
.non-modal-dialog {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  pointer-events: none;
}

/* Dialog Container */
.dialog-container {
  position: relative;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  pointer-events: auto;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-height: 90vh;
}

/* Modal Dialog Container */
.modal-dialog .dialog-container {
  position: relative;
}

/* Non-Modal Dialog Container */
.non-modal-dialog .dialog-container {
  position: absolute;
  min-width: 260px;
  min-height: 160px;
}

/* Größen */
.dialog-small {
  width: 400px;
  max-width: 90vw;
}

.dialog-medium {
  width: 600px;
  max-width: 90vw;
}

.dialog-large {
  width: 900px;
  max-width: 90vw;
}

.dialog-fullscreen {
  width: 90vw;
  height: 90vh;
  max-width: none;
  max-height: 90vh;
}

/* Header */
.dialog-header {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: white;
  padding: 4px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
  flex-shrink: 0;
}

.dialog-header.draggable {
  cursor: grab;
}

.dialog-header.draggable:active {
  cursor: grabbing;
}

.dialog-resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 16px;
  height: 16px;
  cursor: nwse-resize;
  background: linear-gradient(
    135deg,
    transparent 50%,
    rgba(0, 0, 0, 0.12) 50%
  );
  border-bottom-right-radius: 8px;
}

.dialog-resize-handle:hover {
  background: linear-gradient(
    135deg,
    transparent 45%,
    rgba(47, 122, 95, 0.35) 45%
  );
}

.dialog-title {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  flex: 1;
  color: var(--text-on-primary);
}

/* Controls */
.dialog-controls {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

.control-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.2s ease;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.close-btn:hover {
  background: rgba(200, 74, 56, 0.72);
}

/* Body */
.dialog-body {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

/* Footer */
.dialog-footer {
  padding: 4px 16px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

/* Responsive Design */
@media (max-width: 768px) {
  .dialog-small,
  .dialog-medium,
  .dialog-large {
    width: 95vw;
    max-width: 95vw;
  }
  
  .dialog-fullscreen {
    width: 95vw;
    height: 95vh;
  }
}
</style>
