<template>
  <div class="fc-artist-mgmt">
    <section class="fc-artist-mgmt__sec">
      <h2 class="fc-h2">Overview</h2>
      <div class="fc-artist-mgmt__chips">
        <v-chip
          size="small"
          :variant="overview.is_subscription ? 'flat' : 'outlined'"
          :color="overview.is_subscription ? 'accent' : undefined"
          prepend-icon="mdi-rss"
        >{{ overview.is_subscription ? 'Subscription' : 'One-off' }}</v-chip>
        <v-chip
          size="small" variant="outlined" prepend-icon="mdi-link-variant"
          :to="`/subscriptions?artist_id=${overview.id}`"
        >{{ overview.sources.length }} subscription{{ overview.sources.length === 1 ? '' : 's' }}</v-chip>
      </div>
    </section>

    <section v-if="overview.cooccurring_tags.length" class="fc-artist-mgmt__sec">
      <h2 class="fc-h2">Frequent tags</h2>
      <div class="fc-artist-mgmt__tags">
        <v-chip
          v-for="t in overview.cooccurring_tags" :key="t.id"
          size="small" @click="openTag(t.id)"
        >{{ t.name }} <span class="fc-artist-mgmt__tagc">{{ t.count }}</span></v-chip>
      </div>
    </section>

    <section v-if="overview.activity.length" class="fc-artist-mgmt__sec">
      <h2 class="fc-h2">Activity</h2>
      <svg
        class="fc-artist-mgmt__spark" :viewBox="`0 0 ${sparkW} ${sparkH}`"
        preserveAspectRatio="none" role="img" aria-label="posts over time"
      >
        <polyline :points="sparkPoints" fill="none"
                  stroke="rgb(var(--v-theme-accent))" stroke-width="2" />
      </svg>
    </section>

    <section v-if="overview.sources.length" class="fc-artist-mgmt__sec">
      <div class="fc-artist-mgmt__sec-head">
        <h2 class="fc-h2">Subscriptions</h2>
        <RouterLink
          :to="`/subscriptions?artist_id=${overview.id}`"
          class="fc-artist-mgmt__manage"
        >Manage subscriptions →</RouterLink>
      </div>
      <v-table density="compact">
        <thead>
          <tr>
            <th>Platform</th><th>URL</th>
            <th class="text-right">Images</th><th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="s in overview.sources" :key="s.id">
            <td>{{ s.platform }}</td>
            <td class="fc-artist-mgmt__url">{{ s.url }}</td>
            <td class="text-right">{{ s.image_count }}</td>
            <td class="text-right">
              <v-btn
                size="x-small" variant="text" prepend-icon="mdi-account-arrow-right"
                @click="openMove(s)"
              >Move…</v-btn>
            </td>
          </tr>
        </tbody>
      </v-table>
    </section>

    <!-- #130: move a source into a different (existing) artist. The slug is
         immutable so no files move — just re-attribution. -->
    <v-dialog v-model="moveOpen" max-width="480">
      <v-card>
        <v-card-title class="fc-h2">Move source to another artist</v-card-title>
        <v-card-text>
          <p class="mb-3 text-body-2">
            Moving <strong>{{ moveSource?.platform }}</strong> and the posts/images
            it brought in to another artist. Files aren't moved — only the
            attribution changes. If <strong>{{ overview.name }}</strong> is left
            empty it will be removed.
          </p>
          <v-autocomplete
            v-model="moveTarget"
            :items="artistItems"
            :loading="searching"
            item-title="name" item-value="id" return-object
            label="Target artist" density="compact" variant="outlined"
            no-filter hide-details autofocus clearable
            @update:search="onSearch"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="moveOpen = false">Cancel</v-btn>
          <v-btn
            color="accent" :disabled="!moveTarget || moving" :loading="moving"
            @click="confirmMove"
          >Move</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <section class="fc-artist-mgmt__sec">
      <h2 class="fc-h2">Translation</h2>
      <p class="fc-muted text-body-2 mb-3">
        Re-translate every post by {{ overview.name }} through the current
        Interpreter model — clears the stored translations and rebuilds them.
        Use this after switching translation models to refresh just this artist.
      </p>
      <div class="d-flex align-center flex-wrap" style="gap: 10px;">
        <v-btn
          size="small" variant="tonal" rounded="pill"
          prepend-icon="mdi-translate"
          :loading="retranslating" :disabled="!translationEnabled"
          @click="confirmRetranslate = true"
        >Re-translate posts</v-btn>
        <span v-if="!translationEnabled" class="fc-muted text-caption">
          Translation is off — enable it in Settings → Maintenance.
        </span>
      </div>
    </section>

    <!-- m146: per-artist re-translate — clears + rebuilds this artist's stored
         translations (used after a translation-model change). -->
    <v-dialog v-model="confirmRetranslate" max-width="440">
      <v-card>
        <v-card-title class="fc-h2">Re-translate {{ overview.name }}?</v-card-title>
        <v-card-text class="text-body-2">
          Clears the stored translation for every post by
          <strong>{{ overview.name }}</strong> and re-runs them through your
          current Interpreter model. Unchanged text comes back from the cache
          instantly. Runs in the background until done.
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="confirmRetranslate = false">Cancel</v-btn>
          <v-btn color="accent" :loading="retranslating" @click="onRetranslate">
            Re-translate
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <section class="fc-artist-mgmt__sec">
      <h2 class="fc-h2">Danger zone</h2>
      <ArtistDangerZone
        :slug="overview.slug"
        :artist-id="overview.id"
        :artist-name="overview.name"
      />
    </section>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter, RouterLink } from 'vue-router'

