<template>
  <div class="member-transfer-settings">
    <h2>{{ $t('memberTransfer.title') }}</h2>
    
    <div v-if="loading" class="loading">
      {{ $t('memberTransfer.loadingConfig') }}
    </div>

    <div v-else class="settings-container">
      <div class="settings-card">
        <h3>{{ $t('memberTransfer.transferConfiguration') }}</h3>
        <p class="info-text">
          {{ $t('memberTransfer.configInfo') }}
        </p>

        <div class="form-section">
          <h4>{{ $t('memberTransfer.serverConfiguration') }}</h4>
          
          <div class="form-group">
            <label for="server">{{ $t('memberTransfer.serverBaseUrl') }}: <span class="required">*</span></label>
            <input
              type="text"
              id="server"
              v-model="config.server"
              :placeholder="$t('memberTransfer.serverBaseUrlPlaceholder')"
              class="form-input"
              required
            />
            <span class="hint">{{ $t('memberTransfer.serverBaseUrlHint') }}</span>
          </div>
        </div>

        <div class="form-section">
          <h4>{{ $t('memberTransfer.loginConfiguration') }}</h4>
          
          <div class="form-group">
            <label for="loginEndpoint">{{ $t('memberTransfer.loginEndpointPath') }}:</label>
            <input
              type="text"
              id="loginEndpoint"
              v-model="config.loginEndpoint"
              :placeholder="$t('memberTransfer.loginEndpointPlaceholder')"
              class="form-input"
            />
            <span class="hint">{{ $t('memberTransfer.loginEndpointHint') }}</span>
          </div>

          <div class="form-group">
            <label for="loginFormat">{{ $t('memberTransfer.loginFormat') }}:</label>
            <select id="loginFormat" v-model="config.loginFormat" class="form-select">
              <option value="json">JSON</option>
              <option value="form-data">Form Data</option>
              <option value="x-www-form-urlencoded">URL Encoded</option>
            </select>
          </div>

          <div class="form-group">
            <label>{{ $t('memberTransfer.loginData') }}:</label>
            <div class="credentials-group">
              <div class="credential-row">
                <input
                  type="text"
                  v-model="loginCredentials.username"
                  :placeholder="$t('memberTransfer.usernameEmail')"
                  class="form-input"
                />
                <input
                  type="password"
                  v-model="loginCredentials.password"
                  :placeholder="$t('memberTransfer.password')"
                  class="form-input"
                />
              </div>
              <div class="credential-row">
                <input
                  type="text"
                  v-model="loginCredentials.additionalField1"
                  :placeholder="$t('memberTransfer.additionalFieldExample1')"
                  class="form-input"
                />
                <input
                  type="text"
                  v-model="loginCredentials.additionalField2"
                  :placeholder="$t('memberTransfer.additionalFieldExample2')"
                  class="form-input"
                />
              </div>
            </div>
            <span class="hint">{{ $t('memberTransfer.passwordEncrypted') }}</span>
          </div>
        </div>

        <div class="form-section">
          <h4>{{ $t('memberTransfer.transferConfigurationTitle') }}</h4>

          <div class="form-group">
            <label for="transferEndpoint">{{ $t('memberTransfer.transferEndpointPath') }}: <span class="required">*</span></label>
            <input
              type="text"
              id="transferEndpoint"
              v-model="config.transferEndpoint"
              :placeholder="$t('memberTransfer.transferEndpointPlaceholder')"
              class="form-input"
              required
            />
            <span class="hint">{{ $t('memberTransfer.transferEndpointHint') }}</span>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="transferMethod">{{ $t('memberTransfer.httpMethod') }}:</label>
              <select id="transferMethod" v-model="config.transferMethod" class="form-select">
                <option value="POST">POST</option>
                <option value="PUT">PUT</option>
                <option value="GET">GET</option>
              </select>
            </div>

            <div class="form-group">
              <label for="transferFormat">{{ $t('memberTransfer.transferFormat') }}:</label>
              <select id="transferFormat" v-model="config.transferFormat" class="form-select">
                <option value="json">JSON</option>
                <option value="xml">XML</option>
                <option value="form-data">Form Data</option>
                <option value="x-www-form-urlencoded">URL Encoded</option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label class="checkbox-item">
              <input type="checkbox" v-model="config.useBulkMode" />
              <span>{{ $t('memberTransfer.bulkMode') }}</span>
            </label>
            <span class="hint">{{ $t('memberTransfer.bulkModeHint') }}</span>
          </div>

          <div class="form-group">
            <label>{{ $t('memberTransfer.importTemplate') }}:</label>
            <div class="template-import">
              <textarea
                ref="importTextarea"
                v-model="importTemplate"
                rows="8"
                class="form-textarea import-area"
                :placeholder="importTemplatePlaceholderText"
              ></textarea>
              <button
                type="button"
                class="btn-import"
                @click="parseAndImportTemplate"
                :disabled="!importTemplate.trim()"
              >
                {{ $t('memberTransfer.analyzeAndImport') }}
              </button>
              <span class="hint">{{ $t('memberTransfer.importTemplateHint') }}</span>
            </div>
          </div>

          <div class="form-group" v-if="config.useBulkMode">
            <label for="bulkWrapperTemplate">{{ $t('memberTransfer.bulkWrapperTemplate') }}:</label>
            <div class="template-explanation">
              <p class="template-intro">
                <strong>{{ $t('memberTransfer.bulkWrapperWhat') }}</strong><br>
                {{ bulkWrapperDescriptionText }}
              </p>
              <div class="template-examples">
                <div class="example-section">
                  <strong>{{ $t('memberTransfer.example') }}:</strong>
                  <pre class="example-code">{{ bulkWrapperExample }}</pre>
                </div>
                <div class="bulk-mode-note">
                  <strong>ℹ️ {{ $t('memberTransfer.bulkWrapperNote') }}</strong>
                </div>
              </div>
            </div>
            <div class="template-editor">
              <textarea
                ref="bulkWrapperTextarea"
                id="bulkWrapperTemplate"
                v-model="config.bulkWrapperTemplate"
                rows="6"
                class="form-textarea"
                :placeholder="bulkWrapperPlaceholderText"
                @focus="onBulkWrapperFocus"
                @click="onBulkWrapperClick"
              ></textarea>
              <div class="template-help">
                <strong>{{ $t('memberTransfer.availablePlaceholders') }}:</strong>
                <div class="placeholders-grid">
                  <button
                    type="button"
                    class="placeholder-button"
                    :title="$t('memberTransfer.membersArray')"
                    @click="insertPlaceholder('{{members}}', 'bulkWrapper')"
                  >
                    <code v-text="'{{members}}'"></code>
                    <span>{{ $t('memberTransfer.membersArray') }}</span>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="transferTemplate">{{ $t('memberTransfer.transferTemplate') }}: <span class="required">*</span></label>
            <div class="template-explanation">
              <p class="template-intro">
                <strong>{{ $t('memberTransfer.templateWhat') }}</strong><br>
                {{ templateDescriptionText }}
              </p>
              <div class="template-examples">
                <div class="example-section">
                  <strong>{{ $t('memberTransfer.exampleJson') }}:</strong>
                  <pre class="example-code">{{ jsonExample }}</pre>
                </div>
                <div class="example-section" v-if="config.transferFormat === 'xml'">
                  <strong>{{ $t('memberTransfer.exampleXml') }}:</strong>
                  <pre class="example-code">{{ xmlExample }}</pre>
                </div>
                <div class="example-section" v-if="config.transferFormat === 'form-data' || config.transferFormat === 'x-www-form-urlencoded'">
                  <strong>{{ $t('memberTransfer.exampleFormData') }}:</strong>
                  <p class="example-hint">{{ $t('memberTransfer.formDataHint') }}</p>
                  <pre class="example-code">{{ formDataExample }}</pre>
                </div>
                <div class="bulk-mode-note" v-if="config.useBulkMode">
                  <strong>ℹ️ {{ $t('memberTransfer.bulkModeActive') }}:</strong> {{ $t('memberTransfer.bulkModeActiveDescription') }}
                </div>
              </div>
            </div>
            <div class="template-editor">
              <textarea
                ref="templateTextarea"
                id="transferTemplate"
                v-model="config.transferTemplate"
                rows="10"
                class="form-textarea"
                :placeholder="templatePlaceholder"
                @focus="onTemplateFocus"
                @click="onTemplateClick"
                required
              ></textarea>
              <div class="template-help">
                <strong>{{ $t('memberTransfer.availablePlaceholders') }}:</strong>
                <p class="placeholder-hint">{{ $t('memberTransfer.placeholderHint') }}</p>
                <div class="placeholders-grid">
                  <button
                    v-for="placeholder in placeholders"
                    :key="placeholder.code"
                    type="button"
                    class="placeholder-button"
                    :title="placeholder.description"
                    @click="insertPlaceholder(placeholder.code)"
                  >
                    <code>{{ placeholder.code }}</code>
                    <span>{{ placeholder.label }}</span>
                  </button>
                </div>
                <p class="template-tip">
                  <strong>💡 {{ $t('memberTransfer.templateTip') }}</strong>
                </p>
              </div>
            </div>
          </div>
        </div>

        <div class="actions">
          <button @click="saveConfig" class="btn-primary" :disabled="!isValid || saving">
            {{ saving ? $t('memberTransfer.saving') : $t('memberTransfer.save') }}
          </button>
          <button @click="deleteConfig" class="btn-danger" :disabled="!hasConfig || deleting">
            {{ deleting ? $t('memberTransfer.deleting') : $t('memberTransfer.deleteConfig') }}
          </button>
        </div>
      </div>
    </div>

    <InfoDialog
      v-model="infoDialog.isOpen"
      :title="infoDialog.title"
      :message="infoDialog.message"
      :details="infoDialog.details"
      :type="infoDialog.type"
    />

    <ConfirmDialog
      v-model="confirmDialog.isOpen"
      :title="confirmDialog.title"
      :message="confirmDialog.message"
      :details="confirmDialog.details"
      :type="confirmDialog.type"
      :confirm-text="confirmDialog.confirmText"
      :cancel-text="confirmDialog.cancelText"
      :show-cancel="confirmDialog.showCancel"
      @confirm="handleConfirmResult(true)"
      @cancel="handleConfirmResult(false)"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';
