<template>
  <div class="codev-carto">

    <header class="carto-header">
      <h1>Carto entraide</h1>
      <p class="carto-subtitle">
        <template v-if="pending">Chargement...</template>
        <template v-else>
          {{ fiches.length }} fiche{{ fiches.length !== 1 ? 's' : '' }} - clique sur un nom pour voir le detail
        </template>
      </p>
      <NuxtLink to="/codev/qr" class="qr-link" title="QR Code">[ QR ]</NuxtLink>
    </header>

    <div class="codev-tabs">
      <button :class="{ active: tab === 'carto' }" @click="tab = 'carto'" type="button">Carto</button>
      <button :class="{ active: tab === 'annuaire' }" @click="tab = 'annuaire'" type="button">Annuaire</button>
    </div>

    <div v-if="tab === 'carto'">
      <div class="show-labels-bar">
        <button
          type="button"
          :class="{ active: showLabels }"
          @click="showLabels = !showLabels"
        >
          {{ showLabels ? 'Masquer besoins/offres' : 'Montrer besoins/offres' }}
        </button>
      </div>

      <ClientOnly>
        <CodevGraph
          :fiches="fiches"
          :matches="matches"
          :mode="mode"
          :show-labels="showLabels"
          @select-fiche="onSelectFiche"
        />
        <template #fallback>
          <div class="graph-fallback">Chargement du graphe...</div>
        </template>
      </ClientOnly>

      <!-- Bandeau info mode actif -->
      <div v-if="mode !== 'none'" class="mode-banner">
        <span>
          Mode {{ MODE_LABELS[mode] }} actif -
          {{ matches.length }} connexion{{ matches.length !== 1 ? 's' : '' }} trouvee{{ matches.length !== 1 ? 's' : '' }}.
        </span>
        <button class="banner-clear" @click="setMode('none')" type="button">Effacer</button>
      </div>

      <!-- Boutons matching -->
      <div class="matching-controls">
        <button
          :class="{ active: mode === 'solution' }"
          style="--mode-color: #22c55e"
          @click="setMode('solution')"
          type="button"
        >
          Solution
          <span class="hint">besoin - compétence</span>
        </button>
        <button
          :class="{ active: mode === 'alliance' }"
          style="--mode-color: #f97316"
          @click="setMode('alliance')"
          type="button"
        >
          Alliance
          <span class="hint">besoins partagés</span>
        </button>
        <button
          v-if="mode !== 'none'"
          class="reset"
          @click="setMode('none')"
          type="button"
        >
          Effacer
        </button>
      </div>
    </div>

    <div v-else-if="tab === 'annuaire'" class="annuaire-wrap">

      <div v-if="fiches.length === 0" class="list-empty">
        Aucune fiche. <NuxtLink to="/codev/fiche">Ajouter la mienne</NuxtLink>
      </div>

      <div v-else class="annuaire-scroll">
        <table class="annuaire-table">
          <thead>
            <tr>
              <th class="col-nom">Prénom</th>
              <th class="col-besoin">Besoin</th>
              <th class="col-offre">Ce que j'offre</th>
              <th v-if="isAdmin" class="col-actions"></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="f in fiches" :key="f.id" @click="navigateTo(`/codev/fiche?id=${f.id}`)" class="annuaire-row">
              <td class="col-nom">{{ f.nom }}</td>
              <td class="col-besoin">{{ f.besoin }}</td>
              <td class="col-offre">{{ f.offre }}</td>
              <td v-if="isAdmin" class="col-actions">
                <button @click.stop="deleteFiche(f.id)" class="delete-btn" type="button" title="Supprimer">✕</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <p class="annuaire-hint">Clique sur une ligne pour modifier la fiche</p>
    </div>

    <!-- FAB ajouter une fiche -->
    <NuxtLink to="/codev/fiche" class="fab-add" title="Ajouter ma fiche" aria-label="Ajouter une fiche">
      +
    </NuxtLink>

    <Transition name="sheet">
      <div v-if="selectedFiche" class="bottom-sheet" @click.self="selectedFiche = null">
        <div class="sheet-content">
          <div class="sheet-handle"></div>
          <div class="sheet-name">{{ selectedFiche.nom }}</div>
          <div class="sheet-section">
            <span class="sheet-label">Besoin</span>
            <p class="sheet-text">{{ selectedFiche.besoin }}</p>
          </div>
          <div class="sheet-section">
            <span class="sheet-label">Ce que j'apporte</span>
            <p class="sheet-text">{{ selectedFiche.offre }}</p>
          </div>
          <div class="sheet-tags" v-if="selectedFiche.hashtags.length">
            <span v-for="t in selectedFiche.hashtags" :key="t" class="sheet-tag">#{{ t }}</span>
          </div>
          <NuxtLink :to="`/codev/fiche?id=${selectedFiche.id}`" class="sheet-edit-btn">Modifier cette fiche</NuxtLink>
          <button class="sheet-close" @click="selectedFiche = null" type="button">Fermer</button>
        </div>
      </div>
    </Transition>

  </div>
