<template>
  <div class="club-accounts-page">
    <header class="page-header card">
      <div>
        <p class="page-eyebrow">TT-Verein</p>
        <h2>Konten</h2>
        <p class="page-subtitle">
          Vereinskonten als Grundlage für Beiträge, Zahlungswege und spätere SEPA-Prozesse.
        </p>
      </div>
      <button type="button" class="btn-primary" :disabled="!canEdit" @click="resetForm">Neues Konto</button>
    </header>

    <div v-if="!canEdit && currentClub" class="state-banner">
      Lesemodus aktiv. Konten und Kontobewegungen können angezeigt, aber nicht bearbeitet werden.
    </div>

    <section v-if="!currentClub" class="card empty-state">
      <h3>Kein Verein ausgewählt</h3>
      <p>Bitte zuerst einen Verein auswählen, um Vereinskonten zu verwalten.</p>
    </section>

    <template v-else>
      <section class="accounts-stats-grid">
        <article class="card stat-card">
          <span class="stat-label">Aktiv</span>
          <strong class="stat-value">{{ accountStats.active }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">SEPA-fähig</span>
          <strong class="stat-value">{{ accountStats.sepa }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Ausgehend</span>
          <strong class="stat-value">{{ accountStats.outgoing }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Standardkonto</span>
          <strong class="stat-value">{{ defaultAccount ? defaultAccount.name : '–' }}</strong>
        </article>
      </section>

      <section class="accounts-layout">
        <div class="accounts-main">
          <section class="card accounts-filter-card">
            <div class="accounts-filter-grid">
              <label>
                <span>Status</span>
                <select v-model="filters.status">
                  <option value="">Alle</option>
                  <option value="active">Aktiv</option>
                  <option value="inactive">Inaktiv</option>
                  <option value="archived">Archiviert</option>
                </select>
              </label>
              <label>
                <span>Typ</span>
                <select v-model="filters.accountType">
                  <option value="">Alle</option>
                  <option value="bank">Bankkonto</option>
                  <option value="cash">Barkasse</option>
                  <option value="virtual">Virtuell</option>
                </select>
              </label>
              <label class="filter-search">
                <span>Suche</span>
                <input v-model.trim="filters.search" type="text" placeholder="Name, Bank oder IBAN" />
              </label>
            </div>
          </section>

          <section class="card accounts-list-card">
            <div class="section-header accounts-list-header">
              <h3>Kontenliste</h3>
              <button type="button" class="btn-secondary" @click="loadAccounts" :disabled="loading">
                {{ loading ? 'Lädt…' : 'Neu laden' }}
              </button>
            </div>

            <p v-if="loadError" class="state-banner state-banner-error">{{ loadError }}</p>
            <p v-else-if="loading" class="state-banner">Konten werden geladen…</p>
            <p v-else-if="filteredAccounts.length === 0" class="state-banner">Keine Konten im aktuellen Filter.</p>

            <div v-else class="accounts-list">
              <div
                v-for="account in filteredAccounts"
                :key="account.id"
                class="account-row"
                :class="{ active: selectedAccount?.id === account.id, archived: account.status === 'archived' }"
              >
                <div class="account-row-main">
                  <div class="account-row-topline">
                    <strong>{{ account.name }}</strong>
                    <div class="account-badge-row">
                      <span v-if="account.isDefault" class="account-badge badge-default">Standard</span>
                      <span v-if="account.allowSepaCollections" class="account-badge badge-sepa">SEPA</span>
                      <span class="account-badge" :class="`status-${account.status}`">{{ displayStatus(account.status) }}</span>
                    </div>
                  </div>
                  <p class="account-row-meta">
                    <span>{{ displayAccountType(account.accountType) }}</span>
                    <span>{{ displayUsageType(account.usageType) }}</span>
                    <span>{{ account.bankName || 'Ohne Bankname' }}</span>
                    <span>{{ displayIban(account.iban) }}</span>
                  </p>
                  <p class="account-row-description">{{ account.notes || 'Kein Hinweis hinterlegt.' }}</p>
                </div>
                <div class="account-row-actions">
                  <button type="button" class="btn-secondary" @click="selectAccount(account)">Bearbeiten</button>
                  <button type="button" class="btn-secondary" :disabled="!canEdit || account.status === 'archived'" @click="archiveAccount(account)">Archivieren</button>
                  <button type="button" class="btn-danger" :disabled="!canEdit" @click="deleteAccount(account)">Löschen</button>
                </div>
              </div>
            </div>
          </section>

          <section class="card accounts-list-card">
            <div class="section-header accounts-list-header">
              <h3>Kontobewegungen</h3>
              <button type="button" class="btn-secondary" :disabled="!canEdit || !selectedAccount" @click="resetTransactionForm">
                Neue Buchung
              </button>
            </div>

            <p v-if="!selectedAccount" class="state-banner">Bitte zuerst ein Konto auswählen.</p>
            <p v-else-if="selectedTransactions.length === 0" class="state-banner">Für dieses Konto gibt es noch keine Kontobewegungen.</p>

            <div v-else class="accounts-list">
              <div
                v-for="transaction in selectedTransactions"
                :key="transaction.id"
                class="account-row"
                :class="{ active: selectedTransaction?.id === transaction.id }"
              >
                <div class="account-row-main">
                  <div class="account-row-topline">
                    <strong>{{ transaction.reference || 'Manuelle Buchung' }}</strong>
                    <div class="account-badge-row">
                      <span class="account-badge" :class="`direction-${transaction.direction}`">{{ displayTransactionDirection(transaction.direction) }}</span>
                      <span class="account-badge" :class="`status-${transaction.status}`">{{ displayTransactionStatus(transaction.status) }}</span>
                      <span class="account-badge" :class="`booking-${transaction.bookingType}`">{{ displayBookingType(transaction.bookingType) }}</span>
                    </div>
                  </div>
                  <p class="account-row-meta">
                    <span>{{ transaction.bookingDate || 'Kein Buchungsdatum' }}</span>
                    <span>{{ formatTransactionAmount(transaction) }}</span>
                    <span v-if="transaction.invoiceId">Rechnung #{{ transaction.invoiceId }}</span>
                    <span v-if="transaction.paymentClaimId">Forderung #{{ transaction.paymentClaimId }}</span>
                  </p>
                  <p v-if="transaction.paymentClaim?.member" class="account-row-meta">
                    {{ displayPaymentClaimMember(transaction.paymentClaim.member) }}
                  </p>
                  <p class="account-row-description">{{ transaction.notes || 'Keine Notiz hinterlegt.' }}</p>
                </div>
                <div class="account-row-actions">
                  <button type="button" class="btn-secondary" @click="selectTransaction(transaction)">Bearbeiten</button>
                  <button type="button" class="btn-danger" :disabled="!canEdit || transaction.bookingType !== 'manual'" @click="deleteTransaction(transaction)">Löschen</button>
                </div>
              </div>
            </div>
          </section>
        </div>

        <aside class="accounts-side">
          <section class="card account-form-card">
            <div class="section-header">
              <h3>{{ form.id ? 'Konto bearbeiten' : 'Neues Konto' }}</h3>
            </div>
            <p v-if="!canEdit" class="state-banner">Lesemodus aktiv. Konten können geprüft, aber nicht bearbeitet werden.</p>

            <form class="account-form" @submit.prevent="submitAccount">
              <label>
                <span>Kontobezeichnung</span>
                <input v-model.trim="form.name" type="text" placeholder="z. B. Vereinskonto Sparkasse" :disabled="!canEdit" required />
              </label>

              <div class="account-form-grid">
                <label>
                  <span>Kontotyp</span>
                  <select v-model="form.accountType" :disabled="!canEdit">
                    <option value="bank">Bankkonto</option>
                    <option value="cash">Barkasse</option>
                    <option value="virtual">Virtuell</option>
                  </select>
                </label>
                <label>
                  <span>Verwendungszweck</span>
                  <select v-model="form.usageType" :disabled="!canEdit">
                    <option value="general">Allgemein</option>
                    <option value="membership_fees">Mitgliedsbeiträge</option>
                    <option value="donations">Spenden</option>
                    <option value="expenses">Ausgaben</option>
                    <option value="reserve">Rücklage</option>
                    <option value="petty_cash">Barkasse</option>
                  </select>
                </label>
              </div>

              <div class="account-form-grid">
                <label>
                  <span>Status</span>
                  <select v-model="form.status" :disabled="!canEdit">
                    <option value="active">Aktiv</option>
                    <option value="inactive">Inaktiv</option>
                    <option value="archived">Archiviert</option>
                  </select>
                </label>
                <label>
                  <span>Währung</span>
                  <input v-model.trim="form.currencyCode" type="text" maxlength="3" :disabled="!canEdit" />
                </label>
              </div>

              <label>
                <span>Kontoinhaber</span>
                <input v-model.trim="form.accountHolder" type="text" :disabled="!canEdit" />
              </label>
              <label>
                <span>Bankname</span>
                <input v-model.trim="form.bankName" type="text" :disabled="!canEdit" />
              </label>

              <div class="account-form-grid">
                <label>
                  <span>IBAN</span>
                  <input v-model.trim="form.iban" type="text" :disabled="!canEdit" />
                </label>
                <label>
                  <span>BIC</span>
                  <input v-model.trim="form.bic" type="text" :disabled="!canEdit" />
                </label>
              </div>

              <div class="account-check-grid">
                <label class="checkbox-row">
                  <input v-model="form.allowSepaCollections" type="checkbox" :disabled="!canEdit || form.accountType !== 'bank'" />
                  <span>Für SEPA-Einzüge verwenden</span>
                </label>
                <label class="checkbox-row">
                  <input v-model="form.allowOutgoingPayments" type="checkbox" :disabled="!canEdit" />
                  <span>Für Auszahlungen verwenden</span>
                </label>
                <label class="checkbox-row">
                  <input v-model="form.isDefault" type="checkbox" :disabled="!canEdit || form.status === 'archived'" />
                  <span>Als Standardkonto setzen</span>
                </label>
              </div>

              <label>
                <span>Interne Notiz</span>
                <textarea v-model.trim="form.notes" rows="5" :disabled="!canEdit" placeholder="z. B. nur für Beiträge oder Jugendkasse"></textarea>
              </label>

              <div class="account-form-actions">
                <button type="submit" class="btn-primary" :disabled="saving || !canEdit">{{ saving ? 'Speichert…' : 'Speichern' }}</button>
                <button type="button" class="btn-secondary" @click="resetForm">Zurücksetzen</button>
              </div>
            </form>
          </section>

          <section class="card account-form-card">
            <div class="section-header">
              <h3>{{ transactionForm.id ? 'Buchung bearbeiten' : 'Neue Buchung' }}</h3>
            </div>
            <p v-if="!canEdit" class="state-banner">Lesemodus aktiv. Kontobewegungen bleiben sichtbar, neue Buchungen sind gesperrt.</p>

            <form class="account-form" @submit.prevent="submitTransaction">
              <div class="account-form-grid">
                <label>
                  <span>Art</span>
                  <select v-model="transactionForm.direction" :disabled="!canEdit || transactionForm.bookingType !== 'manual'">
                    <option value="credit">Einnahme</option>
                    <option value="debit">Ausgabe</option>
                  </select>
                </label>
                <label>
                  <span>Status</span>
                  <select v-model="transactionForm.status" :disabled="!canEdit || transactionForm.bookingType !== 'manual'">
                    <option value="planned">Geplant</option>
                    <option value="booked">Gebucht</option>
                    <option value="cancelled">Storniert</option>
                  </select>
                </label>
              </div>

              <div class="account-form-grid">
                <label>
                  <span>Buchungsdatum</span>
                  <input v-model="transactionForm.bookingDate" type="date" :disabled="!canEdit || transactionForm.bookingType !== 'manual'" required />
                </label>
                <label>
                  <span>Wertstellung</span>
                  <input v-model="transactionForm.valueDate" type="date" :disabled="!canEdit || transactionForm.bookingType !== 'manual'" />
                </label>
              </div>

              <div class="account-form-grid">
                <label>
                  <span>Betrag (EUR)</span>
                  <input v-model.number="transactionForm.amountEuro" type="number" min="0" step="0.01" :disabled="!canEdit || transactionForm.bookingType !== 'manual'" required />
                </label>
                <label>
                  <span>Währung</span>
                  <input v-model.trim="transactionForm.currencyCode" type="text" maxlength="3" :disabled="!canEdit || transactionForm.bookingType !== 'manual'" />
                </label>
              </div>

              <label>
                <span>Forderung</span>
                <select v-model="transactionForm.paymentClaimId" :disabled="!canEdit || transactionForm.bookingType !== 'manual'">
                  <option value="">Ohne Zuordnung</option>
                  <option v-for="claim in openPaymentClaims" :key="claim.id" :value="String(claim.id)">
                    {{ displayPaymentClaimOption(claim) }}
                  </option>
                </select>
              </label>

              <label>
                <span>Referenz</span>
                <input v-model.trim="transactionForm.reference" type="text" :disabled="!canEdit || transactionForm.bookingType !== 'manual'" />
              </label>

              <label>
                <span>Notiz</span>
                <textarea v-model.trim="transactionForm.notes" rows="4" :disabled="!canEdit || transactionForm.bookingType !== 'manual'"></textarea>
              </label>

              <p v-if="transactionForm.bookingType !== 'manual'" class="detail-label">
                Diese Buchung wurde automatisch erzeugt und kann nicht manuell geändert werden.
              </p>

              <div class="account-form-actions">
                <button type="submit" class="btn-primary" :disabled="transactionSaving || !canEdit || !selectedAccount || transactionForm.bookingType !== 'manual'">
                  {{ transactionSaving ? 'Speichert…' : 'Buchung speichern' }}
                </button>
                <button type="button" class="btn-secondary" @click="resetTransactionForm">Zurücksetzen</button>
              </div>
            </form>
          </section>

          <section v-if="selectedAccount" class="card account-detail-card">
            <div class="section-header">
              <h3>Details</h3>
            </div>
            <div class="detail-stack">
              <div>
                <span class="detail-label">Name</span>
                <p>{{ selectedAccount.name }}</p>
              </div>
              <div>
                <span class="detail-label">Typ</span>
                <p>{{ displayAccountType(selectedAccount.accountType) }}</p>
              </div>
              <div>
                <span class="detail-label">Verwendung</span>
                <p>{{ displayUsageType(selectedAccount.usageType) }}</p>
              </div>
              <div>
                <span class="detail-label">IBAN</span>
                <p>{{ displayIban(selectedAccount.iban) }}</p>
              </div>
              <div>
                <span class="detail-label">Status</span>
                <p>{{ displayStatus(selectedAccount.status) }}</p>
              </div>
            </div>
          </section>
        </aside>
      </section>
    </template>

    <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"
      @confirm="handleConfirmResult(true)"
      @cancel="handleConfirmResult(false)"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import ConfirmDialog from '../components/ConfirmDialog.vue';
import InfoDialog from '../components/InfoDialog.vue';
import { buildConfirmConfig, buildInfoConfig, safeErrorMessage } from '../utils/dialogUtils.js';

function normalizeAccount(payload = {}) {
  return {
    id: payload.id,
    name: payload.name || '',
    accountHolder: payload.accountHolder || payload.account_holder || '',
    bankName: payload.bankName || payload.bank_name || '',
    iban: payload.iban || '',
    bic: payload.bic || '',
    accountType: payload.accountType || payload.account_type || 'bank',
    usageType: payload.usageType || payload.usage_type || 'general',
    currencyCode: payload.currencyCode || payload.currency_code || 'EUR',
    allowSepaCollections: Boolean(payload.allowSepaCollections ?? payload.allow_sepa_collections),
    allowOutgoingPayments: Boolean(payload.allowOutgoingPayments ?? payload.allow_outgoing_payments ?? true),
    isDefault: Boolean(payload.isDefault ?? payload.is_default),
    status: payload.status || 'active',
    notes: payload.notes || '',
    sortOrder: Number(payload.sortOrder ?? payload.sort_order ?? 0) || 0,
    archivedAt: payload.archivedAt || payload.archived_at || null,
  };
}

function normalizeTransaction(payload = {}) {
  return {
    id: payload.id,
    accountId: Number(payload.accountId || payload.account_id || 0) || null,
    invoiceId: Number(payload.invoiceId || payload.invoice_id || 0) || null,
    paymentClaimId: Number(payload.paymentClaimId || payload.payment_claim_id || 0) || null,
    paymentClaim: payload.paymentClaim || payload.payment_claim || null,
    direction: payload.direction || 'credit',
    bookingType: payload.bookingType || payload.booking_type || 'manual',
    status: payload.status || 'booked',
    bookingDate: payload.bookingDate || payload.booking_date || '',
    valueDate: payload.valueDate || payload.value_date || '',
    amountCents: Number(payload.amountCents || payload.amount_cents || 0),
    currencyCode: payload.currencyCode || payload.currency_code || 'EUR',
    reference: payload.reference || '',
    notes: payload.notes || '',
  };
}

function createEmptyTransactionForm(accountId = '') {
  return {
    id: null,
    accountId: accountId ? String(accountId) : '',
    direction: 'credit',
    bookingType: 'manual',
    status: 'booked',
    bookingDate: new Date().toISOString().slice(0, 10),
    valueDate: '',
    amountEuro: 0,
    currencyCode: 'EUR',
    paymentClaimId: '',
    reference: '',
    notes: '',
  };
}

function createEmptyAccountForm() {
  return {
    id: null,
    name: '',
    accountHolder: '',
    bankName: '',
    iban: '',
    bic: '',
    accountType: 'bank',
    usageType: 'general',
    currencyCode: 'EUR',
    allowSepaCollections: false,
    allowOutgoingPayments: true,
    isDefault: false,
    status: 'active',
    notes: '',
  };
}

export default {
  name: 'ClubAccountsView',
  components: {
    ConfirmDialog,
    InfoDialog,
  },
  data() {
    return {
      loading: false,
      saving: false,
      transactionSaving: false,
      loadError: '',
      accounts: [],
      transactions: [],
      paymentClaims: [],
      selectedAccountId: null,
      selectedTransactionId: null,
      filters: {
        status: '',
        accountType: '',
        search: '',
      },
      form: createEmptyAccountForm(),
      transactionForm: createEmptyTransactionForm(),
      infoDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'info',
      },
      confirmDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'warning',
        confirmText: '',
        cancelText: '',
        resolveCallback: null,
      },
    };
  },
  computed: {
    ...mapGetters(['currentClub', 'hasPermission']),
    canEdit() {
      return this.hasPermission('finance_accounts', 'write');
    },
    filteredAccounts() {
      const needle = this.filters.search.trim().toLowerCase();
      return this.accounts.filter((account) => {
        if (this.filters.status && account.status !== this.filters.status) return false;
        if (this.filters.accountType && account.accountType !== this.filters.accountType) return false;
        if (!needle) return true;
        return [account.name, account.bankName, account.iban].join(' ').toLowerCase().includes(needle);
      });
    },
    selectedAccount() {
      return this.accounts.find((account) => String(account.id) === String(this.selectedAccountId)) || null;
    },
    selectedTransactions() {
      return this.transactions.filter((transaction) => String(transaction.accountId) === String(this.selectedAccountId));
    },
    openPaymentClaims() {
      return this.paymentClaims.filter((claim) => ['open', 'partially_paid'].includes(claim.status));
    },
    selectedTransaction() {
      return this.selectedTransactions.find((transaction) => String(transaction.id) === String(this.selectedTransactionId)) || null;
    },
    defaultAccount() {
      return this.accounts.find((account) => account.isDefault && account.status !== 'archived') || null;
    },
    accountStats() {
      return {
        active: this.accounts.filter((account) => account.status === 'active').length,
        sepa: this.accounts.filter((account) => account.allowSepaCollections && account.status !== 'archived').length,
        outgoing: this.accounts.filter((account) => account.allowOutgoingPayments && account.status !== 'archived').length,
      };
    },
  },
  watch: {
    currentClub: {
      immediate: true,
      async handler(newClub) {
        if (!newClub) {
          this.clearAccountsState();
          return;
        }
        await this.loadAccounts();
      },
    },
    '$route.query': {
      immediate: true,
      handler() {
        this.applyRouteQuery();
      },
    },
    selectedAccount(account) {
      if (!account) {
        this.resetForm();
        return;
      }
      this.form = {
        id: account.id,
        name: account.name,
        accountHolder: account.accountHolder,
        bankName: account.bankName,
        iban: account.iban,
        bic: account.bic,
        accountType: account.accountType,
        usageType: account.usageType,
        currencyCode: account.currencyCode,
        allowSepaCollections: account.allowSepaCollections,
        allowOutgoingPayments: account.allowOutgoingPayments,
        isDefault: account.isDefault,
        status: account.status,
        notes: account.notes,
      };
      if (!this.transactionForm.accountId || this.transactionForm.accountId !== String(account.id)) {
        this.resetTransactionForm(account.id);
      }
    },
    selectedTransaction(transaction) {
      if (!transaction) {
        this.resetTransactionForm();
        return;
      }
      this.transactionForm = {
        id: transaction.id,
        accountId: transaction.accountId ? String(transaction.accountId) : '',
        direction: transaction.direction,
        bookingType: transaction.bookingType,
        status: transaction.status,
        bookingDate: transaction.bookingDate || '',
        valueDate: transaction.valueDate || '',
        amountEuro: Number(transaction.amountCents || 0) / 100,
        currencyCode: transaction.currencyCode || 'EUR',
        paymentClaimId: transaction.paymentClaimId ? String(transaction.paymentClaimId) : '',
        reference: transaction.reference || '',
        notes: transaction.notes || '',
      };
    },
  },
  methods: {
    clearAccountsState() {
      this.accounts = [];
      this.transactions = [];
      this.paymentClaims = [];
      this.selectedAccountId = null;
      this.selectedTransactionId = null;
      this.form = createEmptyAccountForm();
      this.transactionForm = createEmptyTransactionForm();
      this.loadError = '';
    },
    applyRouteQuery() {
      const routeAccountId = this.$route?.query?.accountId;
      const routeStatus = typeof this.$route?.query?.status === 'string' ? this.$route.query.status : '';
      if (['active', 'inactive', 'archived'].includes(routeStatus)) {
        this.filters.status = routeStatus;
      }
      if (routeAccountId && this.accounts.some((account) => String(account.id) === String(routeAccountId))) {
        this.selectedAccountId = String(routeAccountId);
      }
    },
    showInfo(title, message, details = '', type = 'info') {
      this.infoDialog = buildInfoConfig({ title, message, details, type });
    },
    async showConfirm(title, message, details = '', type = 'warning', options = {}) {
      return new Promise((resolve) => {
        this.confirmDialog = buildConfirmConfig({
          title,
          message,
          details,
          type,
          resolveCallback: resolve,
          ...options,
        });
      });
    },
    handleConfirmResult(confirmed) {
      if (this.confirmDialog.resolveCallback) {
        this.confirmDialog.resolveCallback(confirmed);
        this.confirmDialog.resolveCallback = null;
      }
      this.confirmDialog.isOpen = false;
    },
    displayStatus(status) {
      return {
        active: 'Aktiv',
        inactive: 'Inaktiv',
        archived: 'Archiviert',
      }[status] || status;
    },
    displayAccountType(accountType) {
      return {
        bank: 'Bankkonto',
        cash: 'Barkasse',
        virtual: 'Virtuell',
      }[accountType] || accountType;
    },
    displayUsageType(usageType) {
      return {
        general: 'Allgemein',
        membership_fees: 'Mitgliedsbeiträge',
        donations: 'Spenden',
        expenses: 'Ausgaben',
        reserve: 'Rücklage',
        petty_cash: 'Barkasse',
      }[usageType] || usageType;
    },
    displayTransactionDirection(direction) {
      return direction === 'debit' ? 'Ausgabe' : 'Einnahme';
    },
    displayTransactionStatus(status) {
      return {
        planned: 'Geplant',
        booked: 'Gebucht',
        cancelled: 'Storniert',
      }[status] || status;
    },
    displayBookingType(bookingType) {
      return {
        manual: 'Manuell',
        invoice: 'Rechnung',
        adjustment: 'Korrektur',
        payment_claim: 'Forderung',
      }[bookingType] || bookingType;
    },
    displayPaymentClaimMember(member) {
      return [member?.lastName, member?.firstName].filter(Boolean).join(', ') || member?.email || 'Mitglied';
    },
    displayIban(iban) {
      if (!iban) return 'Keine IBAN';
      return String(iban).replace(/(.{4})/g, '$1 ').trim();
    },
    formatTransactionAmount(transaction) {
      const amount = Number(transaction?.amountCents || 0) / 100;
      const signedAmount = transaction?.direction === 'debit' ? amount * -1 : amount;
      return new Intl.NumberFormat('de-DE', {
        style: 'currency',
        currency: transaction?.currencyCode || 'EUR',
      }).format(signedAmount);
    },
    selectAccount(account) {
      this.selectedAccountId = account.id;
    },
    selectTransaction(transaction) {
      this.selectedTransactionId = transaction.id;
    },
    resetForm() {
      this.selectedAccountId = null;
      this.form = createEmptyAccountForm();
      this.resetTransactionForm('');
    },
    resetTransactionForm(accountId = this.selectedAccountId || '') {
      this.selectedTransactionId = null;
      this.transactionForm = createEmptyTransactionForm(accountId);
    },
    async loadPaymentClaims() {
      if (!this.currentClub) {
        this.paymentClaims = [];
        return;
      }
      try {
        const response = await apiClient.get(`/club-payment-claims/${this.currentClub}`);
        this.paymentClaims = Array.isArray(response.data?.claims) ? response.data.claims : [];
      } catch (_error) {
        this.paymentClaims = [];
      }
    },
    async loadAccounts() {
      if (!this.currentClub) return;
      this.loading = true;
      this.loadError = '';
      try {
        const response = await apiClient.get(`/club-accounts/${this.currentClub}`);
        const entries = Array.isArray(response.data?.accounts) ? response.data.accounts : [];
        this.accounts = entries.map(normalizeAccount);
        this.transactions = Array.isArray(response.data?.transactions) ? response.data.transactions.map(normalizeTransaction) : [];
        await this.loadPaymentClaims();
        this.applyRouteQuery();
        if (this.selectedAccountId && !this.selectedAccount) {
          this.resetForm();
        }
        if (this.selectedTransactionId && !this.selectedTransaction) {
          this.resetTransactionForm();
        }
        if (!this.selectedAccountId && this.accounts.length > 0) {
          this.selectedAccountId = this.accounts[0].id;
        } else if (this.accounts.length === 0) {
          this.resetForm();
        }
      } catch (error) {
        this.loadError = safeErrorMessage(error, 'Konten konnten nicht geladen werden.');
      } finally {
        this.loading = false;
      }
    },
    async submitAccount() {
      if (!this.currentClub || !this.canEdit) return;
      this.saving = true;
      try {
        const payload = { ...this.form };
        let savedAccountId = this.form.id;
        if (this.form.id) {
          const response = await apiClient.put(`/club-accounts/${this.currentClub}/${this.form.id}`, payload);
          savedAccountId = response.data?.account?.id || savedAccountId;
        } else {
          const response = await apiClient.post(`/club-accounts/${this.currentClub}`, payload);
          savedAccountId = response.data?.account?.id || savedAccountId;
        }
        this.selectedAccountId = savedAccountId ? String(savedAccountId) : null;
        await this.loadAccounts();
        this.showInfo('Erfolg', 'Konto gespeichert.', '', 'success');
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Konto konnte nicht gespeichert werden.'), '', 'error');
      } finally {
        this.saving = false;
      }
    },
    async submitTransaction() {
      if (!this.currentClub || !this.canEdit || !this.selectedAccount) return;
      this.transactionSaving = true;
      try {
        const payload = {
          accountId: this.transactionForm.accountId || this.selectedAccount.id,
          direction: this.transactionForm.direction,
          bookingType: this.transactionForm.bookingType,
          status: this.transactionForm.status,
          bookingDate: this.transactionForm.bookingDate || null,
          valueDate: this.transactionForm.valueDate || null,
          amountCents: Math.round(Number(this.transactionForm.amountEuro || 0) * 100),
          currencyCode: this.transactionForm.currencyCode || 'EUR',
          paymentClaimId: this.transactionForm.paymentClaimId || null,
          reference: this.transactionForm.reference,
          notes: this.transactionForm.notes,
        };
        let savedTransactionId = this.transactionForm.id;
        if (this.transactionForm.id) {
          const response = await apiClient.put(`/club-accounts/${this.currentClub}/transactions/${this.transactionForm.id}`, payload);
          savedTransactionId = response.data?.transaction?.id || savedTransactionId;
        } else {
          const response = await apiClient.post(`/club-accounts/${this.currentClub}/transactions`, payload);
          savedTransactionId = response.data?.transaction?.id || savedTransactionId;
        }
        this.selectedTransactionId = savedTransactionId ? String(savedTransactionId) : null;
        await this.loadAccounts();
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Kontobewegung konnte nicht gespeichert werden.'), '', 'error');
      } finally {
        this.transactionSaving = false;
      }
    },
    async archiveAccount(account) {
      if (!account?.id || !this.canEdit) return;
      const confirmed = await this.showConfirm(
        'Konto archivieren',
        `Soll das Konto "${account.name}" archiviert werden?`,
        'Archivierte Konten bleiben zur Nachvollziehbarkeit erhalten.',
        'warning',
        { confirmText: 'Archivieren', cancelText: 'Abbrechen' }
      );
      if (!confirmed) return;

      try {
        await apiClient.patch(`/club-accounts/${this.currentClub}/${account.id}/status`, { status: 'archived' });
        await this.loadAccounts();
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Konto konnte nicht archiviert werden.'), '', 'error');
      }
    },
    async deleteAccount(account) {
      if (!account?.id || !this.canEdit) return;
      const confirmed = await this.showConfirm(
        'Konto löschen',
        `Soll das Konto "${account.name}" endgültig gelöscht werden?`,
        'Diese Aktion entfernt den Kontodatensatz vollständig.',
        'danger',
        { confirmText: 'Löschen', cancelText: 'Abbrechen' }
      );
      if (!confirmed) return;

      try {
        await apiClient.delete(`/club-accounts/${this.currentClub}/${account.id}`);
        if (this.selectedAccount?.id === account.id) {
          this.resetForm();
        }
        await this.loadAccounts();
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Konto konnte nicht gelöscht werden.'), '', 'error');
      }
    },
    async deleteTransaction(transaction) {
      if (!transaction?.id || !this.canEdit || transaction.bookingType !== 'manual') return;
      const confirmed = await this.showConfirm(
        'Kontobewegung löschen',
        `Soll die Buchung "${transaction.reference || 'Manuelle Buchung'}" gelöscht werden?`,
        '',
        'danger',
        { confirmText: 'Löschen', cancelText: 'Abbrechen' }
      );
      if (!confirmed) return;

      try {
        await apiClient.delete(`/club-accounts/${this.currentClub}/transactions/${transaction.id}`);
        if (this.selectedTransaction?.id === transaction.id) {
          this.resetTransactionForm();
        }
        await this.loadAccounts();
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Kontobewegung konnte nicht gelöscht werden.'), '', 'error');
      }
    },
    displayPaymentClaimOption(claim) {
      const member = claim?.member || {};
      const memberName = [member?.lastName, member?.firstName].filter(Boolean).join(', ') || `Forderung #${claim?.id || '?'}`;
      const remaining = Number(claim?.remainingAmountCents || claim?.amountCents || 0) / 100;
      return `${memberName} · ${new Intl.NumberFormat('de-DE', { style: 'currency', currency: claim?.currencyCode || 'EUR' }).format(remaining)} · ${claim?.dueOn || 'ohne Fälligkeit'}`;
    },
  },
};
</script>

<style scoped>
.club-accounts-page {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.page-header,
.empty-state,
.accounts-filter-card,
.accounts-list-card,
.account-form-card,
.account-detail-card {
  padding: 1.25rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  align-items: flex-start;
}

.page-eyebrow {
  margin: 0 0 0.35rem;
  color: var(--text-light);
  text-transform: uppercase;
  letter-spacing: 0.08em;
  font-size: 0.8rem;
}

.page-subtitle {
  margin: 0.35rem 0 0;
  color: var(--text-secondary);
}

.accounts-stats-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 1rem;
}

.stat-card {
  padding: 1rem 1.1rem;
}

.stat-label {
  display: block;
  color: var(--text-secondary);
  margin-bottom: 0.35rem;
}

.stat-value {
  font-size: 1.4rem;
}

.accounts-layout {
  display: grid;
  grid-template-columns: minmax(0, 1.5fr) minmax(320px, 0.9fr);
  gap: 1rem;
}

.accounts-main,
.accounts-side,
.account-form,
.detail-stack,
.accounts-list {
  display: grid;
  gap: 1rem;
}

.account-badge.direction-credit,
.account-badge.booking-manual {
  background: rgba(46, 125, 50, 0.12);
  color: #1f6d2b;
}

.account-badge.direction-debit,
.account-badge.booking-invoice {
  background: rgba(198, 40, 40, 0.12);
  color: #9a1d1d;
}

.account-badge.booking-adjustment,
.account-badge.status-planned {
  background: rgba(191, 144, 0, 0.12);
  color: #8b6a00;
}

.account-badge.status-cancelled {
  background: rgba(97, 97, 97, 0.12);
  color: #525252;
}

.accounts-filter-grid,
.account-form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 1rem;
}