import { getSafeErrorMessage, getSafeMessage } from '../utils/errorMessages.js';

export default {
  name: 'MemberTransferSettingsView',
  components: {
    InfoDialog,
    ConfirmDialog
  },
  computed: {
    ...mapGetters(['currentClub']),
    
    isValid() {
      return !!(this.config.server && this.config.transferEndpoint && this.config.transferTemplate);
    },
    
    hasConfig() {
      return this.configId !== null;
    },
    
    jsonExample() {
      return JSON.stringify({
        firstName: "{{firstName}}",
        lastName: "{{lastName}}",
        geburtsdatum: "{{geburtsdatum}}",
        email: "{{email}}",
        phone: "{{phone}}",
        address: "{{address}}"
      }, null, 2);
    },
    
    xmlExample() {
      return `<member>
  <firstName>{{firstName}}</firstName>
  <lastName>{{lastName}}</lastName>
  <geburtsdatum>{{geburtsdatum}}</geburtsdatum>
  <email>{{email}}</email>
  <phone>{{phone}}</phone>
  <address>{{address}}</address>
</member>`;
    },
    
    formDataExample() {
      return `firstName={{firstName}}
lastName={{lastName}}
geburtsdatum={{geburtsdatum}}
email={{email}}
phone={{phone}}
address={{address}}`;
    },
    
    bulkWrapperExample() {
      // Beispiel: Der Platzhalter [{{members}}] wird später durch das Array ersetzt
      return `{
  "members": [{{members}}]
}`;
    },
    
    bulkWrapperPlaceholderText() {
      // Verwende den Beispiel-Text direkt, um Probleme mit vue-i18n Platzhaltern zu vermeiden
      return '{"members": [{{members}}]}';
    },
    
    bulkWrapperDescriptionText() {
      // Hole den Text aus der Übersetzung und ersetze den Platzhalter
      // Prüfe, ob $t verfügbar ist, bevor wir es verwenden
      if (!this.$t || typeof this.$t !== 'function') {
        return 'Optional können Sie die äußere Struktur definieren, in die die Mitglieder-Array eingefügt wird. Verwenden Sie {{members}} als Platzhalter für das Array der Mitglieder.';
      }
      try {
        const text = this.$t('memberTransfer.bulkWrapperDescription');
        if (typeof text === 'string') {
          // Ersetze PLACEHOLDER_MEMBERS durch {{members}}
          return text.replace(/PLACEHOLDER_MEMBERS/g, '{{members}}');
        }
        return 'Optional können Sie die äußere Struktur definieren, in die die Mitglieder-Array eingefügt wird. Verwenden Sie {{members}} als Platzhalter für das Array der Mitglieder.';
      } catch (e) {
        console.warn('Fehler beim Laden der Übersetzung für bulkWrapperDescription:', e);
        // Fallback, falls $t nicht verfügbar ist
        return 'Optional können Sie die äußere Struktur definieren, in die die Mitglieder-Array eingefügt wird. Verwenden Sie {{members}} als Platzhalter für das Array der Mitglieder.';
      }
    },
    
    templateDescriptionText() {
      // Hole den Text aus der Übersetzung und ersetze den Platzhalter
      // Prüfe, ob $t verfügbar ist, bevor wir es verwenden
      if (!this.$t || typeof this.$t !== 'function') {
        return 'Das Template definiert das Format, in dem die Mitgliederdaten an das externe System übertragen werden. Verwenden Sie Platzhalter wie {{firstName}}, um die Daten automatisch zu ersetzen.';
      }
      try {
        const text = this.$t('memberTransfer.templateDescription');
        if (typeof text === 'string') {
          // Ersetze PLACEHOLDER_FIRSTNAME durch {{firstName}}
          return text.replace(/PLACEHOLDER_FIRSTNAME/g, '{{firstName}}');
        }
        return 'Das Template definiert das Format, in dem die Mitgliederdaten an das externe System übertragen werden. Verwenden Sie Platzhalter wie {{firstName}}, um die Daten automatisch zu ersetzen.';
      } catch (e) {
        console.warn('Fehler beim Laden der Übersetzung für templateDescription:', e);
        // Fallback, falls $t nicht verfügbar ist
        return 'Das Template definiert das Format, in dem die Mitgliederdaten an das externe System übertragen werden. Verwenden Sie Platzhalter wie {{firstName}}, um die Daten automatisch zu ersetzen.';
      }
    },
    
    importTemplatePlaceholderText() {
      // Hole den Text aus der Übersetzung und ersetze die Platzhalter
      // Prüfe, ob $t verfügbar ist, bevor wir es verwenden
      if (!this.$t || typeof this.$t !== 'function') {
        return `Fügen Sie hier ein vollständiges Beispiel-Template ein, z.B.:\n{\n  "members": [\n    {\n      "firstName": "Max",\n      "lastName": "Mustermann",\n      "email": "max@example.com"\n    }\n  ]\n}`;
      }
      try {
        const text = this.$t('memberTransfer.importTemplatePlaceholder');
        if (typeof text === 'string') {
          // Ersetze die Platzhalter durch geschweifte Klammern und Anführungszeichen
          return text
            .replace(/LBRACE/g, '{')
            .replace(/RBRACE/g, '}')
            .replace(/DQUOTE/g, '"')
            .replace(/AT/g, '@');
        }
        return `Fügen Sie hier ein vollständiges Beispiel-Template ein, z.B.:\n{\n  "members": [\n    {\n      "firstName": "Max",\n      "lastName": "Mustermann",\n      "email": "max@example.com"\n    }\n  ]\n}`;
      } catch (e) {
        console.warn('Fehler beim Laden der Übersetzung für importTemplatePlaceholder:', e);
        // Fallback, falls $t nicht verfügbar ist
        return `Fügen Sie hier ein vollständiges Beispiel-Template ein, z.B.:\n{\n  "members": [\n    {\n      "firstName": "Max",\n      "lastName": "Mustermann",\n      "email": "max@example.com"\n    }\n  ]\n}`;
      }
    },
    
    templatePlaceholder() {
      if (this.config.transferFormat === 'json') {
        return '{"firstName": "{{firstName}}", "lastName": "{{lastName}}", "geburtsdatum": "{{geburtsdatum}}", "email": "{{email}}", "phone": "{{phone}}", "address": "{{address}}"}';
      } else if (this.config.transferFormat === 'xml') {
        return '<member>\n  <firstName>{{firstName}}</firstName>\n  <lastName>{{lastName}}</lastName>\n  <email>{{email}}</email>\n</member>';
      } else {
        return 'firstName={{firstName}}\nlastName={{lastName}}\nemail={{email}}';
      }
    },
    
    placeholders() {
      // Prüfe, ob $t verfügbar ist, bevor wir es verwenden
      if (!this.$t || typeof this.$t !== 'function') {
        // Fallback mit deutschen Texten
        return [
          { code: '{{firstName}}', label: 'Vorname', description: 'Vorname des Mitglieds' },
          { code: '{{lastName}}', label: 'Nachname', description: 'Nachname des Mitglieds' },
          { code: '{{fullName}}', label: 'Vollständiger Name', description: 'Vollständiger Name (Vorname + Nachname)' },
          { code: '{{email}}', label: 'E-Mail', description: 'E-Mail-Adresse des Mitglieds' },
          { code: '{{phone}}', label: 'Telefon', description: 'Telefonnummer des Mitglieds' },
          { code: '{{street}}', label: 'Straße', description: 'Straße und Hausnummer' },
          { code: '{{city}}', label: 'Stadt', description: 'Stadt/Ortsname' },
          { code: '{{birthDate}}', label: 'Geburtsdatum', description: 'Geburtsdatum im Format YYYY-MM-DD' },
          { code: '{{geburtsdatum}}', label: 'Geburtsdatum (alt)', description: 'Geburtsdatum im Format YYYY-MM-DD (alternative Bezeichnung)' },
          { code: '{{address}}', label: 'Adresse', description: 'Vollständige Adresse (Straße, PLZ, Stadt)' },
          { code: '{{ttr}}', label: 'TTR', description: 'Tischtennis-Rating (TTR)' },
          { code: '{{qttr}}', label: 'QTTR', description: 'Quotienten-TTR (QTTR)' },
          { code: '{{gender}}', label: 'Geschlecht', description: 'Geschlecht (m/w/d)' }
        ];
      }
      
      try {
        return [
          { code: '{{firstName}}', label: this.$t('memberTransfer.placeholders.firstName'), description: this.$t('memberTransfer.placeholders.firstNameDesc') },
          { code: '{{lastName}}', label: this.$t('memberTransfer.placeholders.lastName'), description: this.$t('memberTransfer.placeholders.lastNameDesc') },
          { code: '{{fullName}}', label: this.$t('memberTransfer.placeholders.fullName'), description: this.$t('memberTransfer.placeholders.fullNameDesc') },
          { code: '{{email}}', label: this.$t('memberTransfer.placeholders.email'), description: this.$t('memberTransfer.placeholders.emailDesc') },
          { code: '{{phone}}', label: this.$t('memberTransfer.placeholders.phone'), description: this.$t('memberTransfer.placeholders.phoneDesc') },
          { code: '{{street}}', label: this.$t('memberTransfer.placeholders.street'), description: this.$t('memberTransfer.placeholders.streetDesc') },
          { code: '{{city}}', label: this.$t('memberTransfer.placeholders.city'), description: this.$t('memberTransfer.placeholders.cityDesc') },
          { code: '{{birthDate}}', label: this.$t('memberTransfer.placeholders.birthDate'), description: this.$t('memberTransfer.placeholders.birthDateDesc') },
          { code: '{{geburtsdatum}}', label: this.$t('memberTransfer.placeholders.birthDateAlt'), description: this.$t('memberTransfer.placeholders.birthDateAltDesc') },
          { code: '{{address}}', label: this.$t('memberTransfer.placeholders.address'), description: this.$t('memberTransfer.placeholders.addressDesc') },
          { code: '{{ttr}}', label: this.$t('memberTransfer.placeholders.ttr'), description: this.$t('memberTransfer.placeholders.ttrDesc') },
          { code: '{{qttr}}', label: this.$t('memberTransfer.placeholders.qttr'), description: this.$t('memberTransfer.placeholders.qttrDesc') },
          { code: '{{gender}}', label: this.$t('memberTransfer.placeholders.gender'), description: this.$t('memberTransfer.placeholders.genderDesc') }
        ];
      } catch (e) {
        console.warn('Fehler beim Laden der Übersetzungen für placeholders:', e);
        // Fallback mit deutschen Texten
        return [
          { code: '{{firstName}}', label: 'Vorname', description: 'Vorname des Mitglieds' },
          { code: '{{lastName}}', label: 'Nachname', description: 'Nachname des Mitglieds' },
          { code: '{{fullName}}', label: 'Vollständiger Name', description: 'Vollständiger Name (Vorname + Nachname)' },
          { code: '{{email}}', label: 'E-Mail', description: 'E-Mail-Adresse des Mitglieds' },
          { code: '{{phone}}', label: 'Telefon', description: 'Telefonnummer des Mitglieds' },
          { code: '{{street}}', label: 'Straße', description: 'Straße und Hausnummer' },
          { code: '{{city}}', label: 'Stadt', description: 'Stadt/Ortsname' },
          { code: '{{birthDate}}', label: 'Geburtsdatum', description: 'Geburtsdatum im Format YYYY-MM-DD' },
          { code: '{{geburtsdatum}}', label: 'Geburtsdatum (alt)', description: 'Geburtsdatum im Format YYYY-MM-DD (alternative Bezeichnung)' },
          { code: '{{address}}', label: 'Adresse', description: 'Vollständige Adresse (Straße, PLZ, Stadt)' },
          { code: '{{ttr}}', label: 'TTR', description: 'Tischtennis-Rating (TTR)' },
          { code: '{{qttr}}', label: 'QTTR', description: 'Quotienten-TTR (QTTR)' },
          { code: '{{gender}}', label: 'Geschlecht', description: 'Geschlecht (m/w/d)' }
        ];
      }
    }
  },
  data() {
    return {
      infoDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'info'
      },
      confirmDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'info',
        confirmText: 'OK',
        cancelText: '',
        showCancel: true,
        resolveCallback: null
      },
      loading: true,
      saving: false,
      deleting: false,
      configId: null,
      currentTextarea: 'template', // 'template' oder 'bulkWrapper'
      importTemplate: '',
      config: {
        server: '',
        loginEndpoint: '',
        loginFormat: 'json',
        transferEndpoint: '',
        transferMethod: 'POST',
        transferFormat: 'json',
        transferTemplate: '',
        useBulkMode: false,
        bulkWrapperTemplate: ''
      },
      loginCredentials: {
        username: '',
        password: '',
        additionalField1: '',
        additionalField2: ''
      }
    };
  },
  async mounted() {
    await this.loadConfig();
  },
  methods: {
    async showInfo(title, message, details = '', type = 'info') {
      this.infoDialog = {
        isOpen: true,
        title,
        message,
        details,
        type
      };
    },

    async showConfirm(title, message, details = '', type = 'info', options = {}) {
      return new Promise((resolve) => {
        this.confirmDialog = {
          isOpen: true,
          title,
          message,
          details,
          type,
          confirmText: options.confirmText || 'OK',
          cancelText: options.cancelText || this.$t('common.cancel'),
          showCancel: options.showCancel !== false,
          resolveCallback: resolve
        };
      });
    },

    handleConfirmResult(confirmed) {
      if (this.confirmDialog.resolveCallback) {
        this.confirmDialog.resolveCallback(confirmed);
        this.confirmDialog.resolveCallback = null;
      }
      this.confirmDialog.isOpen = false;
    },

    async loadConfig() {
      if (!this.currentClub) {
        this.loading = false;
        return;
      }

      try {
        const response = await apiClient.get(`/member-transfer-config/${this.currentClub}`);
        
        if (response.data.success && response.data.config) {
          const savedConfig = response.data.config;
          this.configId = savedConfig.id;
          this.config.server = savedConfig.server || '';
          this.config.loginEndpoint = savedConfig.loginEndpoint || '';
          this.config.loginFormat = savedConfig.loginFormat || 'json';
          this.config.transferEndpoint = savedConfig.transferEndpoint || '';
          this.config.transferMethod = savedConfig.transferMethod || 'POST';
          this.config.transferFormat = savedConfig.transferFormat || 'json';
          this.config.transferTemplate = savedConfig.transferTemplate || '';
          this.config.useBulkMode = savedConfig.useBulkMode || false;
          this.config.bulkWrapperTemplate = savedConfig.bulkWrapperTemplate || '';
          
          // Login-Credentials laden (Passwort wird nicht zurückgegeben)
          if (savedConfig.loginCredentials) {
            this.loginCredentials = {
              username: savedConfig.loginCredentials.username || '',
              password: '', // Passwort wird nicht zurückgegeben
              additionalField1: savedConfig.loginCredentials.additionalField1 || '',
              additionalField2: savedConfig.loginCredentials.additionalField2 || ''
            };
          }
        }
      } catch (error) {
        if (error.response?.status === 404) {
          // Keine Konfiguration vorhanden - das ist OK
        } else {
          console.error('Fehler beim Laden der Konfiguration:', error);
          await this.showInfo(this.$t('messages.error'), this.$t('memberTransfer.errorLoading'), getSafeErrorMessage(error), 'error');
        }
      } finally {
        this.loading = false;
      }
    },

    async saveConfig() {
      if (!this.isValid || !this.currentClub) {
        return;
      }

      this.saving = true;

      try {
        // Login-Credentials zusammenstellen
        const loginCredentials = {};
        if (this.loginCredentials.username) {
          loginCredentials.username = this.loginCredentials.username;
        }
        if (this.loginCredentials.password) {
          loginCredentials.password = this.loginCredentials.password;
        }
        
        // Zusätzliche Felder verarbeiten
        if (this.loginCredentials.additionalField1) {
          const parts1 = this.loginCredentials.additionalField1.split(':').map(s => s.trim());
          if (parts1.length === 2) {
            loginCredentials[parts1[0]] = parts1[1];
          } else {
            loginCredentials[parts1[0]] = parts1[0];
          }
        }
        if (this.loginCredentials.additionalField2) {
          const parts2 = this.loginCredentials.additionalField2.split(':').map(s => s.trim());
          if (parts2.length === 2) {
            loginCredentials[parts2[0]] = parts2[1];
          } else {
            loginCredentials[parts2[0]] = parts2[0];
          }
        }

        const payload = {
          server: this.config.server,
          loginEndpoint: this.config.loginEndpoint || null,
          loginFormat: this.config.loginFormat,
          loginCredentials: Object.keys(loginCredentials).length > 0 ? loginCredentials : null,
          transferEndpoint: this.config.transferEndpoint,
          transferMethod: this.config.transferMethod,
          transferFormat: this.config.transferFormat,
          transferTemplate: this.config.transferTemplate,
          useBulkMode: this.config.useBulkMode,
          bulkWrapperTemplate: this.config.bulkWrapperTemplate || null
        };

        const response = await apiClient.post(`/member-transfer-config/${this.currentClub}`, payload);

        if (response.data.success) {
          this.configId = response.data.config?.id || null;
          const successMessage = getSafeMessage(response.data?.message, this.$t('memberTransfer.configSaved'));
          await this.showInfo(this.$t('messages.success'), successMessage, '', 'success');
          
          // Passwort-Feld leeren nach erfolgreichem Speichern
          this.loginCredentials.password = '';
        } else {
          const errorMessage = getSafeMessage(response.data?.error, this.$t('memberTransfer.errorSaving'));
          await this.showInfo(this.$t('messages.error'), errorMessage, '', 'error');
        }
      } catch (error) {
        console.error('Fehler beim Speichern:', error);
        await this.showInfo(this.$t('messages.error'), this.$t('memberTransfer.errorSaving'), getSafeErrorMessage(error), 'error');
      } finally {
        this.saving = false;
      }
    },

    async deleteConfig() {
      if (!this.hasConfig || !this.currentClub) {
        return;
      }

      const confirmed = await this.showConfirm(this.$t('memberTransfer.confirmDelete'), this.$t('memberTransfer.confirmDeleteMessage'), '', 'danger');
      if (!confirmed) {
        return;
      }

      this.deleting = true;

      try {
        const response = await apiClient.delete(`/member-transfer-config/${this.currentClub}`);

        if (response.data.success) {
          this.configId = null;
          // Reset zu Standardwerten
          this.config = {
            server: '',
            loginEndpoint: '',
            loginFormat: 'json',
            transferEndpoint: '',
            transferMethod: 'POST',
            transferFormat: 'json',
            transferTemplate: '',
            useBulkMode: false,
            bulkWrapperTemplate: ''
          };
          this.loginCredentials = {
            username: '',
            password: '',
            additionalField1: '',
            additionalField2: ''
          };
          await this.showInfo(this.$t('messages.success'), getSafeMessage(response.data?.message, this.$t('memberTransfer.configDeleted')), '', 'success');
        } else {
          await this.showInfo(this.$t('messages.error'), getSafeMessage(response.data?.error, this.$t('memberTransfer.errorDeleting')), '', 'error');
        }
      } catch (error) {
        console.error('Fehler beim Löschen:', error);
        await this.showInfo(this.$t('messages.error'), this.$t('memberTransfer.errorDeleting'), getSafeErrorMessage(error), 'error');
      } finally {
        this.deleting = false;
      }
    },
    
    onTemplateFocus() {
      this.currentTextarea = 'template';
    },
    
    onTemplateClick() {
      this.currentTextarea = 'template';
    },
    
    onBulkWrapperFocus() {
      this.currentTextarea = 'bulkWrapper';
    },
    
    onBulkWrapperClick() {
      this.currentTextarea = 'bulkWrapper';
    },
    
    insertPlaceholder(placeholderCode, target = null) {
      const textareaName = target || this.currentTextarea;
      const textareaRef = textareaName === 'bulkWrapper' ? this.$refs.bulkWrapperTextarea : this.$refs.templateTextarea;
      
      if (!textareaRef) {
        // Fallback: Direkt in den v-model String einfügen
        if (textareaName === 'bulkWrapper') {
          const currentValue = this.config.bulkWrapperTemplate || '';
          const cursorPos = currentValue.length;
          this.config.bulkWrapperTemplate = 
            currentValue.slice(0, cursorPos) + 
            placeholderCode + 
            currentValue.slice(cursorPos);
        } else {
          const currentValue = this.config.transferTemplate || '';
          const cursorPos = currentValue.length;
          this.config.transferTemplate = 
            currentValue.slice(0, cursorPos) + 
            placeholderCode + 
            currentValue.slice(cursorPos);
        }
        return;
      }
      
      const textarea = textareaRef;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const currentValue = textarea.value || '';
      
      // Platzhalter einfügen
      const newValue = 
        currentValue.slice(0, start) + 
        placeholderCode + 
        currentValue.slice(end);
      
      // Wert aktualisieren
      if (textareaName === 'bulkWrapper') {
        this.config.bulkWrapperTemplate = newValue;
      } else {
        this.config.transferTemplate = newValue;
      }
      
      // Cursor-Position nach dem eingefügten Platzhalter setzen
      this.$nextTick(() => {
        const newCursorPos = start + placeholderCode.length;
        textarea.setSelectionRange(newCursorPos, newCursorPos);
        textarea.focus();
      });
    },
    
    async parseAndImportTemplate() {
      if (!this.importTemplate.trim()) {
        return;
      }
      
      try {
        // Versuche JSON zu parsen
        const parsed = JSON.parse(this.importTemplate.trim());
        
        // Prüfe, ob es ein Bulk-Format ist (mit members-Array)
        if (parsed.members && Array.isArray(parsed.members) && parsed.members.length > 0) {
          // Bulk-Format erkannt
          const firstMember = parsed.members[0];
          
          // Mitglied-Template extrahieren (erster Member im Array)
          const memberTemplate = { ...firstMember };
          
          // Platzhalter in den Werten finden und ersetzen
          // Zuerst versuchen, echte Werte zu Platzhaltern zu machen
          const memberTemplateWithPlaceholders = this.convertValuesToPlaceholders(memberTemplate);
          
          // Mitglied-Template als JSON-String setzen
          this.config.transferTemplate = JSON.stringify(memberTemplateWithPlaceholders, null, 2);
          
          // Bulk-Wrapper-Template erstellen (alles außer dem members-Array)
          // Wir erstellen eine Kopie des gesamten Objekts und ersetzen das members-Array durch den Platzhalter
          const wrapperTemplate = JSON.parse(JSON.stringify(parsed)); // Deep copy
          
          // Bulk-Wrapper-Template erstellen
          // Wichtig: Wir müssen das Template als Text-String erstellen, nicht als JSON-Objekt,
          // damit wir den Platzhalter [{{members}}] direkt verwenden können (ohne Anführungszeichen)
          let wrapperTemplateString = JSON.stringify(parsed, null, 2);
          
          // Finde das members-Array im JSON-String und ersetze es durch den Platzhalter [{{members}}]
          // Pattern: "members": [\n ... alles bis zum schließenden ] ... \n]
          // Ersetze durch: "members": [{{members}}]
          const membersArrayRegex = /("members"\s*:\s*)\[[\s\S]*?\]/;
          
          if (membersArrayRegex.test(wrapperTemplateString)) {
            // Ersetze das Array durch [{{members}}]
            wrapperTemplateString = wrapperTemplateString.replace(
              membersArrayRegex,
              '$1[{{members}}]'
            );
          } else {
            // Fallback: Versuche auch verschachtelte Strukturen zu finden
            const nestedMembersRegex = /("data"\s*:\s*\{[^}]*"members"\s*:\s*)\[[\s\S]*?\]/;
            if (nestedMembersRegex.test(wrapperTemplateString)) {
              wrapperTemplateString = wrapperTemplateString.replace(
                nestedMembersRegex,
                '$1[{{members}}]'
              );
            }
          }
          
          // Wrapper-Template als String setzen (nicht als JSON geparst)
          this.config.bulkWrapperTemplate = wrapperTemplateString;
          
          // Bulk-Modus aktivieren
          this.config.useBulkMode = true;
          
          // Import-Bereich leeren
          this.importTemplate = '';
          
          await this.showInfo(this.$t('messages.success'), this.$t('memberTransfer.templateImported'), this.$t('memberTransfer.templateImportedDetails'), 'success');
        } else if (Array.isArray(parsed) && parsed.length > 0) {
          // Direktes Array-Format (ohne Wrapper)
          const firstMember = parsed[0];
          const memberTemplateWithPlaceholders = this.convertValuesToPlaceholders({ ...firstMember });
          
          this.config.transferTemplate = JSON.stringify(memberTemplateWithPlaceholders, null, 2);
          this.config.useBulkMode = true;
          this.config.bulkWrapperTemplate = '{"members": "{{members}}"}';
          
          this.importTemplate = '';
          await this.showInfo(this.$t('messages.success'), this.$t('memberTransfer.templateImported'), this.$t('memberTransfer.templateImportedBulk'), 'success');
        } else if (typeof parsed === 'object' && parsed !== null) {
          // Einzelnes Mitglied-Objekt
          const memberTemplateWithPlaceholders = this.convertValuesToPlaceholders(parsed);
          this.config.transferTemplate = JSON.stringify(memberTemplateWithPlaceholders, null, 2);
          this.config.useBulkMode = false;
          
          this.importTemplate = '';
          await this.showInfo(this.$t('messages.success'), this.$t('memberTransfer.templateImported'), this.$t('memberTransfer.templateImportedSingle'), 'success');
        } else {
          throw new Error(this.$t('memberTransfer.invalidTemplateFormat'));
        }
      } catch (error) {
        const detail = `${getSafeMessage(error.message, this.$t('messages.error'))}\n\n${this.$t('memberTransfer.invalidJson')}`;
        await this.showInfo(this.$t('messages.error'), this.$t('memberTransfer.errorParsingTemplate'), detail, 'error');
      }
    },
    
    convertValuesToPlaceholders(obj) {
      // Konvertiert Beispiel-Werte zu Platzhaltern basierend auf Feldnamen und Werten
      const result = {};
      
      // Mapping von Beispiel-Werten zu Platzhaltern
      const valueToPlaceholder = {
        'Max': '{{firstName}}',
        'Mustermann': '{{lastName}}',
        'max@example.com': '{{email}}',
        'anna@example.com': '{{email}}',
        '0123456789': '{{phone}}',
        'Musterstraße 1': '{{street}}',
        'Musterstraße': '{{street}}',
        'Berlin': '{{city}}',
        'München': '{{city}}',
        '1990-01-15': '{{birthDate}}',
        '1985-03-20': '{{birthDate}}',
        '1990-01-15': '{{geburtsdatum}}',
        '1985-03-20': '{{geburtsdatum}}',
        'Optional': '{{notes}}'
      };
      
      // Mapping von Feldnamen zu Platzhaltern
      const fieldToPlaceholder = {
        'firstName': '{{firstName}}',
        'first_name': '{{firstName}}',
        'vorname': '{{firstName}}',
        'lastName': '{{lastName}}',
        'last_name': '{{lastName}}',
        'nachname': '{{lastName}}',
        'name': '{{fullName}}',
        'email': '{{email}}',
        'eMail': '{{email}}',
        'phone': '{{phone}}',
        'telefon': '{{phone}}',
        'telephone': '{{phone}}',
        'street': '{{street}}',
        'straße': '{{street}}',
        'strasse': '{{street}}',
        'address': '{{address}}',
        'adresse': '{{address}}',
        'city': '{{city}}',
        'ort': '{{city}}',
        'birthDate': '{{birthDate}}',
        'birth_date': '{{birthDate}}',
        'geburtsdatum': '{{geburtsdatum}}',
        'geburtstag': '{{birthDate}}',
        'ttr': '{{ttr}}',
        'qttr': '{{qttr}}',
        'gender': '{{gender}}',
        'geschlecht': '{{gender}}'
      };
      
      for (const [key, value] of Object.entries(obj)) {
        // Prüfe zuerst Feldnamen-Mapping
        const normalizedKey = key.toLowerCase();
        if (fieldToPlaceholder[normalizedKey]) {
          result[key] = fieldToPlaceholder[normalizedKey];
        } else if (valueToPlaceholder[value]) {
          // Dann prüfe Wert-Mapping
          result[key] = valueToPlaceholder[value];
        } else if (typeof value === 'string' && value.trim()) {
          // Wenn es ein String ist, versuche basierend auf dem Feldnamen zu erraten
          if (normalizedKey.includes('first') || normalizedKey.includes('vorname')) {
            result[key] = '{{firstName}}';
          } else if (normalizedKey.includes('last') || normalizedKey.includes('nachname')) {
            result[key] = '{{lastName}}';
          } else if (normalizedKey.includes('email') || normalizedKey.includes('mail')) {
            result[key] = '{{email}}';
          } else if (normalizedKey.includes('phone') || normalizedKey.includes('tel')) {
            result[key] = '{{phone}}';
          } else if (normalizedKey.includes('street') || normalizedKey.includes('straße') || normalizedKey.includes('strasse')) {
            result[key] = '{{street}}';
          } else if (normalizedKey.includes('city') || normalizedKey.includes('ort')) {
            result[key] = '{{city}}';
          } else if (normalizedKey.includes('birth') || normalizedKey.includes('geburts')) {
            result[key] = '{{birthDate}}';
          } else if (normalizedKey.includes('address') || normalizedKey.includes('adresse')) {
            result[key] = '{{address}}';
          } else {
            // Unbekanntes Feld - behalte den Wert oder verwende einen generischen Platzhalter
            result[key] = value;
          }
        } else {
          // Andere Typen (Zahlen, booleans, etc.) behalten
          result[key] = value;
        }
      }
      
      return result;
    }
  }
};
</script>