</template>

<script setup lang="ts">
import type { CodevFiche, CodevMatch } from '~/types/codev'
import { computeMatches } from '~/utils/codev/matching'

useHead({ title: 'Carto - Co-developpement' })

const { data, pending, refresh } = await useFetch<{ list: CodevFiche[] }>('/api/codev/fiches')
const fiches = computed(() => data.value?.list ?? [])

const matches = ref<CodevMatch[]>([])
const mode = ref<'none' | 'solution' | 'alliance' | 'surprise'>('none')
const showLabels = ref(false)
const tab = ref<'carto' | 'annuaire'>('carto')
const selectedFiche = ref<CodevFiche | null>(null)
const isMobileView = typeof window !== 'undefined' ? window.innerWidth < 600 : false

const isAdmin = ref(false)

onMounted(async () => {
  try {
    const r = await $fetch<{ admin: boolean }>('/api/codev/me')
    isAdmin.value = r.admin
  } catch { isAdmin.value = false }
})

const MODE_LABELS: Record<string, string> = {
  solution: 'Solution',
  alliance: 'Alliance',
  surprise: 'Surprise',
}

function setMode(newMode: 'none' | 'solution' | 'alliance' | 'surprise') {
  mode.value = newMode
  if (newMode === 'none') {
    matches.value = []
  } else {
    matches.value = computeMatches(fiches.value, newMode)
  }
}

function onSelectFiche(id: number) {
  if (isMobileView) {
    selectedFiche.value = fiches.value.find(f => f.id === id) ?? null
  } else {
    navigateTo(`/codev/fiche?id=${id}`)
  }
}

async function deleteFiche(id: number) {
  if (!confirm('Supprimer la fiche ?')) return
  await $fetch(`/api/codev/fiches/${id}`, { method: 'DELETE' })
  await refresh()
}
</script>

