<template>
  <div class="nuscore-analyzer">
    <div class="analyzer-header">
      <h3>{{ $t('nuscoreAnalyzer.title') }}</h3>
      <p>{{ $t('nuscoreAnalyzer.description') }}</p>
    </div>
    
    <div class="analyzer-controls">
      <button @click="analyzeNuscore" :disabled="isAnalyzing" class="analyze-btn">
        {{ isAnalyzing ? $t('nuscoreAnalyzer.analyzing') : $t('nuscoreAnalyzer.analyze') }}
      </button>
      
      <button @click="downloadResources" :disabled="!resources.length || isDownloading" class="download-btn">
        {{ isDownloading ? $t('nuscoreAnalyzer.downloading') : `⬇️ ${resources.length} ${$t('nuscoreAnalyzer.downloadResources')}` }}
      </button>
      
      <button @click="createLocalCopy" :disabled="!hasDownloadedResources || isCreating" class="create-btn">
        {{ isCreating ? $t('nuscoreAnalyzer.creating') : $t('nuscoreAnalyzer.createLocalCopy') }}
      </button>
    </div>
    
    <div class="analyzer-results" v-if="resources.length > 0">
      <h4>{{ $t('nuscoreAnalyzer.foundResources') }}</h4>
      <div class="resource-list">
        <div 
          v-for="resource in resources" 
          :key="resource.url"
          class="resource-item"
          :class="{ 'downloaded': resource.downloaded }"
        >
          <span class="resource-type">{{ resource.type }}</span>
          <span class="resource-url">{{ resource.url }}</span>
          <span class="resource-size">{{ formatSize(resource.size) }}</span>
          <span v-if="resource.downloaded" class="status">✅</span>
        </div>
      </div>
    </div>
    
    <div class="analyzer-log" v-if="logs.length > 0">
      <h4>{{ $t('nuscoreAnalyzer.log') }}</h4>
      <div class="log-content">
        <div v-for="(log, index) in logs" :key="index" class="log-entry">
          {{ log }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { generateSimpleNuscoreHTML } from '../utils/simpleNuscoreHTMLGenerator.js';

export default {
  name: 'NuscoreAnalyzer',
  data() {
    return {
      isAnalyzing: false,
      isDownloading: false,
      isCreating: false,
      resources: [],
      downloadedResources: [],
      logs: []
    };
  },
  computed: {
    hasDownloadedResources() {
      return this.resources.some(resource => resource.downloaded) || this.downloadedResources.length > 0;
    }
  },
  methods: {
    async analyzeNuscore() {
      this.isAnalyzing = true;
      this.logs = [];
      this.resources = [];
      
      this.addLog('🔍 ' + this.$t('nuscoreAnalyzer.startAnalysis'));
      
      try {
        // Öffne nuscore in einem versteckten iframe
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = 'https://ttde-apps.liga.nu/nuliga/nuscore-tt/meetings-list';
        document.body.appendChild(iframe);
        
        // Warte auf das Laden
        await new Promise((resolve) => {
          iframe.onload = resolve;
          setTimeout(resolve, 5000); // Timeout nach 5 Sekunden
        });
        
        this.addLog('✅ ' + this.$t('nuscoreAnalyzer.pageLoaded'));
        
        // Analysiere die Seite
        await this.analyzePage(iframe);
        
        // Entferne das iframe
        document.body.removeChild(iframe);
        
        this.addLog('✅ ' + this.$t('nuscoreAnalyzer.analysisComplete', { count: this.resources.length }));
        
      } catch (error) {
        this.addLog(`❌ Fehler bei der Analyse: ${error.message}`);
      } finally {
        this.isAnalyzing = false;
      }
    },
    
    async analyzePage(iframe) {
      try {
        const doc = iframe.contentDocument || iframe.contentWindow.document;
        
        // Analysiere Script-Tags
        const scripts = doc.querySelectorAll('script[src]');
        this.addLog(`📜 ${scripts.length} Script-Tags gefunden`);
        
        scripts.forEach(script => {
          this.resources.push({
            type: 'script',
            url: script.src,
            size: 0,
            downloaded: false
          });
        });
        
        // Analysiere Link-Tags (CSS)
        const stylesheets = doc.querySelectorAll('link[rel="stylesheet"][href]');
        this.addLog(`🎨 ${stylesheets.length} Stylesheets gefunden`);
        
        stylesheets.forEach(link => {
          this.resources.push({
            type: 'stylesheet',
            url: link.href,
            size: 0,
            downloaded: false
          });
        });
        
        // Analysiere andere Ressourcen
        const images = doc.querySelectorAll('img[src]');
        this.addLog(`🖼️ ${images.length} Bilder gefunden`);
        
        images.forEach(img => {
          this.resources.push({
            type: 'image',
            url: img.src,
            size: 0,
            downloaded: false
          });
        });
        
      } catch (error) {
        this.addLog(`⚠️ Cross-Origin-Zugriff blockiert: ${error.message}`);
        
        // Fallback: Analysiere die ursprüngliche URL
        await this.analyzeUrlDirectly();
      }
    },
    
    async analyzeUrlDirectly() {
      this.addLog('🔄 Fallback: Bekannte nuscore-Ressourcen verwenden');
      
      try {
        // Bekannte nuscore-Ressourcen basierend auf der URL-Struktur
        const baseUrl = 'https://ttde-apps.liga.nu';
        
        // Typische nuscore-Ressourcen
        const knownResources = [
          // JavaScript-Bundles (typische Angular/React-Bundles)
          `${baseUrl}/nuliga/nuscore-tt/main.js`,
          `${baseUrl}/nuliga/nuscore-tt/runtime.js`,
          `${baseUrl}/nuliga/nuscore-tt/vendor.js`,
          `${baseUrl}/nuliga/nuscore-tt/polyfills.js`,
          `${baseUrl}/nuliga/nuscore-tt/styles.js`,
          `${baseUrl}/nuliga/nuscore-tt/main.6c3da9dbb4871026b9a1.js`, // Aus den Logs
          
          // CSS-Dateien
          `${baseUrl}/nuliga/nuscore-tt/styles.css`,
          `${baseUrl}/nuliga/nuscore-tt/main.css`,
          
          // Weitere mögliche Ressourcen
          `${baseUrl}/nuliga/nuscore-tt/assets/main.js`,
          `${baseUrl}/nuliga/nuscore-tt/assets/runtime.js`,
          `${baseUrl}/nuliga/nuscore-tt/assets/vendor.js`,
          `${baseUrl}/nuliga/nuscore-tt/assets/styles.css`,
          
          // Angular-spezifische Ressourcen
          `${baseUrl}/nuliga/nuscore-tt/angular.js`,
          `${baseUrl}/nuliga/nuscore-tt/angular.min.js`,
          
          // Bootstrap/CSS-Frameworks
          `${baseUrl}/nuliga/nuscore-tt/bootstrap.css`,
          `${baseUrl}/nuliga/nuscore-tt/bootstrap.min.css`,
          
          // Fonts
          `${baseUrl}/nuliga/nuscore-tt/fonts/`,
          
          // Bilder/Assets
          `${baseUrl}/nuliga/nuscore-tt/assets/images/`,
          `${baseUrl}/nuliga/nuscore-tt/assets/icons/`
        ];
        
        // Füge bekannte Ressourcen hinzu
        knownResources.forEach(url => {
          this.resources.push({
            type: url.includes('.css') ? 'stylesheet' : 
                  url.includes('.js') ? 'script' : 
                  url.includes('fonts') ? 'font' : 'asset',
            url: url,
            size: 0,
            downloaded: false
          });
        });
        
        this.addLog(`✅ ${this.resources.length} bekannte Ressourcen hinzugefügt`);
        
        // Versuche zusätzlich, Ressourcen aus dem aktuellen iframe zu extrahieren
        await this.extractResourcesFromCurrentPage();
        
      } catch (error) {
        this.addLog(`❌ Bekannte Ressourcen-Analyse fehlgeschlagen: ${error.message}`);
      }
    },
    
    async extractResourcesFromCurrentPage() {
      this.addLog('🔍 Versuche Ressourcen-Extraktion von der aktuellen Seite');
      
      try {
        // Analysiere die aktuelle Seite nach Ressourcen
        const scripts = document.querySelectorAll('script[src]');
        const stylesheets = document.querySelectorAll('link[rel="stylesheet"][href]');
        
        this.addLog(`📜 ${scripts.length} Scripts auf aktueller Seite gefunden`);
        this.addLog(`🎨 ${stylesheets.length} Stylesheets auf aktueller Seite gefunden`);
        
        // Füge gefundene Ressourcen hinzu (falls sie nuscore-relevant sind)
        scripts.forEach(script => {
          if (script.src.includes('nuscore') || script.src.includes('liga.nu')) {
            this.resources.push({
              type: 'script',
              url: script.src,
              size: 0,
              downloaded: false
            });
          }
        });
        
        stylesheets.forEach(link => {
          if (link.href.includes('nuscore') || link.href.includes('liga.nu')) {
            this.resources.push({
              type: 'stylesheet',
              url: link.href,
              size: 0,
              downloaded: false
            });
          }
        });
        
        this.addLog(`✅ ${this.resources.length} nuscore-relevante Ressourcen gefunden`);
        
      } catch (error) {
        this.addLog(`⚠️ Ressourcen-Extraktion fehlgeschlagen: ${error.message}`);
      }
    },
    
    async downloadResources() {
      this.isDownloading = true;
      this.downloadedResources = [];
      
      this.addLog('⬇️ Starte Download der Ressourcen...');
      this.addLog('⚠️ Hinweis: CORS-Beschränkungen können Downloads blockieren');
      
      for (const resource of this.resources) {
        try {
          this.addLog(`⬇️ Lade herunter: ${resource.url}`);
          
          // Versuche verschiedene Download-Methoden
          let blob = null;
          
          // Methode 1: Direkter fetch
          try {
            const response = await fetch(resource.url, { 
              mode: 'cors',
              credentials: 'omit'
            });
            blob = await response.blob();
          } catch (corsError) {
            this.addLog(`⚠️ CORS-Fehler für ${resource.url}, versuche Alternative...`);
            
            // Methode 2: Proxy über iframe
            blob = await this.downloadViaIframe(resource.url);
          }
          
          if (blob && blob.size > 0) {
            resource.downloaded = true;
            resource.size = blob.size;
            resource.blob = blob;
            resource.localUrl = URL.createObjectURL(blob);
            
            this.downloadedResources.push(resource);
            
            this.addLog(`✅ Heruntergeladen: ${this.formatSize(blob.size)}`);
          } else {
            this.addLog(`⚠️ Leere oder ungültige Ressource: ${resource.url}`);
          }
          
        } catch (error) {
          this.addLog(`❌ Download fehlgeschlagen: ${resource.url} - ${error.message}`);
          
          // Fallback: Markiere als "verfügbar aber nicht heruntergeladen"
          resource.available = true;
          resource.downloaded = false;
        }
      }
      
      this.addLog(`✅ Download abgeschlossen: ${this.downloadedResources.length}/${this.resources.length} erfolgreich`);
      this.addLog(`💡 Tipp: Verwenden Sie die lokale Kopie auch mit externen Ressourcen`);
      this.isDownloading = false;
    },
    
    async downloadViaIframe(url) {
      return new Promise((resolve, reject) => {
        try {
          const iframe = document.createElement('iframe');
          iframe.style.display = 'none';
          iframe.src = url;
          document.body.appendChild(iframe);
          
          iframe.onload = () => {
            try {
              const doc = iframe.contentDocument || iframe.contentWindow.document;
              const content = doc.documentElement.outerHTML;
              const blob = new Blob([content], { type: 'text/html' });
              document.body.removeChild(iframe);
              resolve(blob);
            } catch (error) {
              document.body.removeChild(iframe);
              reject(error);
            }
          };
          
          iframe.onerror = () => {
            document.body.removeChild(iframe);
            reject(new Error('Iframe load failed'));
          };
          
          // Timeout nach 10 Sekunden
          setTimeout(() => {
            if (document.body.contains(iframe)) {
              document.body.removeChild(iframe);
              reject(new Error('Download timeout'));
            }
          }, 10000);
          
        } catch (error) {
          reject(error);
        }
      });
    },
    
    async createLocalCopy() {
      this.isCreating = true;
      this.addLog('🏗️ Erstelle lokale Kopie...');

      try {
        // Erstelle eine einfache HTML-Datei, die die ursprüngliche nuscore-Seite in einem iframe lädt
        const html = generateSimpleNuscoreHTML({ homePin: '', guestPin: '', code: '' });

        const blob = new Blob([html], { type: 'text/html' });
        const url = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.href = url;
        link.download = 'nuscore-local.html';
        link.click();

        URL.revokeObjectURL(url);

        this.addLog('✅ Lokale Kopie erstellt (iframe-basiert)');
        this.addLog('💡 Die lokale Kopie lädt die ursprüngliche nuscore-Seite in einem iframe');
        this.addLog('💡 PIN-Einfügung funktioniert über PostMessage');

      } catch (error) {
        this.addLog(`❌ Fehler beim Erstellen der lokalen Kopie: ${error.message}`);
      } finally {
        this.isCreating = false;
      }
    },
    
    addLog(message) {
      const timestamp = new Date().toLocaleTimeString();
      this.logs.push(`[${timestamp}] ${message}`);
    },
    
    formatSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
  }
};
</script>

<style scoped>
.nuscore-analyzer {
  padding: 20px;
  background: var(--background-soft);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  margin: 20px 0;
}

.analyzer-header h3 {
  margin: 0 0 10px 0;
  color: var(--primary-color);
}

.analyzer-controls {
  display: flex;
  gap: 10px;
  margin: 20px 0;
  flex-wrap: wrap;
}

.analyze-btn, .download-btn, .create-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 999px;
  cursor: pointer;
  font-weight: bold;
  transition: transform 0.2s ease, opacity 0.2s ease;
}

