<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal">
      <div class="modal-header">
        <h3>{{ loginMode ? 'Login' : (account ? 'HTTV-/click-TT-Account bearbeiten' : 'HTTV-/click-TT-Account verknüpfen') }}</h3>
      </div>

      <div class="modal-body">
        <div class="form-group">
          <label for="clicktt-username">Benutzername / Login</label>
          <input
            id="clicktt-username"
            v-model="formData.username"
            type="text"
            placeholder="TTDE / click-TT Benutzername"
            :readonly="loginMode"
          />
        </div>

        <div class="form-group">
          <label for="clicktt-password">Passwort</label>
          <input
            id="clicktt-password"
            v-model="formData.password"
            type="password"
            :placeholder="account && account.savePassword ? 'Leer lassen, um das gespeicherte Passwort zu behalten' : 'HTTV-/click-TT-Passwort'"
          />
        </div>

        <template v-if="!loginMode">
          <div class="form-group checkbox-group">
            <label>
              <input type="checkbox" v-model="formData.savePassword" />
              <span>Passwort speichern</span>
            </label>
          </div>

          <div class="form-group" v-if="formData.password">
            <label for="clicktt-app-password">App-Passwort</label>
            <input
              id="clicktt-app-password"
              v-model="formData.userPassword"
              type="password"
              placeholder="Eigenes App-Passwort zur Bestätigung"
            />
          </div>
        </template>

        <div v-if="error" class="error-message">{{ error }}</div>
      </div>

      <div class="modal-footer">
        <button class="btn-secondary" @click="$emit('close')" :disabled="saving">Abbrechen</button>
        <button v-if="loginMode" class="btn-primary" @click="performLogin" :disabled="!canLogin || saving">
          {{ saving ? 'Prüfe…' : 'Login testen' }}
        </button>
        <button v-else class="btn-primary" @click="saveAccount" :disabled="!canSave || saving">
          {{ saving ? 'Speichere…' : 'Speichern' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import apiClient from '../apiClient.js';

export default {
  name: 'ClickTtAccountDialog',
  props: {
    account: { type: Object, default: null },
    loginMode: { type: Boolean, default: false }
  },
  data() {
    return {
      formData: {
        username: this.account?.username || '',
        password: '',
        savePassword: this.account?.savePassword || false,
        userPassword: ''
      },
      saving: false,
      error: null
    };
  },
  computed: {
    canLogin() {
      return !!this.formData.password;
    },
    canSave() {
      if (!this.formData.username.trim()) return false;
      if (this.formData.password && !this.formData.userPassword) return false;
      return true;
    }
  },
  methods: {
    async performLogin() {
      this.saving = true;
      this.error = null;
      try {
        await apiClient.post('/clicktt-account/verify', { password: this.formData.password });
        this.$emit('logged-in');
      } catch (error) {
        this.error = error.response?.data?.error || error.response?.data?.message || 'Login fehlgeschlagen';
      } finally {
        this.saving = false;
      }
    },
    async saveAccount() {
      this.saving = true;
      this.error = null;
      try {
        const payload = {
          username: this.formData.username,
          savePassword: this.formData.savePassword
        };
        if (this.formData.password) {
          payload.password = this.formData.password;
          payload.userPassword = this.formData.userPassword;
        }
        await apiClient.post('/clicktt-account/account', payload);
        this.$emit('saved');
      } catch (error) {
        this.error = error.response?.data?.error || error.response?.data?.message || 'Speichern fehlgeschlagen';
      } finally {
        this.saving = false;
      }
    }
  }
};
</script>

<style scoped>
.modal-overlay { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.38); display: flex; justify-content: center; align-items: center; z-index: 1000; }
.modal { background: var(--surface-color); border: 1px solid var(--border-color); border-radius: 14px; box-shadow: 0 18px 48px rgba(15, 23, 42, 0.18); max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto; display: flex; flex-direction: column; }
.modal-header { padding: 1.5rem; border-bottom: 1px solid var(--border-color); background: linear-gradient(180deg, rgba(47, 122, 95, 0.12), rgba(47, 122, 95, 0.04)); }
.modal-header h3 { margin: 0; color: var(--text-color); }
.modal-body { padding: 1.5rem; flex: 1; }
.modal-footer { padding: 1rem 1.5rem; border-top: 1px solid var(--border-color); display: flex; justify-content: flex-end; gap: 1rem; background: var(--surface-muted); }
.form-group { margin-bottom: 1.5rem; }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: var(--text-color); }
.form-group input[type="text"], .form-group input[type="password"] { width: 100%; padding: 0.75rem 0.875rem; border: 1px solid var(--border-color); border-radius: 10px; font-size: 1rem; box-sizing: border-box; background: var(--surface-muted); color: var(--text-color); }
.form-group input[type="text"]:focus, .form-group input[type="password"]:focus { outline: none; border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(47, 122, 95, 0.16); }
.checkbox-group label { display: flex; align-items: center; gap: 0.5rem; font-weight: normal; }
.error-message { padding: 0.75rem; background: rgba(200, 74, 56, 0.12); border: 1px solid rgba(200, 74, 56, 0.24); border-radius: 10px; color: #7a2e21; margin-top: 1rem; }
.btn-primary, .btn-secondary { padding: 0.75rem 1.5rem; border: 1px solid transparent; border-radius: 10px; font-size: 0.95rem; font-weight: 600; cursor: pointer; transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease; }
.btn-primary { background: linear-gradient(135deg, var(--primary-color), var(--primary-hover)); color: var(--text-on-primary); }
.btn-primary:hover:not(:disabled) { transform: translateY(-1px); }
.btn-secondary { background: var(--surface-color); border-color: var(--border-color); color: var(--text-color); }
.btn-secondary:hover:not(:disabled) { background: var(--surface-muted); border-color: var(--primary-soft); }
.btn-primary:disabled, .btn-secondary:disabled { opacity: 0.55; cursor: not-allowed; }
</style>
