<template>
  <div class="dialog-manager">
    <!-- Minimierte Dialoge in der Fußzeile -->
    <div class="minimized-dialogs">
      <button
        v-for="dialog in minimizedDialogs"
        :key="dialog.id"
        @click="restoreDialog(dialog.id)"
        class="minimized-dialog-button"
        :title="dialog.title"
      >
        {{ dialog.title }}
      </button>
      <div v-if="minimizedDialogs.length === 0" class="no-minimized-dialogs">
        {{ $t('dialogManager.noMinimizedDialogs') }}
      </div>
    </div>

    <!-- Aktive Dialoge -->
    <div
      v-for="dialog in activeDialogs"
      :key="dialog.id"
      class="dialog-window"
      :style="dialogWindowStyle(dialog)"
      @mousedown="bringToFront(dialog.id)"
    >
      <div class="dialog-header" @mousedown="startDrag(dialog.id, $event)">
        <h3 class="dialog-title">{{ dialog.title }}</h3>
        <div class="dialog-header-actions">
          <component 
            v-if="dialog.headerActions" 
            :is="getDialogComponent(dialog.headerActions.component)" 
            v-bind="dialog.headerActions.props"
            :dialog-id="dialog.id"
            @action="handleHeaderAction"
          />
        </div>
        <div class="dialog-controls" @mousedown.stop>
          <button type="button" @click="minimizeDialog(dialog.id)" class="control-btn minimize-btn" :title="$t('dialogManager.minimize')">−</button>
          <button type="button" @click="closeDialog(dialog.id)" class="control-btn close-btn" :title="$t('dialogManager.close')">×</button>
        </div>
      </div>
      <div class="dialog-content">
        <component :is="getDialogComponent(dialog.component)" v-bind="dialog.props" @close="() => closeDialog(dialog.id)" />
      </div>
      <div
        class="dialog-resize-handle"
        :title="$t('baseDialog.resize')"
        @mousedown.stop="startResize(dialog.id, $event)"
      />
    </div>
  </div>
</template>

<script>
import { defineAsyncComponent } from 'vue';
import { mapGetters, mapActions } from 'vuex';
import MatchReportDialog from './MatchReportDialog.vue';
import MatchReportApiDialog from './MatchReportApiDialog.vue';
import MatchReportHeaderActions from './MatchReportHeaderActions.vue';

const MyTischtennisAccount = defineAsyncComponent(() => import('../views/MyTischtennisAccount.vue'));
const ClickTtAccount = defineAsyncComponent(() => import('../views/ClickTtAccount.vue'));
const PermissionsView = defineAsyncComponent(() => import('../views/PermissionsView.vue'));
const MemberTransferSettingsView = defineAsyncComponent(() => import('../views/MemberTransferSettingsView.vue'));
const LogsView = defineAsyncComponent(() => import('../views/LogsView.vue'));
const ClickTtView = defineAsyncComponent(() => import('../views/ClickTtView.vue'));
const PersonalSettings = defineAsyncComponent(() => import('../views/PersonalSettings.vue'));
const InternalTournamentStats = defineAsyncComponent(() =>
  import('./tournament/InternalTournamentStats.vue'),
);

const MIN_DIALOG_W = 280;
const MIN_DIALOG_H = 200;