<style scoped>
.codev-carto {
  min-height: 100vh;
  background: var(--nav-bg, #fafafa);
  display: flex;
  flex-direction: column;
  padding: 1.25rem 1rem 2rem;
  gap: 1rem;
  max-width: 100%;
  box-sizing: border-box;
}

/* ── En-tete ── */

.carto-header {
  text-align: center;
  padding-bottom: 0.5rem;
}

.carto-header h1 {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--nav-text, #1a1a2e);
  margin: 0 0 0.375rem;
}

.carto-subtitle {
  font-size: 0.9rem;
  color: var(--nav-text-muted, #6b7280);
  margin: 0;
}

/* ── Fallback ── */

.graph-fallback {
  width: 100%;
  height: 70vh;
  min-height: 320px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--nav-text-muted, #6b7280);
  font-size: 0.9rem;
  background: var(--nav-bg-alt, #f3f4f6);
  border-radius: 12px;
}

/* ── Bandeau mode actif ── */

.mode-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.75rem;
  padding: 0.5rem 0.875rem;
  background: #f0fdf4;
  border: 1px solid #bbf7d0;
  border-radius: 8px;
  font-size: 0.875rem;
  color: #166534;
  flex-wrap: wrap;
}

.banner-clear {
  font-size: 0.8rem;
  font-weight: 600;
  color: #166534;
  background: transparent;
  border: 1px solid #166534;
  border-radius: 6px;
  padding: 0.2rem 0.6rem;
  cursor: pointer;
  white-space: nowrap;
}

.banner-clear:hover {
  background: #166534;
  color: #fff;
}

/* ── Boutons matching ── */

.matching-controls {
  position: sticky;
  bottom: 0;
  display: flex;
  gap: 8px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
  border-top: 1px solid #e5e7eb;
  margin: 0 -1rem -2rem;
}

.matching-controls button {
  flex: 1;
  padding: 12px 8px;
  border: 1px solid #d0d4dc;
  border-radius: 8px;
  background: white;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  transition: background 0.15s, color 0.15s, border-color 0.15s;
}

.matching-controls button .hint {
  font-size: 11px;
  color: #6b7280;
  font-weight: normal;
}

.matching-controls button.active {
  background: var(--mode-color, #1B4436);
  color: white;
  border-color: transparent;
}

.matching-controls button.active .hint {
  color: rgba(255, 255, 255, 0.8);
}

.matching-controls button.reset {
  flex: 0 0 auto;
  padding: 12px 16px;
  background: #f3f4f6;
  border-color: #d0d4dc;
  color: #374151;
  font-size: 13px;
}

.matching-controls button.reset:hover {
  background: #e5e7eb;
}

@media (max-width: 500px) {
  .matching-controls {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    margin: 0 -0.75rem -1.5rem;
  }

  .matching-controls button.reset {
    grid-column: span 2;
  }
}

/* ── Toggle besoins/offres ── */

.show-labels-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 8px;
}

.show-labels-bar button {
  border: 1px solid #d0d4dc;
  border-radius: 8px;
  padding: 8px 16px;
  background: white;
  font-size: 13px;
  cursor: pointer;
  color: #374151;
  transition: background 0.15s, color 0.15s, border-color 0.15s;
}

.show-labels-bar button.active {
  background: #1B4436;
  color: white;
  border-color: transparent;
}

/* ── FAB ajouter ── */

.fab-add {
  position: fixed;
  bottom: 80px;
  right: 16px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #1B4436;
  color: white;
  font-size: 28px;
  font-weight: 300;
  display: flex;
  align-items: center;
  justify-content: center;
  text-decoration: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.18);
  z-index: 100;
  transition: transform 0.15s, opacity 0.15s;
  line-height: 1;
}

.fab-add:hover {
  transform: scale(1.08);
  opacity: 0.92;
}

/* ── Tabs ── */

.codev-tabs { display: flex; gap: 4px; background: #f3f4f6; border-radius: 10px; padding: 4px; }
.codev-tabs button { flex: 1; padding: 8px 4px; border: none; border-radius: 7px; background: transparent; font-size: 0.875rem; font-weight: 500; cursor: pointer; color: #6b7280; transition: all 0.15s; }
.codev-tabs button.active { background: white; color: #1a1a2e; font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }

/* ── List view ── */

.list-view { display: flex; flex-direction: column; gap: 12px; padding: 8px 0; }
.list-card { background: white; border: 1px solid #e5e7eb; border-radius: 10px; padding: 14px 16px; display: flex; flex-direction: column; gap: 6px; }
.list-card-name { font-weight: 700; font-size: 0.95rem; color: #1a1a2e; }
.list-card-text { font-size: 0.875rem; color: #4b5563; margin: 0; line-height: 1.5; }
.list-card-link { font-size: 0.8rem; color: #1B4436; text-decoration: none; align-self: flex-end; }
.list-empty { text-align: center; color: #6b7280; font-size: 0.9rem; }

/* ── Bottom sheet ── */

.bottom-sheet { position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 200; display: flex; align-items: flex-end; }
.sheet-content { background: white; border-radius: 16px 16px 0 0; padding: 16px 20px 32px; width: 100%; display: flex; flex-direction: column; gap: 12px; max-height: 80vh; overflow-y: auto; }
.sheet-handle { width: 36px; height: 4px; background: #d1d5db; border-radius: 2px; align-self: center; margin-bottom: 4px; }
.sheet-name { font-size: 1.1rem; font-weight: 700; color: #1a1a2e; }
.sheet-section { display: flex; flex-direction: column; gap: 4px; }
.sheet-label { font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; }
.sheet-text { font-size: 0.9rem; color: #374151; margin: 0; line-height: 1.5; }
.sheet-tags { display: flex; flex-wrap: wrap; gap: 6px; }
.sheet-tag { font-size: 0.75rem; background: #f3f4f6; color: #374151; padding: 2px 8px; border-radius: 12px; }
.sheet-edit-btn { display: block; text-align: center; background: #1B4436; color: white; border-radius: 8px; padding: 12px; text-decoration: none; font-weight: 600; }
.sheet-close { background: transparent; border: 1px solid #d1d5db; border-radius: 8px; padding: 10px; color: #6b7280; cursor: pointer; font-size: 0.875rem; }
.sheet-enter-active, .sheet-leave-active { transition: opacity 0.2s; }
.sheet-enter-from, .sheet-leave-to { opacity: 0; }

/* ── QR link ── */

.qr-link {
  font-size: 0.75rem;
  color: #9ca3af;
  text-decoration: none;
  align-self: flex-end;
}
.qr-link:hover { color: #6b7280; }

/* ── Annuaire ── */

.annuaire-wrap {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.annuaire-scroll {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
}

.annuaire-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 480px;
}

.annuaire-table thead tr {
  background: #f9fafb;
  border-bottom: 2px solid #e5e7eb;
}

.annuaire-table th {
  padding: 10px 14px;
  text-align: left;
  font-size: 0.75rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: #6b7280;
  white-space: nowrap;
}

.annuaire-table td {
  padding: 12px 14px;
  font-size: 0.875rem;
  color: #374151;
  vertical-align: top;
  border-bottom: 1px solid #f3f4f6;
  line-height: 1.5;
}

.annuaire-row {
  cursor: pointer;
  transition: background 0.12s;
}

.annuaire-row:hover { background: #f9fafb; }
.annuaire-row:last-child td { border-bottom: none; }

.col-nom {
  position: sticky;
  left: 0;
  z-index: 2;
  background: #ffffff;
  font-weight: 600;
  color: #1a1a2e !important;
  white-space: nowrap;
  min-width: 80px;
  border-right: 2px solid #e5e7eb;
  box-shadow: 2px 0 6px rgba(0,0,0,0.06);
}

.annuaire-row:hover .col-nom { background: #f9fafb; }
thead tr .col-nom { background: #f9fafb; z-index: 3; }

.col-besoin { min-width: 200px; max-width: 260px; }
.col-offre  { min-width: 200px; max-width: 260px; }

.annuaire-hint {
  font-size: 0.75rem;
  color: #9ca3af;
  text-align: center;
  margin: 0;
}

.col-actions { width: 40px; text-align: center; }
.delete-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  color: #ef4444;
  font-size: 1rem;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background 0.1s;
}
.delete-btn:hover { background: #fef2f2; }

/* ── Mobile ── */

@media (max-width: 600px) {
  .codev-carto {
    padding: 1rem 0.75rem 1.5rem;
  }

  .carto-header h1 {
    font-size: 1.25rem;
  }
}
</style>