<style scoped>
.member-transfer-settings {
  max-width: 1200px;
  margin: 0 auto;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.settings-container {
  margin-top: 1.5rem;
}

.settings-card {
  background: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.settings-card h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #333;
}

.info-text {
  color: #666;
  margin-bottom: 2rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #007bff;
}

.form-section {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #e0e0e0;
}

.form-section:last-of-type {
  border-bottom: none;
}

.form-section h4 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #333;
  font-size: 1.1em;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}

.form-group .required {
  color: #dc3545;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 0.9em;
  font-family: inherit;
}

.form-textarea {
  font-family: 'Courier New', monospace;
  resize: vertical;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.credentials-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.credential-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem;
}

.hint {
  display: block;
  margin-top: 0.25rem;
  font-size: 0.85em;
  color: #666;
  font-style: italic;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
}

.checkbox-item input[type="checkbox"] {
  width: auto;
  margin: 0;
}

.template-explanation {
  margin-bottom: 1rem;
  padding: 1.25rem;
  background-color: #f0f7ff;
  border-radius: 6px;
  border-left: 4px solid #007bff;
}

.template-intro {
  margin: 0 0 1rem 0;
  color: #333;
  line-height: 1.6;
}

.template-intro strong {
  display: block;
  margin-bottom: 0.5rem;
  color: #0056b3;
  font-size: 1.05em;
}