.analyze-btn {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
}

.analyze-btn:hover:not(:disabled) {
  transform: translateY(-1px);
}

.download-btn {
  background: var(--surface-color, white);
  color: var(--text-color);
  border: 1px solid var(--border-color);
}

.download-btn:hover:not(:disabled) {
  transform: translateY(-1px);
}

.create-btn {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
}

.create-btn:hover:not(:disabled) {
  opacity: 0.95;
}

.analyze-btn:disabled, .download-btn:disabled, .create-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.resource-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background: white;
}

.resource-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid var(--border-color);
  gap: 10px;
}

.resource-item:last-child {
  border-bottom: none;
}

.resource-item.downloaded {
  background: rgba(46, 125, 50, 0.12);
}

.resource-type {
  font-weight: bold;
  min-width: 80px;
  font-size: 12px;
}

.resource-url {
  flex: 1;
  font-family: monospace;
  font-size: 12px;
  color: var(--text-muted);
}

.resource-size {
  min-width: 60px;
  text-align: right;
  font-size: 12px;
}

.status {
  color: var(--success-color);
  font-weight: bold;
}

.log-content {
  max-height: 200px;
  overflow-y: auto;
  background: #1b232b;
  color: #b9f7c3;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

.log-entry {
  margin-bottom: 2px;
}
</style>
