import { computed, type ComputedRef, type Ref } from 'vue'

import type { AwardsStore } from '../../stores/awards'
import type { HomeDisplayCategory, HomeInteractionModalKind, HomePreviewPhase, HomeSuccessKind } from './homeLandingTypes'

export function useHomeParticipationPresentation(params: {
  store: AwardsStore
  displayCategories: ComputedRef<HomeDisplayCategory[]>
  activeCat: Ref<number>
  modal: Ref<null | HomeInteractionModalKind>
  previewPhase: Ref<HomePreviewPhase>
  votes: Ref<Record<string, number>>
  savedVoteCount: Ref<number>
  submitted: Ref<boolean>
  successKind: Ref<null | HomeSuccessKind>
  clipCatIdx: Ref<number>
  clipDsgvo: Ref<boolean>
  clipSubmissionsEnabled: ComputedRef<boolean>
}) {
  const {
    store,
    displayCategories,
    activeCat,
    modal,
    previewPhase,
    votes,
    savedVoteCount,
    submitted,
    successKind,
    clipCatIdx,
    clipDsgvo,
    clipSubmissionsEnabled,
  } = params

  const notSubmitted = computed(() => !submitted.value)
  const voteCount = computed(() => Object.keys(votes.value).length)
  const totalCats = computed(() => displayCategories.value.length)
  const canSubmitVote = computed(() => previewPhase.value === 'voting' && voteCount.value > 0)
  const savedVoteActive = computed(() => savedVoteCount.value > 0)
  const activeCategory = computed(() => displayCategories.value[activeCat.value] ?? displayCategories.value[0] ?? null)
  const activeCatName = computed(() => {
    const category = activeCategory.value
    return category ? `${category.groupName} · ${category.name}` : ''
  })
  const pickerTitle = computed(() => (modal.value === 'nominate' && previewPhase.value === 'nomination' ? 'Streamer nominieren' : modal.value === 'nominate' ? 'Eingegangene Nominierungen' : 'Deine Stimme zählt'))
  const pickerSubtitle = computed(() => (modal.value === 'nominate' && previewPhase.value === 'nomination' ? 'Reiche den offiziellen Stream- oder Kanal-Link ein. Den Anzeigenamen vergibt das Team im Review.' : modal.value === 'nominate' ? 'Die Nominierungsphase ist abgeschlossen — hier sind alle eingereichten Kandidat:innen.' : 'Wähle in jeder Hauptkategorie die passende Unterkategorie und dort deine:n Favorit:in. Eine Stimme pro Unterkategorie.'))
  const successTitle = computed(() => successKind.value === 'nomination' ? 'Nominierung eingereicht ✦' : successKind.value === 'clip' ? 'Clip eingereicht ✦' : successKind.value === 'show' ? 'Erinnerung aktiviert ✦' : 'Stimme gespeichert ✩')
  const successText = computed(() => successKind.value === 'nomination' ? 'Danke! Deine Links wurden gespeichert und landen im Admin-Review.' : successKind.value === 'clip' ? 'Danke! Dein Clip wurde im Backend gespeichert und wird vom Team geprüft.' : successKind.value === 'show' ? `Wir erinnern dich rechtzeitig vor der Award-Show am ${formatShowDate(store)}.` : savedVoteActive.value ? 'Danke! Deine geänderte Auswahl wurde gespeichert.' : 'Danke fürs Abstimmen! Deine Auswahl wurde im Backend gespeichert.')
  const clipNomOptions = computed(() => (displayCategories.value[clipCatIdx.value]?.candidates ?? []).map((candidate, index) => ({ id: index, label: `${candidate.displayName}` })))
  const catOptions = computed(() => {
    const seenGroups = new Set<string>()
    return displayCategories.value.flatMap((category, index) => {
      const groupKey = category.groupName.trim().toLowerCase()
      if (seenGroups.has(groupKey)) return []
      seenGroups.add(groupKey)
      return [{
        id: index,
        label: `${category.icon} ${category.groupName}`,
        name: category.groupName,
        groupName: category.groupName,
        icon: category.icon,
        maxNomineesPerUser: category.maxNomineesPerUser,
      }]
    })
  })
  const canSubmitClip = computed(() => clipSubmissionsEnabled.value && previewPhase.value === 'nomination' && clipDsgvo.value)
  const clipSubmitStyle = computed(() => canSubmitClip.value ? "width:100%;display:flex;align-items:center;justify-content:center;gap:10px;padding:16px;border-radius:13px;border:none;background:linear-gradient(135deg,#8b6cdb,#7355c8);color:#fff;font-family:'Outfit',sans-serif;font-weight:600;font-size:15px;cursor:pointer;box-shadow:0 10px 24px rgba(124,86,196,.3);" : "width:100%;display:flex;align-items:center;justify-content:center;gap:10px;padding:16px;border-radius:13px;border:none;background:#d1c4e9;color:#9e8cc5;font-family:'Outfit',sans-serif;font-weight:600;font-size:15px;cursor:not-allowed;")

  return {
    notSubmitted,
    voteCount,
    totalCats,
    canSubmitVote,
    savedVoteActive,
    activeCategory,
    activeCatName,
    pickerTitle,
    pickerSubtitle,
    successTitle,
    successText,
    clipNomOptions,
    catOptions,
    canSubmitClip,
    clipSubmitStyle,
  }
}

function formatShowDate(store: AwardsStore) {
  const value = store.overview.showDate
  if (!value) return 'Noch nicht terminiert'
  const date = new Date(`${value}T00:00:00`)
  return Number.isNaN(date.getTime())
    ? value
    : date.toLocaleDateString('de-DE', { day: '2-digit', month: 'short', year: 'numeric' })
}