export default {
  components: {
    MatchReportDialog,
    MatchReportApiDialog,
    MatchReportHeaderActions,
    MyTischtennisAccount,
    ClickTtAccount,
    PermissionsView,
    MemberTransferSettingsView,
    LogsView,
    ClickTtView,
    PersonalSettings,
    InternalTournamentStats,
  },
  name: 'DialogManager',
  data() {
    return {
      dragSession: null,
      resizeSession: null,
    };
  },
  computed: {
    ...mapGetters(['dialogs', 'minimizedDialogs', 'activeDialogs'])
  },
  methods: {
    ...mapActions(['closeDialog', 'minimizeDialog', 'restoreDialog', 'bringDialogToFront', 'updateDialogBounds']),

    dialogWindowStyle(dialog) {
      const s = {
        left: `${dialog.position.x}px`,
        top: `${dialog.position.y}px`,
        zIndex: dialog.zIndex,
      };
      if (dialog.width != null && Number.isFinite(Number(dialog.width))) {
        s.width = `${Number(dialog.width)}px`;
      }
      if (dialog.height != null && Number.isFinite(Number(dialog.height))) {
        s.height = `${Number(dialog.height)}px`;
      }
      return s;
    },

    approxDialogWidth(dialog) {
      if (dialog.width != null && Number.isFinite(Number(dialog.width))) return Number(dialog.width);
      return Math.round(window.innerWidth * 0.9);
    },

    approxDialogHeight(dialog) {
      if (dialog.height != null && Number.isFinite(Number(dialog.height))) return Number(dialog.height);
      return Math.round(window.innerHeight * 0.9);
    },
    
    getDialogComponent(componentName) {
      const components = {
        'MatchReportDialog': MatchReportDialog,
        'MatchReportApiDialog': MatchReportApiDialog,
        'MatchReportHeaderActions': MatchReportHeaderActions,
        'MyTischtennisAccount': MyTischtennisAccount,
        'ClickTtAccount': ClickTtAccount,
        'PermissionsView': PermissionsView,
        'MemberTransferSettingsView': MemberTransferSettingsView,
        'LogsView': LogsView,
        'ClickTtView': ClickTtView,
        'PersonalSettings': PersonalSettings,
        InternalTournamentStats,
      };
      const component = components[componentName] || null;
      return component;
    },
    
    bringToFront(dialogId) {
      this.bringDialogToFront(dialogId);
    },
    
    startDrag(dialogId, event) {
      if (event.button !== 0) return;
      if (event.target.closest('button, a, input, select, textarea, [contenteditable="true"]')) {
        return;
      }
      const dialog = this.dialogs.find((d) => d.id === dialogId);
      if (!dialog) return;
      this.bringDialogToFront(dialogId);
      this.dragSession = {
        dialogId,
        startX: event.clientX,
        startY: event.clientY,
        origX: dialog.position.x,
        origY: dialog.position.y,
      };
      document.addEventListener('mousemove', this.onDragMove);
      document.addEventListener('mouseup', this.onDragEnd);
      event.preventDefault();
    },

    onDragMove(event) {
      if (!this.dragSession) return;
      const { dialogId, startX, startY, origX, origY } = this.dragSession;
      const dialog = this.dialogs.find((d) => d.id === dialogId);
      if (!dialog) return;
      let nx = origX + event.clientX - startX;
      let ny = origY + event.clientY - startY;
      const w = this.approxDialogWidth(dialog);
      const h = this.approxDialogHeight(dialog);
      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.updateDialogBounds({ dialogId, position: { x: nx, y: ny } });
    },

    onDragEnd() {
      this.dragSession = null;
      document.removeEventListener('mousemove', this.onDragMove);
      document.removeEventListener('mouseup', this.onDragEnd);
    },

    startResize(dialogId, event) {
      if (event.button !== 0) return;
      this.bringDialogToFront(dialogId);
      const dialog = this.dialogs.find((d) => d.id === dialogId);
      if (!dialog) return;
      const el = event.currentTarget.closest('.dialog-window');
      if (!el) return;
      const rect = el.getBoundingClientRect();
      this.resizeSession = {
        dialogId,
        startX: event.clientX,
        startY: event.clientY,
        origW: rect.width,
        origH: rect.height,
      };
      document.addEventListener('mousemove', this.onResizeMove);
      document.addEventListener('mouseup', this.onResizeEnd);
      event.preventDefault();
    },

    onResizeMove(event) {
      if (!this.resizeSession) return;
      const { dialogId, startX, startY, origW, origH } = this.resizeSession;
      const dialog = this.dialogs.find((d) => d.id === dialogId);
      if (!dialog) return;
      let w = origW + event.clientX - startX;
      let h = origH + event.clientY - startY;
      const maxW = window.innerWidth - dialog.position.x - 8;
      const maxH = window.innerHeight - dialog.position.y - 8;
      w = Math.min(Math.max(MIN_DIALOG_W, w), maxW);
      h = Math.min(Math.max(MIN_DIALOG_H, h), maxH);
      this.updateDialogBounds({ dialogId, width: w, height: h });
      let nx = dialog.position.x;
      let ny = dialog.position.y;
      if (nx + w > window.innerWidth - 8) nx = Math.max(8, window.innerWidth - w - 8);
      if (ny + h > window.innerHeight - 8) ny = Math.max(8, window.innerHeight - h - 8);
      if (nx !== dialog.position.x || ny !== dialog.position.y) {
        this.updateDialogBounds({ dialogId, position: { x: nx, y: ny } });
      }
    },

    onResizeEnd() {
      this.resizeSession = null;
      document.removeEventListener('mousemove', this.onResizeMove);
      document.removeEventListener('mouseup', this.onResizeEnd);
    },
    
    handleHeaderAction(action) {
      // Finde den Dialog und die entsprechende Komponente
      const dialog = this.dialogs.find(d => d.id === action.dialogId);
      if (!dialog) return;
      
      // Behandle die verschiedenen Action-Types
      if (action.type === 'insertPin') {
        // PIN via postMessage an das zuletzt geöffnete MatchReport-iframe senden
        this.insertPinIntoIframe(action.match);
      }
    },
    
    insertPinIntoIframe(match) {
      console.log('🔍 PIN-Einfügen gestartet (postMessage)');
      const iframes = document.querySelectorAll('iframe');
      if (iframes.length === 0) {
        console.log('❌ Kein iframe gefunden');
        return;
      }
      const iframe = iframes[iframes.length - 1];
      const message = {
        action: 'fillPin',
        pin: match.homePin || match.guestPin || '',
        timestamp: Date.now(),
        source: 'trainingstagebuch'
      };
      try {
        iframe.contentWindow.postMessage(message, 'http://localhost:3000');
        console.log('📤 PostMessage an http://localhost:3000 gesendet');
      } catch (e) {
        console.log('PostMessage Fehler (nicht kritisch):', e.message);
        // Fallback: Versuche mit anderen Origins
        const origins = ['https://ttde-apps.liga.nu', 'https://liga.nu', '*'];
        origins.forEach(origin => {
          try {
            iframe.contentWindow.postMessage(message, origin);
          } catch (e2) {
            // Ignoriere fehlgeschlagene PostMessage-Versuche
          }
        });
      }
    },
    
    handlePostMessage(event) {
      console.log('📨 PostMessage empfangen:', event);
      console.log('- Origin:', event.origin);
      console.log('- Data:', event.data);
      
      // Nur Nachrichten von unserem Proxy oder nuscore verarbeiten
      const allowedOrigins = ['http://localhost:3000', 'https://ttde-apps.liga.nu', 'https://liga.nu'];
      if (!allowedOrigins.includes(event.origin)) {
        console.log('🚫 Nachricht von unbekannter Origin ignoriert');
        return;
      }
      
      if (!event.data || typeof event.data !== 'object') {
        return;
      }
      
      // Weitere Aktionen bei Bedarf implementieren
    }
  },
  
  mounted() {
    // Event-Listener für PostMessage-Antworten
    window.addEventListener('message', this.handlePostMessage);
  },
  
  beforeUnmount() {
    window.removeEventListener('message', this.handlePostMessage);
    if (this.dragSession) this.onDragEnd();
    if (this.resizeSession) this.onResizeEnd();
  }
};
</script>