.filter-search {
  grid-column: 1 / -1;
}

.accounts-list-header {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  align-items: center;
}

.account-row {
  border: 1px solid rgba(24, 70, 54, 0.14);
  border-radius: 16px;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  gap: 1rem;
}

.account-row.active {
  border-color: rgba(47, 122, 95, 0.6);
  box-shadow: 0 0 0 1px rgba(47, 122, 95, 0.14);
}

.account-row.archived {
  opacity: 0.75;
}

.account-row-main {
  display: grid;
  gap: 0.55rem;
  min-width: 0;
}

.account-row-topline,
.account-row-meta,
.account-badge-row,
.account-row-actions,
.account-check-grid,
.account-form-actions {
  display: flex;
  gap: 0.6rem;
  flex-wrap: wrap;
}

.account-row-topline {
  justify-content: space-between;
  align-items: center;
}

.account-row-meta,
.account-row-description {
  color: var(--text-secondary);
}

.account-badge {
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  padding: 0.2rem 0.55rem;
  font-size: 0.78rem;
  font-weight: 700;
}

.badge-default {
  background: rgba(47, 122, 95, 0.12);
  color: var(--primary-strong);
}

.badge-sepa {
  background: rgba(61, 118, 196, 0.12);
  color: #295b9c;
}

.status-active {
  background: rgba(47, 122, 95, 0.12);
  color: var(--primary-strong);
}

.status-inactive {
  background: rgba(160, 112, 64, 0.14);
  color: #8a5b1d;
}

.status-archived {
  background: rgba(120, 120, 120, 0.16);
  color: #5b5b5b;
}

.checkbox-row {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}

.detail-label {
  display: block;
  font-size: 0.82rem;
  color: var(--text-secondary);
  margin-bottom: 0.2rem;
}

.state-banner {
  margin: 0;
  color: var(--text-secondary);
}

@media (max-width: 960px) {
  .accounts-layout {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 720px) {
  .accounts-stats-grid,
  .accounts-filter-grid,
  .account-form-grid {
    grid-template-columns: 1fr;
  }

  .account-row {
    flex-direction: column;
  }
}
</style>
