<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>
    </header>

    <div class="codev-tabs">
      <button :class="{ active: tab === 'carto' }" @click="tab = 'carto'" type="button">Carto</button>
      <button :class="{ active: tab === 'besoins' }" @click="tab = 'besoins'" type="button">Besoins</button>
      <button :class="{ active: tab === 'competences' }" @click="tab = 'competences'" type="button">Compétences</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 === 'alliance' }"
          style="--mode-color: #f97316"
          @click="setMode('alliance')"
          type="button"
        >
          Alliance
          <span class="hint">besoins partages</span>
        </button>
        <button
          :class="{ active: mode === 'surprise' }"
          style="--mode-color: #3b82f6"
          @click="setMode('surprise')"
          type="button"
        >
          Surprise
          <span class="hint">offres partagees</span>
        </button>
        <button
          v-if="mode !== 'none'"
          class="reset"
          @click="setMode('none')"
          type="button"
        >
          Effacer
        </button>
      </div>
    </div>

    <div v-else-if="tab === 'besoins'" class="list-view">
      <div v-for="f in fiches" :key="f.id" class="list-card">
        <div class="list-card-name">{{ f.nom }}</div>
        <p class="list-card-text">{{ f.besoin }}</p>
        <NuxtLink :to="`/codev/fiche?id=${f.id}`" class="list-card-link">Modifier</NuxtLink>
      </div>
      <div v-if="fiches.length === 0" class="list-empty">Aucune fiche. <NuxtLink to="/codev/fiche">Ajouter la mienne</NuxtLink></div>
    </div>

    <div v-else-if="tab === 'competences'" class="list-view">
      <div v-for="f in fiches" :key="f.id" class="list-card">
        <div class="list-card-name">{{ f.nom }}</div>
        <p class="list-card-text">{{ f.offre }}</p>
        <NuxtLink :to="`/codev/fiche?id=${f.id}`" class="list-card-link">Modifier</NuxtLink>
      </div>
      <div v-if="fiches.length === 0" class="list-empty">Aucune fiche. <NuxtLink to="/codev/fiche">Ajouter la mienne</NuxtLink></div>
    </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 } = 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' | 'besoins' | 'competences'>('carto')
const selectedFiche = ref<CodevFiche | null>(null)
const isMobileView = typeof window !== 'undefined' ? window.innerWidth < 600 : 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}`)
  }
}
</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; }

/* ── Mobile ── */

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

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