<template>
  <section class="team-planning-board">
    <div class="team-planning-head">
      <div>
        <h3>{{ t('teamManagement.planningTitle') }}</h3>
        <p>{{ t('teamManagement.planningSubtitle') }}</p>
      </div>
      <div class="team-planning-actions">
        <input
          :value="memberSearchQuery"
          type="search"
          class="team-search-input"
          :placeholder="t('teamManagement.searchMembers')"
          @input="$emit('update:member-search-query', $event.target.value)"
        >
        <button type="button" class="btn-secondary" @click="$emit('add-planning-team')">
          {{ t('teamManagement.addPlanningTeam') }}
        </button>
      </div>
    </div>

    <div class="team-planning-quick-assign">
      <select v-model="memberSortMode" class="planning-select planning-sort-select">
        <option value="firstLast">{{ t('teamManagement.sortFirstLast') }}</option>
        <option value="lastFirst">{{ t('teamManagement.sortLastFirst') }}</option>
      </select>
      <select v-model="selectedMemberId" class="planning-select">
        <option value="">{{ t('teamManagement.selectMember') }}</option>
        <option v-for="member in sortedSelectableMembers" :key="member.id" :value="String(member.id)">
          {{ formatMemberLabel(member) }}
        </option>
      </select>
      <button
        type="button"
        class="btn-secondary"
        :disabled="!selectedMemberId || markingInterest"
        @click="markSelectedMemberInterested"
      >
        {{ markingInterest ? t('common.saving') : t('teamManagement.markAsInterested') }}
      </button>
    </div>

    <div class="team-planning-grid">
      <TeamPlanningLane
        lane-id="pool"
        :title="t('teamManagement.playersWantToPlay')"
        :subtitle="t('teamManagement.playersPoolSubtitle')"
        :members="poolMembers"
        :show-actions="false"
        :empty-label="t('teamManagement.noMembersInPool')"
        @drag-start="$emit('drag-member', $event)"
      />

      <div class="team-planning-teams">
        <article v-for="team in plannedTeams" :key="team.id" class="team-planning-team-card">
          <div class="team-planning-team-head">
            <input
              :value="team.name"
              type="text"
              class="planning-team-name-input"
              :placeholder="t('teamManagement.teamName')"
              @input="$emit('update-team-field', team.id, 'name', $event.target.value)"
            >
            <button
              type="button"
              class="btn-secondary planning-team-open-button"
              :title="t('teamManagement.openInWorkspace')"
              :aria-label="t('teamManagement.openInWorkspace')"
              @click="$emit('convert-planning-team', team.id)"
            >
              ↗
            </button>
            <button type="button" class="btn-secondary btn-upload-sm" @click="$emit('remove-planning-team', team.id)">×</button>
          </div>
          <div v-if="getTeamStatusLabel(team.id)" class="planning-team-status" :class="`state-${getTeamStatusState(team.id)}`">
            {{ getTeamStatusLabel(team.id) }}
          </div>
          <div class="planning-team-meta-grid">
            <label class="planning-team-field">
              <span>{{ t('teamManagement.teamAgeGroup') }}</span>
              <select
                :value="team.teamAgeGroup || 'adult'"
                class="planning-select"
                @change="$emit('update-team-field', team.id, 'teamAgeGroup', $event.target.value)"
              >
                <option v-for="option in teamAgeGroupOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </label>
            <label class="planning-team-field">
              <span>{{ t('teamManagement.teamGender') }}</span>
              <select
                :value="team.teamGender || 'open'"
                class="planning-select"
                @change="$emit('update-team-field', team.id, 'teamGender', $event.target.value)"
              >
                <option v-for="option in teamGenderOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </label>
          </div>
          <label class="planning-team-field">
            <span>{{ t('teamManagement.plannedLeague') }}</span>
            <input
              :value="team.plannedLeagueName || ''"
              type="text"
              class="planning-team-league-input"
              :placeholder="t('teamManagement.plannedLeaguePlaceholder')"
              @input="$emit('update-team-field', team.id, 'plannedLeagueName', $event.target.value)"
            >
          </label>
          <TeamPlanningLane
            :lane-id="team.id"
            :title="team.name || t('teamManagement.teamName')"
            :subtitle="team.plannedLeagueName || t('teamManagement.noPlannedLeague')"
            :members="team.members"
            :empty-label="t('teamManagement.lineupEmpty')"
            @drop-member="$emit('drop-member-to-team', $event)"
            @drag-start="$emit('drag-member', $event)"
            @move-member="$emit('move-member-inside-team', $event)"
            @remove-member="$emit('remove-member-from-team', $event)"
          />
        </article>
      </div>

      <TeamPlanningLane
        lane-id="unassigned"
        :title="t('teamManagement.unassignedMembers')"
        :subtitle="t('teamManagement.unassignedMembersSubtitle')"
        :members="unassignedMembers"
        :empty-label="t('teamManagement.allMembersAssigned')"
        @drop-member="$emit('drop-member-to-unassigned')"
        @drag-start="$emit('drag-member', $event)"
      />
    </div>
  </section>
</template>

<script>
import TeamPlanningLane from './TeamPlanningLane.vue';