.template-examples {
  margin-top: 1rem;
}

.example-section {
  margin-bottom: 1.25rem;
}

.example-section strong {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
  font-size: 0.95em;
}

.example-hint {
  margin: 0.5rem 0;
  font-size: 0.9em;
  color: #555;
  font-style: italic;
}

.example-code {
  background-color: #2d2d2d;
  color: #f8f8f2;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 0.85em;
  line-height: 1.5;
  margin: 0.5rem 0;
  border: 1px solid #1a1a1a;
}

.bulk-mode-note {
  margin-top: 1rem;
  padding: 0.75rem 1rem;
  background-color: #fff3cd;
  border-left: 4px solid #ffc107;
  border-radius: 4px;
  color: #856404;
  font-size: 0.9em;
}

.bulk-mode-note strong {
  color: #856404;
}

.template-help {
  margin-top: 1rem;
  padding: 1.25rem;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  font-size: 0.9em;
}

.template-help strong {
  display: block;
  margin-bottom: 0.75rem;
  color: #333;
  font-size: 1em;
}

.placeholders-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 0.75rem;
  margin: 1rem 0;
}

.template-editor {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.placeholder-hint {
  margin: 0.5rem 0;
  font-size: 0.9em;
  color: #555;
  font-style: italic;
}

.placeholder-button {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  padding: 0.5rem;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #dee2e6;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
  width: 100%;
}

.placeholder-button:hover {
  background-color: #f8f9fa;
  border-color: #007bff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 123, 255, 0.1);
}

.placeholder-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 123, 255, 0.1);
}