<style scoped>
.dialog-manager {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1000;
}

.dialog-window {
  position: absolute;
  box-sizing: border-box;
  min-width: 280px;
  min-height: 200px;
  width: min(90vw, calc(100vw - 32px));
  height: min(90vh, calc(100vh - 32px));
  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;
}

.dialog-header {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: grab;
  user-select: none;
  flex-shrink: 0;
}

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

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

.dialog-header-actions {
  display: flex;
  align-items: center;
}

.dialog-controls {
  display: flex;
  gap: 8px;
}

.control-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.2);
  color: var(--text-on-primary);
  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);
}

.dialog-content {
  flex: 1;
  padding: 0;
  overflow-y: auto;
  min-height: 0;
}

.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.1) 50%
  );
  border-bottom-right-radius: 8px;
  z-index: 2;
}

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

.minimized-dialogs {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, rgba(24, 70, 54, 0.96), rgba(47, 122, 95, 0.94));
  padding: 4px 16px;
  display: flex;
  gap: 8px;
  z-index: 2000;
  pointer-events: auto;
  min-height: 24px;
  align-items: center;
}

.no-minimized-dialogs {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.875rem;
  font-style: italic;
}

.minimized-dialog-button {
  background: var(--primary-color);
  color: var(--text-on-primary);
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: background-color 0.2s ease;
  white-space: nowrap;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.minimized-dialog-button:hover {
  background: var(--primary-hover);
}

/* Responsive Design */
@media (max-width: 768px) {
  .dialog-window {
    max-width: calc(100vw - 16px);
    max-height: calc(100vh - 16px);
  }
  
  .minimized-dialogs {
    flex-wrap: wrap;
  }
  
  .minimized-dialog-button {
    max-width: 150px;
  }
}
</style>