export default {
  name: 'TeamPlanningBoard',
  components: { TeamPlanningLane },
  props: {
    t: { type: Function, required: true },
    poolMembers: { type: Array, required: true },
    selectableMembers: { type: Array, default: () => [] },
    plannedTeams: { type: Array, required: true },
    teamAgeGroupOptions: { type: Array, default: () => [] },
    teamGenderOptions: { type: Array, default: () => [] },
    teamSaveStatusMap: { type: Object, default: () => ({}) },
    unassignedMembers: { type: Array, required: true },
    memberSearchQuery: { type: String, required: true },
    markingInterest: { type: Boolean, default: false }
  },
  data() {
    return {
      selectedMemberId: '',
      memberSortMode: 'firstLast'
    };
  },
  computed: {
    sortedSelectableMembers() {
      const source = this.selectableMembers.length ? this.selectableMembers : this.poolMembers;
      const normalized = [...source];
      const collator = new Intl.Collator('de', { sensitivity: 'base' });
      const getFirstName = (member) => String(member?.firstName ?? member?.firstname ?? '').trim();
      const getLastName = (member) => String(member?.lastName ?? member?.lastname ?? '').trim();

      if (this.memberSortMode === 'lastFirst') {
        return normalized.sort((a, b) => {
          const byLast = collator.compare(getLastName(a), getLastName(b));
          if (byLast !== 0) return byLast;
          const byFirst = collator.compare(getFirstName(a), getFirstName(b));
          if (byFirst !== 0) return byFirst;
          return Number(a?.id || 0) - Number(b?.id || 0);
        });
      }
      return normalized.sort((a, b) => {
        const byFirst = collator.compare(getFirstName(a), getFirstName(b));
        if (byFirst !== 0) return byFirst;
        const byLast = collator.compare(getLastName(a), getLastName(b));
        if (byLast !== 0) return byLast;
        return Number(a?.id || 0) - Number(b?.id || 0);
      });
    }
  },
  emits: [
    'update:member-search-query',
    'add-planning-team',
    'drag-member',
    'drop-member-to-team',
    'drop-member-to-unassigned',
    'move-member-inside-team',
    'remove-member-from-team',
    'update-team-field',
    'remove-planning-team',
    'convert-planning-team',
    'mark-member-interested'
  ],
  methods: {
    formatMemberLabel(member) {
      const firstName = String(member?.firstName ?? member?.firstname ?? '').trim();
      const lastName = String(member?.lastName ?? member?.lastname ?? '').trim();
      if (this.memberSortMode === 'lastFirst') {
        return [lastName, firstName].filter(Boolean).join(', ');
      }
      return [firstName, lastName].filter(Boolean).join(' ');
    },
    getTeamStatusState(teamId) {
      return this.teamSaveStatusMap?.[String(teamId)]?.state || '';
    },
    getTeamStatusLabel(teamId) {
      const state = this.getTeamStatusState(teamId);
      if (state === 'saving') return this.t('common.saving');
      if (state === 'saved') return this.t('teamManagement.autoSaved');
      if (state === 'error') return this.t('teamManagement.autoSaveError');
      return '';
    },
    markSelectedMemberInterested() {
      if (!this.selectedMemberId) return;
      this.$emit('mark-member-interested', {
        memberId: this.selectedMemberId
      });
      this.selectedMemberId = '';
    }
  }
};
</script>

<style scoped>
.team-planning-board {
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--background-light);
  padding: 0.9rem;
}

.team-planning-head {
  display: flex;
  justify-content: space-between;
  gap: 0.9rem;
  align-items: flex-start;
  margin-bottom: 0.85rem;
}

.team-planning-head h3 {
  margin: 0;
}

.team-planning-head p {
  margin: 0.2rem 0 0;
  color: var(--text-muted);
}

.team-planning-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
}

.team-planning-grid {
  display: grid;
  grid-template-columns: minmax(220px, 1fr) minmax(340px, 2fr) minmax(220px, 1fr);
  gap: 0.8rem;
}

.team-planning-quick-assign {
  display: grid;
  grid-template-columns: minmax(190px, 0.8fr) minmax(260px, 1.3fr) auto;
  gap: 0.5rem;
  margin-bottom: 0.85rem;
}

.planning-select {
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-small);
  padding: 0.45rem 0.55rem;
  background: var(--surface-color);
  color: var(--text-color);
}

.team-planning-teams {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 0.7rem;
}

.team-planning-team-card {
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  padding: 0.7rem;
  display: flex;
  flex-direction: column;
  gap: 0.55rem;
}

.team-planning-team-head {
  display: flex;
  gap: 0.45rem;
  align-items: center;
}

.planning-team-meta-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem;
}

.planning-team-field {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.planning-team-field > span {
  font-size: 0.82rem;
  color: var(--text-muted);
}

.planning-team-status {
  font-size: 0.78rem;
  color: var(--text-muted);
  min-height: 1rem;
}

.planning-team-status.state-error {
  color: #b42318;
}

.planning-team-name-input,
.planning-team-league-input {
  width: auto;
  min-width: 0;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-small);
  padding: 0.4rem 0.55rem;
}

.planning-team-name-input {
  flex: 1 1 auto;
}

.planning-team-open-button {
  flex: 0 0 auto;
  white-space: nowrap;
  padding: 0.4rem 0.6rem;
  border: 1px solid var(--primary-color);
  background: rgba(47, 122, 95, 0.12);
  color: var(--primary-dark, #1f5f49) !important;
  font-weight: 700;
  border-radius: 10px;
}

.planning-team-open-button:hover {
  background: rgba(47, 122, 95, 0.18);
}

@media (max-width: 1200px) {
  .team-planning-quick-assign {
    grid-template-columns: 1fr;
  }

  .team-planning-grid {
    grid-template-columns: 1fr;
  }

  .planning-team-meta-grid {
    grid-template-columns: 1fr;
  }
}
</style>