.placeholder-button code {
  background-color: #e9ecef;
  padding: 0.3rem 0.5rem;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
  color: #c7254e;
  font-weight: 600;
  pointer-events: none;
}

.placeholder-button span {
  font-size: 0.85em;
  color: #666;
  pointer-events: none;
}

.placeholder-item {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  padding: 0.5rem;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #dee2e6;
}

.placeholder-item code {
  background-color: #e9ecef;
  padding: 0.3rem 0.5rem;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
  color: #c7254e;
  font-weight: 600;
}

.placeholder-item span {
  font-size: 0.85em;
  color: #666;
}

.template-tip {
  margin-top: 1rem;
  padding: 0.75rem 1rem;
  background-color: #d1ecf1;
  border-left: 4px solid #17a2b8;
  border-radius: 4px;
  color: #0c5460;
  font-size: 0.9em;
  line-height: 1.5;
}

.template-tip strong {
  color: #0c5460;
}

.template-import {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.import-area {
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.btn-import {
  align-self: flex-start;
  padding: 0.6rem 1.2rem;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border: 1px solid transparent;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 600;
  transition: transform 0.2s ease, opacity 0.2s ease;
  font-size: 0.95em;
}

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

.btn-import:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid #e0e0e0;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border: 1px solid transparent;
  padding: 0.75rem 1.5rem;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.2s ease, transform 0.2s ease;
}

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

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

.btn-danger {
  background: rgba(200, 74, 56, 0.12);
  color: #8b3327;
  border: 1px solid rgba(200, 74, 56, 0.24);
  padding: 0.75rem 1.5rem;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.2s ease;
}

.btn-danger:hover:not(:disabled) {
  background: rgba(200, 74, 56, 0.18);
}

.btn-danger:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}
</style>
