<template>
  <div class="club-tasks-page">
    <header class="page-header card">
      <div>
        <p class="page-eyebrow">TT-Verein</p>
        <h2>Aufgaben</h2>
        <p class="page-subtitle">
          Aufgaben, Wiedervorlagen und Fristen für den täglichen Vereinsbetrieb in einer gemeinsamen Arbeitsfläche.
        </p>
      </div>
      <button type="button" class="btn-primary" :disabled="!canEdit" @click="resetForm">Neue Aufgabe</button>
    </header>

    <div v-if="!canEdit && currentClub" class="state-banner">
      Lesemodus aktiv. Aufgaben 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 Aufgaben zu verwalten.</p>
    </section>

    <template v-else>
      <section class="tasks-stats-grid">
        <article class="card stat-card">
          <span class="stat-label">Offen</span>
          <strong class="stat-value">{{ taskStats.open }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">In Bearbeitung</span>
          <strong class="stat-value">{{ taskStats.inProgress }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Überfällig</span>
          <strong class="stat-value">{{ taskStats.overdue }}</strong>
        </article>
        <article class="card stat-card">
          <span class="stat-label">Erledigt</span>
          <strong class="stat-value">{{ taskStats.done }}</strong>
        </article>
      </section>

      <section class="tasks-layout">
        <div class="tasks-main">
          <section class="card tasks-filter-card">
            <div class="tasks-filter-grid">
              <label>
                <span>Status</span>
                <select v-model="filters.status">
                  <option value="">Alle</option>
                  <option value="open">Offen</option>
                  <option value="in_progress">In Bearbeitung</option>
                  <option value="waiting">Wartend</option>
                  <option value="done">Erledigt</option>
                  <option value="cancelled">Abgebrochen</option>
                  <option value="archived">Archiviert</option>
                </select>
              </label>
              <label>
                <span>Priorität</span>
                <select v-model="filters.priority">
                  <option value="">Alle</option>
                  <option value="low">Niedrig</option>
                  <option value="normal">Normal</option>
                  <option value="high">Hoch</option>
                  <option value="urgent">Dringend</option>
                </select>
              </label>
              <label class="filter-search">
                <span>Suche</span>
                <input v-model.trim="filters.search" type="text" placeholder="Titel oder Beschreibung" />
              </label>
            </div>
          </section>

          <section class="card tasks-list-card">
            <div class="section-header tasks-list-header">
              <h3>Aufgabenliste</h3>
              <button type="button" class="btn-secondary" @click="loadTasks" :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">Aufgaben werden geladen…</p>
            <p v-else-if="filteredTasks.length === 0" class="state-banner">Keine Aufgaben im aktuellen Filter.</p>

            <div v-else class="tasks-list">
              <div
                v-for="task in filteredTasks"
                :key="task.id"
                class="task-row"
                :class="{ active: selectedTask?.id === task.id }"
              >
                <div class="task-row-main">
                  <div class="task-row-topline">
                    <strong>{{ task.title }}</strong>
                    <span class="task-status-badge" :class="`status-${task.status}`">{{ displayStatus(task.status) }}</span>
                  </div>
                  <p class="task-row-meta">
                    <span>{{ displayTaskType(task.taskType) }}</span>
                    <span :class="`priority-${task.priority}`">{{ displayPriority(task.priority) }}</span>
                    <span v-if="task.assignedUserLabel">{{ task.assignedUserLabel }}</span>
                    <span>{{ formatDateTime(task.dueAt) }}</span>
                    <span v-if="isOverdue(task)" class="task-overdue">Überfällig</span>
                  </p>
                  <p class="task-row-description">{{ task.description || 'Keine Beschreibung hinterlegt.' }}</p>
                </div>
                <div class="task-row-actions">
                  <button type="button" class="btn-secondary" @click="selectTask(task)">
                    Bearbeiten
                  </button>
                  <button
                    type="button"
                    class="btn-secondary"
                    @click="archiveTask(task)"
                    :disabled="!canEdit || task.status === 'archived'"
                  >
                    Archivieren
                  </button>
                  <button
                    type="button"
                    class="btn-danger"
                    :disabled="!canEdit"
                    @click="deleteTask(task)"
                  >
                    Löschen
                  </button>
                </div>
              </div>
            </div>
          </section>

          <section class="task-automation-layout">
            <article class="card task-suggestion-card">
              <div class="section-header">
                <h3>Automatische Vorschläge</h3>
              <div class="section-header-actions">
                  <button
                    type="button"
                    class="btn-secondary"
                    @click="showDefinitionsDialog = true"
                  >
                    Aufgabentypen
                  </button>
                  <button
                    type="button"
                    class="btn-secondary"
                    @click="materializeSuggestions(filteredSuggestions.map((suggestion) => suggestion.automationKey))"
                    :disabled="!canEdit || materializing || filteredSuggestions.length === 0"
                  >
                    {{ materializing ? 'Erstellt…' : 'Alle übernehmen' }}
                  </button>
                </div>
              </div>
              <p v-if="taskSuggestions.length === 0" class="state-banner">Aktuell gibt es keine automatischen Vorschläge.</p>
              <div v-else class="task-suggestion-list">
                <article v-for="suggestion in filteredSuggestions" :key="suggestion.automationKey" class="task-suggestion-item">
                  <div class="task-row-topline">
                    <strong>{{ suggestion.title }}</strong>
                    <span class="task-status-badge" :class="`status-${suggestion.priority}`">{{ displayPriority(suggestion.priority) }}</span>
                  </div>
                  <p class="task-row-description">{{ suggestion.description }}</p>
                  <p class="task-row-meta">
                    <span>{{ suggestion.definition?.label || suggestion.taskType }}</span>
                    <span v-if="suggestion.definition?.workflow">{{ suggestion.definition.workflow }}</span>
                    <span>{{ formatDateTime(suggestion.dueAt) }}</span>
                  </p>
                  <p v-if="suggestion.definition?.suggestedAction" class="task-suggestion-next-step">
                    Nächster Schritt: {{ suggestion.definition.suggestedAction }}
                  </p>
                  <button
                    type="button"
                    class="btn-secondary"
                    @click="materializeSuggestions([suggestion.automationKey])"
                    :disabled="!canEdit || materializing"
                  >
                    Vorschlag übernehmen
                  </button>
                  <button
                    type="button"
                    class="btn-secondary"
                    @click="dismissSuggestion(suggestion)"
                    :disabled="!canEdit || materializing"
                  >
                    Vorschlag ausblenden
                  </button>
                </article>
              </div>
            </article>
          </section>
        </div>

        <aside class="tasks-side">
          <section class="card task-form-card">
            <div class="section-header">
              <h3>{{ form.id ? 'Aufgabe bearbeiten' : 'Neue Aufgabe' }}</h3>
            </div>
            <p v-if="!canEdit" class="state-banner">Lesemodus aktiv. Aufgaben bleiben sichtbar, Änderungen am Formular sind gesperrt.</p>
            <form class="task-form" @submit.prevent="submitTask">
              <label>
                <span>Titel</span>
                <input v-model.trim="form.title" type="text" placeholder="Titel" :disabled="!canEdit" required />
              </label>
              <div class="task-form-grid">
                <label>
                  <span>Status</span>
                  <select v-model="form.status" :disabled="!canEdit">
                    <option value="open">Offen</option>
                    <option value="in_progress">In Bearbeitung</option>
                    <option value="waiting">Wartend</option>
                    <option value="done">Erledigt</option>
                    <option value="cancelled">Abgebrochen</option>
                    <option value="archived">Archiviert</option>
                  </select>
                </label>
                <label>
                  <span>Priorität</span>
                  <select v-model="form.priority" :disabled="!canEdit">
                    <option value="low">Niedrig</option>
                    <option value="normal">Normal</option>
                    <option value="high">Hoch</option>
                    <option value="urgent">Dringend</option>
                  </select>
                </label>
              </div>
              <div class="task-form-grid">
                <label>
                  <span>Fällig am</span>
                  <input v-model="form.dueAt" type="datetime-local" :disabled="!canEdit" />
                </label>
                <label>
                  <span>Erinnerung</span>
                  <input v-model="form.remindAt" type="datetime-local" :disabled="!canEdit" />
                </label>
              </div>
              <label>
                <span>Zuständig</span>
                <select v-model="form.assignedUserId" :disabled="!canEdit">
                  <option value="">Nicht zugewiesen</option>
                  <option v-for="user in assignableUsers" :key="user.userId" :value="String(user.userId)">
                    {{ user.label }}
                  </option>
                </select>
              </label>
              <label>
                <span>Beschreibung</span>
                <textarea v-model.trim="form.description" rows="5" placeholder="Beschreibung der Aufgabe" :disabled="!canEdit"></textarea>
              </label>
              <div class="task-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 task-detail-card">
            <div class="section-header">
              <h3>Aufgabenquellen</h3>
            </div>
            <div v-if="workflowSources.length" class="task-definition-list">
              <article v-for="source in workflowSources" :key="source.key" class="task-definition-item">
                <div class="task-definition-topline">
                  <strong>{{ source.label }}</strong>
                  <span class="task-definition-category">{{ source.key }}</span>
                </div>
                <p>{{ source.description }}</p>
              </article>
            </div>
            <p v-else class="state-banner">Noch keine Aufgabenquellen geladen.</p>
          </section>

          <section v-if="selectedTask" class="card task-detail-card">
            <div class="section-header">
              <h3>Details</h3>
            </div>
            <div class="detail-stack">
              <div>
                <span class="detail-label">Status</span>
                <select v-model="selectedTask.status" :disabled="!canEdit" @change="updateTaskStatus(selectedTask)">
                  <option value="open">Offen</option>
                  <option value="in_progress">In Bearbeitung</option>
                  <option value="waiting">Wartend</option>
                  <option value="done">Erledigt</option>
                  <option value="cancelled">Abgebrochen</option>
                  <option value="archived">Archiviert</option>
                </select>
              </div>
              <div>
                <span class="detail-label">Typ</span>
                <p>{{ displayTaskType(selectedTask.taskType) }}</p>
              </div>
              <div v-if="nextTaskLabelsFor(selectedTask).length">
                <span class="detail-label">Folgt danach</span>
                <p>{{ nextTaskLabelsFor(selectedTask).join(', ') }}</p>
              </div>
              <div>
                <span class="detail-label">Priorität</span>
                <p>{{ displayPriority(selectedTask.priority) }}</p>
              </div>
              <div>
                <span class="detail-label">Fälligkeit</span>
                <p>{{ formatDateTime(selectedTask.dueAt) }}</p>
              </div>
              <div>
                <span class="detail-label">Zuständig</span>
                <p>{{ selectedTask.assignedUserLabel || 'Nicht zugewiesen' }}</p>
              </div>
              <div>
                <span class="detail-label">Beschreibung</span>
                <p class="detail-message">{{ selectedTask.description || 'Keine Beschreibung hinterlegt.' }}</p>
              </div>
            </div>
            <div class="task-detail-actions">
              <button
                type="button"
                class="btn-secondary"
                @click="archiveSelectedTask"
                :disabled="!canEdit || selectedTask.status === 'archived'"
              >
                Archivieren
              </button>
              <button
                type="button"
                class="btn-danger"
                :disabled="!canEdit"
                @click="deleteSelectedTask"
              >
                Endgültig löschen
              </button>
            </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)"
    />

    <BaseDialog
      :model-value="showDefinitionsDialog"
      title="Definierte Aufgabentypen"
      size="large"
      :width="920"
      max-width="95vw"
      @update:model-value="showDefinitionsDialog = $event"
      @close="showDefinitionsDialog = false"
    >
      <div v-if="taskDefinitions.length" class="task-definition-list">
        <article v-for="definition in taskDefinitions" :key="definition.key" class="task-definition-item">
          <div class="task-definition-topline">
            <strong>{{ definition.label }}</strong>
            <span class="task-definition-category">{{ definition.category }}</span>
          </div>
          <p>{{ definition.description }}</p>
          <p v-if="definition.trigger" class="task-definition-meta"><strong>Auslöser:</strong> {{ definition.trigger }}</p>
          <p v-if="definition.suggestedAction" class="task-definition-meta"><strong>Nächster Schritt:</strong> {{ definition.suggestedAction }}</p>
          <p v-if="definition.nextTaskTypes?.length" class="task-definition-meta">
            <strong>Folgeschritt:</strong> {{ definition.nextTaskTypes.map(displayTaskType).join(', ') }}
          </p>
          <small>Quelle: {{ definition.source }}</small>
        </article>
      </div>
      <p v-else class="state-banner">Noch keine Aufgabentypen geladen.</p>
      <template #footer>
        <button type="button" class="btn-secondary" @click="showDefinitionsDialog = false">Schließen</button>
      </template>
    </BaseDialog>
  </div>
</template>

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

function toDateTimeLocal(value) {
  if (!value) return '';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  const timezoneOffset = date.getTimezoneOffset() * 60000;
  return new Date(date.getTime() - timezoneOffset).toISOString().slice(0, 16);
}

function normalizeTask(payload = {}) {
  return {
    id: payload.id,
    title: payload.title || '',
    taskType: payload.taskType || payload.task_type || null,
    description: payload.description || '',
    status: payload.status || 'open',
    priority: payload.priority || 'normal',
    dueAt: payload.dueAt || payload.due_at || null,
    remindAt: payload.remindAt || payload.remind_at || null,
    assignedUserId: payload.assignedUserId || payload.assigned_user_id || null,
    assignedUserLabel: payload.assignedUser?.email || payload.assignedUserLabel || '',
    completedAt: payload.completedAt || payload.completed_at || null,
    archivedAt: payload.archivedAt || payload.archived_at || null,
    createdAt: payload.createdAt || payload.created_at || null,
    updatedAt: payload.updatedAt || payload.updated_at || null,
  };
}

function createEmptyTaskForm() {
  return {
    id: null,
    title: '',
    description: '',
    status: 'open',
    priority: 'normal',
    dueAt: '',
    remindAt: '',
    assignedUserId: '',
  };
}

export default {
  name: 'ClubTasksView',
  components: {
    BaseDialog,
    ConfirmDialog,
    InfoDialog,
  },
  data() {
    return {
      loading: false,
      saving: false,
      materializing: false,
      loadError: '',
      tasks: [],
      taskDefinitions: [],
      taskSuggestions: [],
      workflowSources: [],
      assignableUsers: [],
      selectedTaskId: null,
      filters: {
        status: '',
        priority: '',
        search: '',
      },
      form: createEmptyTaskForm(),
      infoDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'info',
      },
      confirmDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'warning',
        confirmText: '',
        cancelText: '',
        resolveCallback: null,
      },
      showDefinitionsDialog: false,
    };
  },
  computed: {
    ...mapGetters(['currentClub', 'hasPermission']),
    canEdit() {
      return this.hasPermission('tasks', 'write');
    },
    filteredTasks() {
      const search = this.filters.search.trim().toLowerCase();
      return this.tasks.filter((task) => {
        if (this.filters.status && task.status !== this.filters.status) return false;
        if (this.filters.priority && task.priority !== this.filters.priority) return false;
        if (!search) return true;
        return [task.title, task.description].join(' ').toLowerCase().includes(search);
      });
    },
    filteredSuggestions() {
      return this.taskSuggestions.slice(0, 12);
    },
    selectedTask() {
      return this.tasks.find((task) => String(task.id) === String(this.selectedTaskId)) || null;
    },
    taskStats() {
      return {
        open: this.tasks.filter((task) => task.status === 'open').length,
        inProgress: this.tasks.filter((task) => task.status === 'in_progress').length,
        overdue: this.tasks.filter((task) => this.isOverdue(task)).length,
        done: this.tasks.filter((task) => task.status === 'done').length,
      };
    },
  },
  watch: {
    currentClub: {
      immediate: true,
      async handler(newClub) {
        if (!newClub) {
          this.clearTaskState();
          return;
        }
        await this.loadTasks();
      },
    },
    '$route.query': {
      immediate: true,
      handler() {
        this.applyRouteQuery();
      },
    },
    selectedTask(task) {
      if (!task) {
        this.resetForm();
        return;
      }
      this.form = {
        id: task.id,
        title: task.title,
        description: task.description,
        status: task.status,
        priority: task.priority,
        dueAt: toDateTimeLocal(task.dueAt),
        remindAt: toDateTimeLocal(task.remindAt),
        assignedUserId: task.assignedUserId ? String(task.assignedUserId) : '',
      };
    },
  },
  methods: {
    clearTaskState() {
      this.tasks = [];
      this.taskDefinitions = [];
      this.taskSuggestions = [];
      this.workflowSources = [];
      this.assignableUsers = [];
      this.selectedTaskId = null;
      this.form = createEmptyTaskForm();
      this.loadError = '';
    },
    normalizeAssignableUser(user = {}) {
      const email = typeof user.email === 'string' ? user.email.trim() : '';
      return {
        userId: user.userId || user.id || null,
        email,
        label: email || `Benutzer #${user.userId || user.id || 'unbekannt'}`,
      };
    },
    applyRouteQuery() {
      const routeStatus = typeof this.$route?.query?.status === 'string' ? this.$route.query.status : '';
      const routeTaskId = this.$route?.query?.taskId;

      if (['open', 'in_progress', 'waiting', 'done', 'cancelled', 'archived'].includes(routeStatus)) {
        this.filters.status = routeStatus;
      }

      if (routeTaskId && this.tasks.some((task) => String(task.id) === String(routeTaskId))) {
        this.selectedTaskId = String(routeTaskId);
      }
    },
    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;
    },
    displayTaskType(taskType) {
      const definition = this.taskDefinitions.find((entry) => entry.key === taskType);
      return definition?.label || taskType || 'Freie Aufgabe';
    },
    nextTaskLabelsFor(task) {
      if (!task?.taskType) return [];
      const definition = this.taskDefinitions.find((entry) => entry.key === task.taskType);
      const nextTaskTypes = Array.isArray(definition?.nextTaskTypes) ? definition.nextTaskTypes : [];
      return nextTaskTypes.map((taskType) => this.displayTaskType(taskType));
    },
    displayStatus(status) {
      return {
        open: 'Offen',
        in_progress: 'In Bearbeitung',
        waiting: 'Wartend',
        done: 'Erledigt',
        cancelled: 'Abgebrochen',
        archived: 'Archiviert',
      }[status] || status;
    },
    displayPriority(priority) {
      return {
        low: 'Niedrig',
        normal: 'Normal',
        high: 'Hoch',
        urgent: 'Dringend',
      }[priority] || priority;
    },
    formatDateTime(value) {
      if (!value) return '–';
      const date = new Date(value);
      if (Number.isNaN(date.getTime())) return '–';
      return new Intl.DateTimeFormat('de-DE', {
        dateStyle: 'medium',
        timeStyle: 'short',
      }).format(date);
    },
    isOverdue(task) {
      if (!task?.dueAt || ['done', 'cancelled', 'archived'].includes(task.status)) {
        return false;
      }
      return new Date(task.dueAt) < new Date();
    },
    selectTask(task) {
      this.selectedTaskId = task.id;
    },
    resetForm() {
      this.selectedTaskId = null;
      this.form = createEmptyTaskForm();
    },
    async loadTasks() {
      if (!this.currentClub) return;
      this.loading = true;
      this.loadError = '';
      try {
        const response = await apiClient.get(`/club-tasks/${this.currentClub}`);
        const entries = Array.isArray(response.data?.tasks)
          ? response.data.tasks
          : Array.isArray(response.data)
            ? response.data
            : [];
        this.taskDefinitions = Array.isArray(response.data?.taskDefinitions) ? response.data.taskDefinitions : [];
        this.taskSuggestions = Array.isArray(response.data?.taskSuggestions) ? response.data.taskSuggestions : [];
        this.workflowSources = Array.isArray(response.data?.workflowSources) ? response.data.workflowSources : [];
        this.assignableUsers = Array.isArray(response.data?.assignableUsers)
          ? response.data.assignableUsers
            .map((user) => this.normalizeAssignableUser(user))
            .filter((user) => user.userId)
          : [];
        this.tasks = entries.map(normalizeTask);
        this.applyRouteQuery();
        if (this.selectedTaskId && !this.selectedTask) {
          this.selectedTaskId = null;
        }
        if (!this.selectedTaskId && this.tasks.length > 0) {
          this.selectedTaskId = this.tasks[0].id;
        } else if (this.tasks.length === 0) {
          this.resetForm();
        }
      } catch (error) {
        this.loadError = safeErrorMessage(error, 'Aufgaben konnten nicht geladen werden.');
      } finally {
        this.loading = false;
      }
    },
    async submitTask() {
      if (!this.currentClub) return;
      this.saving = true;
      const payload = {
        title: this.form.title,
        taskType: this.form.id && this.selectedTask ? this.selectedTask.taskType : null,
        description: this.form.description,
        status: this.form.status,
        priority: this.form.priority,
        dueAt: this.form.dueAt || null,
        remindAt: this.form.remindAt || null,
        assignedUserId: this.form.assignedUserId || null,
      };
      try {
        let savedTaskId = this.form.id;
        if (this.form.id) {
          const response = await apiClient.put(`/club-tasks/${this.currentClub}/${this.form.id}`, payload);
          savedTaskId = response.data?.task?.id || savedTaskId;
        } else {
          const response = await apiClient.post(`/club-tasks/${this.currentClub}`, payload);
          savedTaskId = response.data?.task?.id || savedTaskId;
        }
        this.selectedTaskId = savedTaskId ? String(savedTaskId) : null;
        await this.loadTasks();
        this.showInfo('Erfolg', 'Aufgabe gespeichert.', '', 'success');
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Aufgabe konnte nicht gespeichert werden.'), '', 'error');
      } finally {
        this.saving = false;
      }
    },
    async updateTaskStatus(task) {
      if (!this.currentClub || !task?.id) return;
      try {
        const response = await apiClient.patch(`/club-tasks/${this.currentClub}/${task.id}/status`, {
          status: task.status,
        });
        await this.loadTasks();
        const followUpTasks = Array.isArray(response.data?.followUpTasks) ? response.data.followUpTasks : [];
        const sourceUpdate = response.data?.sourceUpdate || null;
        if (followUpTasks.length > 0 || sourceUpdate) {
          const messages = [];
          if (followUpTasks.length > 0) {
            messages.push(`${followUpTasks.length} Folgeaufgabe wurde automatisch angelegt.`);
          }
          if (sourceUpdate?.workflowStage) {
            messages.push(`Der Quellvorgang wurde auf Workflow-Stufe "${sourceUpdate.workflowStage}" gesetzt.`);
          }
          this.showInfo('Workflow fortgeschrieben', messages.join(' '), '', 'success');
        }
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Status konnte nicht aktualisiert werden.'), '', 'error');
      }
    },
    async archiveSelectedTask() {
      if (!this.selectedTask?.id || !this.currentClub) return;
      await this.archiveTask(this.selectedTask);
    },
    async archiveTask(task) {
      if (!task?.id || !this.currentClub) return;
      const confirmed = await this.showConfirm(
        'Aufgabe archivieren',
        `Soll die Aufgabe "${task.title}" archiviert werden?`,
        'Archivierte Aufgaben bleiben in der Historie und können über den Statusfilter wieder angezeigt werden.',
        'warning',
        { confirmText: 'Archivieren', cancelText: 'Abbrechen' }
      );
      if (!confirmed) return;

      try {
        await apiClient.patch(`/club-tasks/${this.currentClub}/${task.id}/status`, {
          status: 'archived',
        });
        if (this.selectedTask?.id === task.id) {
          this.resetForm();
        }
        await this.loadTasks();
        this.showInfo('Erfolg', 'Aufgabe wurde archiviert.', '', 'success');
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Aufgabe konnte nicht archiviert werden.'), '', 'error');
      }
    },
    async deleteSelectedTask() {
      if (!this.selectedTask?.id || !this.currentClub) return;
      await this.deleteTask(this.selectedTask);
    },
    async deleteTask(task) {
      if (!task?.id || !this.currentClub) return;
      const confirmed = await this.showConfirm(
        'Aufgabe löschen',
        `Soll die Aufgabe "${task.title}" endgültig gelöscht werden?`,
        'Diese Aktion entfernt die Aufgabe vollständig.',
        'danger',
        { confirmText: 'Endgültig löschen', cancelText: 'Abbrechen' }
      );
      if (!confirmed) return;

      try {
        await apiClient.delete(`/club-tasks/${this.currentClub}/${task.id}`);
        if (this.selectedTask?.id === task.id) {
          this.resetForm();
        }
        await this.loadTasks();
        this.showInfo('Erfolg', 'Aufgabe wurde gelöscht.', '', 'success');
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Aufgabe konnte nicht gelöscht werden.'), '', 'error');
      }
    },
    async materializeSuggestions(automationKeys) {
      if (!this.currentClub || !Array.isArray(automationKeys) || automationKeys.length === 0) return;
      this.materializing = true;
      try {
        await apiClient.post(`/club-tasks/${this.currentClub}/materialize`, {
          automationKeys,
        });
        await this.loadTasks();
        this.showInfo('Erfolg', 'Automatische Aufgaben wurden erstellt.', '', 'success');
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Automatische Aufgaben konnten nicht erstellt werden.'), '', 'error');
      } finally {
        this.materializing = false;
      }
    },
    async dismissSuggestion(suggestion) {
      if (!this.currentClub || !suggestion?.automationKey || !suggestion?.suppressionToken) return;
      const confirmed = await this.showConfirm(
        'Vorschlag ausblenden',
        `Soll der Vorschlag "${suggestion.title}" für den gesamten Verein ausgeblendet werden?`,
        'Der Vorschlag verschwindet für alle Benutzer. Bei relevanten Änderungen an den Quelldaten kann er später wieder erscheinen.',
        'warning',
        { confirmText: 'Ausblenden', cancelText: 'Abbrechen' }
      );
      if (!confirmed) return;

      this.materializing = true;
      try {
        await apiClient.post(`/club-tasks/${this.currentClub}/dismiss-suggestion`, {
          automationKey: suggestion.automationKey,
          suppressionToken: suggestion.suppressionToken,
        });
        await this.loadTasks();
      } catch (error) {
        this.showInfo('Fehler', safeErrorMessage(error, 'Vorschlag konnte nicht ausgeblendet werden.'), '', 'error');
      } finally {
        this.materializing = false;
      }
    },
  },
};
</script>

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