import { useApi } from '../../composables/useApi.js'
import { useImportStore } from '../../stores/import.js'
import { useSourcesStore } from '../../stores/sources.js'
import { toast } from '../../utils/toast.js'
import ArtistDangerZone from './ArtistDangerZone.vue'

const props = defineProps({
  overview: { type: Object, required: true },
})

const router = useRouter()
const api = useApi()
const importStore = useImportStore()
const sources = useSourcesStore()

// m146: per-artist re-translate. Gated on translation being enabled globally
// (the endpoint 400s otherwise) — read the shared import settings once.
const translationEnabled = ref(false)
const retranslating = ref(false)
const confirmRetranslate = ref(false)

onMounted(async () => {
  try {
    await importStore.loadSettings()
    translationEnabled.value = !!importStore.settings?.translation_enabled
  } catch { /* non-fatal — the button just stays disabled */ }
})

async function onRetranslate () {
  retranslating.value = true
  try {
    await api.post('/api/settings/translation/retranslate', {
      body: { artist_id: props.overview.id },
    })
    confirmRetranslate.value = false
    toast({ text: `Re-translating ${props.overview.name}…`, type: 'success' })
  } catch (e) {
    toast({ text: `Re-translate failed: ${e.message}`, type: 'error' })
  } finally {
    retranslating.value = false
  }
}

// #130: move a source into another artist.
const moveOpen = ref(false)
const moveSource = ref(null)
const moveTarget = ref(null)
const artistItems = ref([])
const searching = ref(false)
const moving = ref(false)

function openMove (s) {
  moveSource.value = s
  moveTarget.value = null
  artistItems.value = []
  moveOpen.value = true
}

let searchSeq = 0
async function onSearch (q) {
  const mine = ++searchSeq
  if (!q || !q.trim()) { artistItems.value = []; return }
  searching.value = true
  try {
    const rows = await sources.autocompleteArtist(q)
    // Drop the current artist — you can't move a source onto itself.
    if (mine === searchSeq) artistItems.value = rows.filter(a => a.id !== props.overview.id)
  } finally {
    if (mine === searchSeq) searching.value = false
  }
}

async function confirmMove () {
  if (!moveTarget.value || !moveSource.value) return
  moving.value = true
  try {
    await sources.reassign(moveSource.value.id, moveTarget.value.id)
    moveOpen.value = false
    toast({ text: `Moved to ${moveTarget.value.name}`, type: 'success' })
    // The current artist may now be empty (deleted); route to the target,
    // whose slug is stable (immutable).
    router.push({ name: 'artist', params: { slug: moveTarget.value.slug } })
  } catch (e) {
    toast({ text: `Move failed: ${e.message}`, type: 'error' })
  } finally {
    moving.value = false
  }
}

const sparkW = 600
const sparkH = 80
const sparkPoints = computed(() => {
  const a = props.overview.activity ?? []
  if (a.length === 0) return ''
  const max = Math.max(...a.map(p => p.count), 1)
  const stepX = a.length > 1 ? sparkW / (a.length - 1) : 0
  return a.map((p, i) => {
    const x = i * stepX
    const y = sparkH - (p.count / max) * (sparkH - 4) - 2
    return `${x.toFixed(1)},${y.toFixed(1)}`
  }).join(' ')
})

function openTag (tagId) {
  router.push({ name: 'gallery', query: { tag_id: tagId } })
}
</script>

<style scoped>
.fc-artist-mgmt { padding-top: 1rem; }
.fc-h2 {
  font-family: 'Fraunces', Georgia, serif;
  font-size: 20px; font-weight: 500; margin-bottom: 8px;
}
.fc-artist-mgmt__sec { margin-bottom: 28px; }
.fc-artist-mgmt__chips { display: flex; gap: 8px; flex-wrap: wrap; }
.fc-artist-mgmt__tags { display: flex; flex-wrap: wrap; gap: 6px; }
.fc-artist-mgmt__tagc {
  color: rgb(var(--v-theme-on-surface-variant));
  margin-left: 4px;
  font-variant-numeric: tabular-nums;
}
.fc-artist-mgmt__spark { width: 100%; height: 80px; }
.fc-artist-mgmt__url {
  max-width: 380px; overflow: hidden; text-overflow: ellipsis;
  white-space: nowrap;
}
.fc-artist-mgmt__sec-head {
  display: flex; align-items: baseline; justify-content: space-between;
  margin-bottom: 0.25rem;
}
.fc-artist-mgmt__manage {
  font-size: 0.85rem;
  color: rgb(var(--v-theme-accent));
  text-decoration: none;
}
.fc-artist-mgmt__manage:hover { text-decoration: underline; }
</style>
