<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="{
        left: dialog.position.x + 'px',
        top: dialog.position.y + 'px',
        zIndex: dialog.zIndex
      }"
      @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">
          <button @click="minimizeDialog(dialog.id)" class="control-btn minimize-btn" :title="$t('dialogManager.minimize')">−</button>
          <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>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import MatchReportDialog from './MatchReportDialog.vue';
import MatchReportApiDialog from './MatchReportApiDialog.vue';
import MatchReportHeaderActions from './MatchReportHeaderActions.vue';
import MyTischtennisAccount from '../views/MyTischtennisAccount.vue';
import ClickTtAccount from '../views/ClickTtAccount.vue';
import PermissionsView from '../views/PermissionsView.vue';
import MemberTransferSettingsView from '../views/MemberTransferSettingsView.vue';
import LogsView from '../views/LogsView.vue';
import ClickTtView from '../views/ClickTtView.vue';
import PersonalSettings from '../views/PersonalSettings.vue';

export default {
  components: {
    MatchReportDialog,
    MatchReportApiDialog,
    MatchReportHeaderActions,
    MyTischtennisAccount,
    ClickTtAccount,
    PermissionsView,
    MemberTransferSettingsView,
    LogsView,
    ClickTtView,
    PersonalSettings
  },
  name: 'DialogManager',
  computed: {
    ...mapGetters(['dialogs', 'minimizedDialogs', 'activeDialogs'])
  },
  methods: {
    ...mapActions(['closeDialog', 'minimizeDialog', 'restoreDialog', 'bringDialogToFront']),
    
    getDialogComponent(componentName) {
      const components = {
        'MatchReportDialog': MatchReportDialog,
        'MatchReportApiDialog': MatchReportApiDialog,
        'MatchReportHeaderActions': MatchReportHeaderActions,
        'MyTischtennisAccount': MyTischtennisAccount,
        'ClickTtAccount': ClickTtAccount,
        'PermissionsView': PermissionsView,
        'MemberTransferSettingsView': MemberTransferSettingsView,
        'LogsView': LogsView,
        'ClickTtView': ClickTtView,
        'PersonalSettings': PersonalSettings
      };
      const component = components[componentName] || null;
      return component;
    },
    
    bringToFront(dialogId) {
      this.bringDialogToFront(dialogId);
    },
    
    startDrag(dialogId, event) {
      // Drag & Drop deaktiviert, da Dialog jetzt fest positioniert ist
      // Dialog wird immer zentriert angezeigt
      this.bringToFront(dialogId);
    },
    
    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() {
    // Event-Listener entfernen
    window.removeEventListener('message', this.handlePostMessage);
  }
};
</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;
  width: 90vw;
  height: 90vh;
  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;
  left: 5vw !important;
  top: 5vh !important;
}

.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: move;
  user-select: none;
}

.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;
}

.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 {
    width: 95vw;
    height: 95vh;
    left: 2.5vw !important;
    top: 2.5vh !important;
  }
  
  .minimized-dialogs {
    flex-wrap: wrap;
  }
  
  .minimized-dialog-button {
    max-width: 150px;
  }
}
</style>
