<template>
  <div class="clicktt-view" :class="{ 'embedded-dialog-view': embedded }">
    <div v-if="!embedded" class="header">
      <h1>{{ $t('navigation.clickTtBrowser') }}</h1>
      <p class="subtitle">
        Lade und bediene click-TT-Seiten (Ligenübersicht, Vereinsinfo, Spielplan) im iframe.
        Alle Aufrufe werden geloggt.
      </p>
    </div>

    <div class="controls-section">
      <div class="form-row">
        <div class="form-group">
          <label>Seitentyp</label>
          <select v-model="pageType" class="form-select">
            <option value="leaguePage">Ligenübersicht (leaguePage)</option>
            <option value="clubInfo">Vereinsinfo (clubInfoDisplay)</option>
            <option value="regionMeetings">Regionsspielplan (regionMeetingFilter)</option>
            <option value="url">Direkte URL</option>
            <option value="preset:httv-home">HTTV Einstieg: https://httv.de</option>
            <option value="preset:ttde-login">TTDE Login: ttde-id.liga.nu/oauth2/authz/ttde...</option>
          </select>
        </div>

        <div class="form-group" v-if="pageType === 'leaguePage' || pageType === 'clubInfo' || pageType === 'regionMeetings'">
          <label>Verband</label>
          <select v-model="association" class="form-select">
            <option value="HeTTV">HeTTV (Hessen)</option>
            <option value="RTTV">RTTV</option>
            <option value="WTTV">WTTV</option>
            <option value="TTVNw">TTVNw</option>
          </select>
        </div>

        <div class="form-group" v-if="pageType === 'leaguePage' || pageType === 'regionMeetings'">
          <label>Championship / Saison</label>
          <input
            v-model="championship"
            type="text"
            class="form-input"
            placeholder="z.B. HTTV 25/26, K43 25/26"
          />
        </div>

        <div class="form-group" v-if="pageType === 'clubInfo'">
          <label>Vereins-ID</label>
          <input
            v-model="clubId"
            type="text"
            class="form-input"
            placeholder="z.B. 1060"
          />
        </div>

        <div class="form-group" v-if="pageType === 'url'">
          <label>URL</label>
          <input
            v-model="directUrl"
            type="text"
            class="form-input form-input-wide"
            placeholder="https://httv.click-tt.de/..."
          />
        </div>

        <div class="form-group form-group-actions">
          <button @click="loadPage" class="btn-primary" :disabled="!canLoad">
            Laden
          </button>
          <button @click="clearIframe" class="btn-secondary">Leeren</button>
        </div>
      </div>
    </div>

    <div class="iframe-container" v-if="iframeSrc">
      <iframe
        id="clicktt-iframe"
        ref="clickttIframe"
        :src="iframeSrc"
        class="clicktt-iframe"
        title="click-TT Seite"
        sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox"
      />
    </div>
    <div v-else class="placeholder">
      <p>Wähle einen Seitentyp, fülle die Parameter und klicke auf „Laden“, um die Seite anzuzeigen.</p>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';

const backendBaseUrl = import.meta.env.VITE_BACKEND || 'http://localhost:3005';
const presetUrls = {
  'preset:httv-home': 'https://httv.de',
  'preset:ttde-login': 'https://ttde-id.liga.nu/oauth2/authz/ttde?scope=nuLiga&response_type=code&redirect_uri=https%3A%2F%2Fhttv.click-tt.de%2Fcgi-bin%2FWebObjects%2FnuLigaTTDE.woa%2Fwa%2FoAuthLogin&state=nonce%3DVF6WbXUOvTjpsGq9zoZ6oxTH7625JEGH&client_id=XtVpGjXKAhz3BZuu',
};

export default {
  name: 'ClickTtView',
  props: {
    embedded: {
      type: Boolean,
      default: false
    }
  },
  setup() {
    const pageType = ref('leaguePage');
    const association = ref('HeTTV');
    const championship = ref('HTTV 25/26');
    const clubId = ref('');
    const directUrl = ref('');
    const iframeSrc = ref('');
    const sessionId = ref('');
    const clickttIframe = ref(null);

    const canLoad = computed(() => {
      if (pageType.value === 'url') {
        return directUrl.value.trim().length > 0;
      }
      if (pageType.value.startsWith('preset:')) {
        return true;
      }
      if (pageType.value === 'clubInfo') {
        return clubId.value.trim().length > 0;
      }
      return true;
    });

    function buildProxyUrl() {
      const base = `${backendBaseUrl}/api/clicktt/proxy`;
      const params = new URLSearchParams();

      if (pageType.value === 'url') {
        params.set('url', directUrl.value.trim());
      } else if (pageType.value.startsWith('preset:')) {
        params.set('url', presetUrls[pageType.value]);
      } else {
        params.set('type', pageType.value);
        params.set('association', association.value);
        if (pageType.value !== 'clubInfo') {
          params.set('championship', championship.value);
        }
        if (pageType.value === 'clubInfo') {
          params.set('clubId', clubId.value.trim());
        }
      }
      if (sessionId.value) params.set('sid', sessionId.value);
      return `${base}?${params.toString()}`;
    }

    function loadPage() {
      if (!canLoad.value) return;
      sessionId.value = crypto.randomUUID?.() || `s${Date.now()}-${Math.random().toString(36).slice(2)}`;
      iframeSrc.value = buildProxyUrl();
    }

    function clearIframe() {
      iframeSrc.value = '';
    }

    return {
      pageType,
      association,
      championship,
      clubId,
      directUrl,
      iframeSrc,
      clickttIframe,
      canLoad,
      loadPage,
      clearIframe,
    };
  },
};
</script>

<style scoped>
.clicktt-view {
  padding: 1.5rem;
  max-width: 1400px;
  margin: 0 auto;
}
.clicktt-view.embedded-dialog-view {
  padding: 0;
  max-width: none;
}

.header {
  margin-bottom: 1.5rem;
}

.header h1 {
  margin: 0 0 0.5rem 0;
  color: var(--text-color, #333);
  font-size: 1.5rem;
}

.subtitle {
  color: var(--text-secondary, #666);
  margin: 0;
  font-size: 0.95em;
}

.controls-section {
  background: var(--background-light, #f8f9fa);
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  align-items: flex-end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.form-group label {
  font-size: 0.85em;
  font-weight: 500;
  color: var(--text-color, #333);
}

.form-select,
.form-input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9em;
  min-width: 140px;
}

.form-input-wide {
  min-width: 320px;
}

.form-group-actions {
  flex-direction: row;
  align-items: flex-end;
  gap: 0.5rem;
}

.btn-primary {
  background: var(--primary-color, #2563eb);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.btn-primary:hover:not(:disabled) {
  background: var(--primary-hover, #1d4ed8);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background: #6b7280;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.btn-secondary:hover {
  background: #4b5563;
}

.iframe-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  min-height: 500px;
  background: #fff;
}

.clicktt-iframe {
  width: 100%;
  height: 70vh;
  min-height: 500px;
  border: none;
  display: block;
}

.placeholder {
  padding: 3rem;
  text-align: center;
  color: var(--text-secondary, #666);
  background: var(--background-light, #f8f9fa);
  border-radius: 8px;
  border: 1px dashed #ccc;
}

.placeholder p {
  margin: 0;
}
</style>