.page-header,
.empty-state,
.tasks-filter-card,
.tasks-list-card,
.task-form-card,
.task-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);
}

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

.task-automation-layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  gap: 1rem;
}

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

.task-definition-card,
.task-suggestion-card {
  padding: 1.25rem;
}

.task-definition-list,
.task-suggestion-list {
  display: grid;
  gap: 0.75rem;
}

.task-definition-item,
.task-suggestion-item {
  border: 1px solid rgba(24, 70, 54, 0.12);
  border-radius: 16px;
  padding: 0.95rem 1rem;
  background: rgba(255, 255, 255, 0.86);
}

.task-definition-topline {
  display: flex;
  justify-content: space-between;
  gap: 0.75rem;
  align-items: center;
  flex-wrap: wrap;
}

.task-definition-category {
  display: inline-flex;
  padding: 0.2rem 0.6rem;
  border-radius: 999px;
  background: rgba(24, 70, 54, 0.08);
  color: var(--primary-strong);
  font-size: 0.8rem;
  font-weight: 700;
}

.task-definition-meta,
.task-suggestion-next-step {
  margin: 0.35rem 0 0;
  color: var(--text-secondary);
}

.section-header-actions {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-wrap: wrap;
}

.stat-label {
  display: block;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.stat-value {
  display: block;
  margin-top: 0.35rem;
  font-size: 1.8rem;
}

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

.tasks-main,
.tasks-side {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

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

.filter-search {
  grid-column: span 2;
}

label {
  display: grid;
  gap: 0.35rem;
}

label span,
.detail-label {
  font-size: 0.9rem;
  color: var(--text-secondary);
}

input,
select,
textarea {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1rem;
}

.state-banner {
  margin: 0;
  padding: 0.85rem 1rem;
  border-radius: 12px;
  background: rgba(24, 70, 54, 0.06);
  color: var(--text-secondary);
}

.state-banner-error {
  background: rgba(178, 56, 56, 0.08);
  color: #a03b3b;
}

.tasks-list {
  display: grid;
  gap: 0.75rem;
}

.task-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
  width: 100%;
  text-align: left;
  border: 1px solid rgba(24, 70, 54, 0.12);
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.9);
  padding: 1rem;
}

.task-row-main {
  flex: 1;
}

.task-row-actions {
  display: flex;
  flex-direction: column;
  gap: 0.55rem;
  min-width: 132px;
}

.task-row.active {
  border-color: rgba(47, 122, 95, 0.42);
  box-shadow: 0 0 0 1px rgba(47, 122, 95, 0.15);
}

.task-row-topline,
.task-row-meta {
  display: flex;
  justify-content: space-between;
  gap: 0.75rem;
  flex-wrap: wrap;
}

.task-row-description {
  margin: 0.55rem 0 0;
  color: var(--text-secondary);
}

.task-status-badge {
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  padding: 0.2rem 0.65rem;
  font-size: 0.8rem;
  font-weight: 700;
}

.status-open {
  background: rgba(201, 152, 28, 0.14);
  color: #8a6510;
}

.status-in_progress {
  background: rgba(61, 118, 196, 0.14);
  color: #2e5f9e;
}

.status-waiting {
  background: rgba(122, 122, 122, 0.14);
  color: #575757;
}

.status-done {
  background: rgba(47, 122, 95, 0.14);
  color: #2b6f56;
}

.status-cancelled,
.status-archived {
  background: rgba(178, 56, 56, 0.12);
  color: #9c3d3d;
}

.status-low,
.status-normal,
.status-high,
.status-urgent {
  background: rgba(61, 118, 196, 0.1);
  color: #2e5f9e;
}

.status-urgent {
  background: rgba(178, 56, 56, 0.12);
  color: #9c3d3d;
}

.priority-low {
  color: #6e6e6e;
}

.priority-high {
  color: #a46816;
}

.priority-urgent {
  color: #a03b3b;
  font-weight: 700;
}

.task-overdue {
  color: #a03b3b;
  font-weight: 700;
}

.task-form,
.detail-stack {
  display: grid;
  gap: 0.85rem;
}

.task-form-actions {
  display: flex;
  gap: 0.75rem;
}

.task-detail-actions {
  display: flex;
  gap: 0.75rem;
  flex-wrap: wrap;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid rgba(24, 70, 54, 0.1);
}

.detail-message {
  white-space: pre-wrap;
}

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

  .tasks-stats-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 640px) {
  .page-header,
  .task-form-actions,
  .task-detail-actions {
    flex-direction: column;
  }

  .task-row {
    flex-direction: column;
  }

  .task-row-actions {
    width: 100%;
    min-width: 0;
  }

  .tasks-filter-grid,
  .task-form-grid,
  .tasks-stats-grid {
    grid-template-columns: 1fr;
  }

  .filter-search {
    grid-column: auto;
  }
}
</style>
