<script setup>
import languageTemplateApi from '@/api/languageTemplateApi'
import ReusableDialog from '@/components/ReusableDialog.vue'
import { useAuthStore } from '@/stores/authStore'
import { useSettingStore } from '@/stores/settingStore'
import { computed, onMounted, ref, watch } from 'vue'
import { toast } from 'vue3-toastify'

const props = defineProps({
  modelValue: Boolean,
})

const emit = defineEmits(['update:modelValue', 'adopted'])

const settingStore = useSettingStore()
const authStore = useAuthStore()

const loading = ref(false)
const adopting = ref(false)
const suggestions = ref([])
const templateInfo = ref(null)

const languageCode = computed(() => {
  return (
    settingStore.setting?.general_settings?.language_code ||
    authStore.user?.data?.franchisee?.language ||
    null
  )
})

const languageName = computed(() => {
  const code = settingStore.setting?.general_settings?.language_code || authStore.user?.data?.franchisee?.language
  const name = settingStore.setting?.general_settings?.language_name
  
  if (name) return name

  const names = {
    'fr': 'French',
    'de': 'German',
    'es': 'Spanish',
    'it': 'Italian',
    'ur': 'Urdu',
    'id': 'Indonesian',
    'hi': 'Hindi',
    'ja': 'Japanese',
  }
  return names[code] || code || 'your language'
})

const fetchSuggestions = async () => {
  if (!languageCode.value || languageCode.value === 'en') {
    emit('update:modelValue', false)
    return
  }

  const selected = settingStore.setting?.general_settings?.translation_template_choice
  const selectedLanguage = settingStore.setting?.general_settings?.translation_template_choice_language

  if (selected && selectedLanguage === languageCode.value) {
    emit('update:modelValue', false)
    return
  }

  loading.value = true
  try {
    const response = await languageTemplateApi.getPublishedTemplate(languageCode.value)
    const data = response?.data?.data

    templateInfo.value = data?.template || null
    suggestions.value = data?.readiness?.pages?.items || []

  } catch (err) {
    console.error('Failed to fetch translation template suggestions:', err)
  } finally {
    loading.value = false
  }
}

const persistSelection = async (choice) => {
  const existingGeneral = settingStore.setting?.general_settings || {}
  await settingStore.saveSettings({
    general_settings: {
      ...existingGeneral,
      translation_template_choice: choice,
      translation_template_choice_language: languageCode.value,
      translation_template_choice_at: new Date().toISOString(),
      translation_template_id: templateInfo.value?.id || null,
    },
  })
  await settingStore.getSetting()
}

const adoptAll = async () => {
  adopting.value = true
  try {
    await languageTemplateApi.adoptPublishedTemplate(languageCode.value)
    await persistSelection('adopt_existing_template')
    toast.success('Published translation content has been adopted successfully.')
    emit('adopted', 'all')
    emit('update:modelValue', false)
  } catch (err) {
    console.error('Failed to save adoption choice:', err)
  } finally {
    adopting.value = false
  }
}

const handleManual = async () => {
  adopting.value = true
  try {
    await persistSelection('manual_translation')
    toast.info('Manual translation mode selected.')
    emit('adopted', 'manual')
    emit('update:modelValue', false)
  } catch (err) {
    console.error('Failed to save manual choice:', err)
  }
}

const openPreview = () => {
  const base = 'https://preview.youngengineers.org'
  const url = `${base}?language=${languageCode.value}`
  window.open(url, '_blank')
}


watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    fetchSuggestions()
  }
})

onMounted(() => {
  if (props.modelValue) {
    fetchSuggestions()
  }
})
</script>

<template>
  <ReusableDialog
    :model-value="modelValue"
    title="Website Content Setup"
    max-width="800"
    persistent
    @update:model-value="emit('update:modelValue', $event)"
  >

    <div class="dialog-content-grey">
      <!-- Intro Section -->
      <div class="text-center mb-6">
      
        <p class="text-body-2 text-medium-emphasis px-md-10 mb-0">
          We found professional <strong>{{ languageName }}</strong> versions. 
          Standardize now or manage manually.
        </p>
        <p v-if="templateInfo?.published_at" class="text-caption text-medium-emphasis mt-1">
          Template: {{ templateInfo.language_name }} ({{ templateInfo.language_code.toUpperCase() }})
        </p>
      </div>


      <!-- Path Selection Section -->
      <VRow class="choice-container px-2">
        <!-- Option A: Professional Path -->
        <VCol cols="12" md="6">
          <VCard
            variant="flat"
            class="choice-card pro-path h-100 d-flex flex-column"
            @click="adoptAll"
          >
            <!-- RECOMMENDED RIBBON -->
            <div class="card-highlight">RECOMMENDED</div>
            
            <VCardText class="pa-5 text-center flex-grow-1 d-flex flex-column">
              <div class="icon-orb pro-orb mb-4">
                <VIcon icon="bx-certification" size="32" color="white" />
              </div>
              
              <h3 class="text-h5 font-weight-bold mb-2">Adopt Professional</h3>
              <p class="text-body-2 mb-4 opacity-90">
                Instantly sync with high-quality translations from our team.
              </p>
              
              <ul class="benefit-list text-left mb-6">
                <li><VIcon icon="bx-check-double" color="success" size="18" class="mr-2" /> Accuracy & Brand consistency</li>
                <li><VIcon icon="bx-check-double" color="success" size="18" class="mr-2" /> Zero manual effort required</li>
              </ul>

              <VSpacer />

              <VBtn
                variant="outlined"
                color="primary"
                prepend-icon="bx-show"
                class="mb-4 font-weight-bold py-3 rounded-lg action-btn"
                block
                @click.stop="openPreview"
                :disabled="loading"
              >
                Preview Website
              </VBtn>


              <VBtn
                block
                size="large"
                color="primary"
                class="font-weight-bold py-3 rounded-lg action-btn"
                elevation="2"
                :loading="adopting || loading"
              >
                Adopt & Standardize
              </VBtn>
            </VCardText>
          </VCard>
        </VCol>


        <!-- Option B: Manual Path -->
        <VCol cols="12" md="6">
          <VCard
            variant="flat"
            class="choice-card manual-path h-100 d-flex flex-column"
            @click="handleManual"
          >
            <VCardText class="pa-5 text-center flex-grow-1 d-flex flex-column">
              <div class="icon-orb manual-orb mb-4">
                <VIcon icon="bx-pencil" size="32" color="primary" />
              </div>
              
              <h3 class="text-h5 font-weight-bold mb-2">Manual Translation</h3>
              <p class="text-body-2 mb-4 opacity-90">
                Maintain full local control for highly specific dialects.
              </p>

              <ul class="benefit-list text-left mb-6">
                <li><VIcon icon="bx-check" color="primary" size="18" class="mr-2" /> Full creative autonomy</li>
                <li><VIcon icon="bx-check" color="primary" size="18" class="mr-2" /> Independent local updates</li>
              </ul>

              <VSpacer />

              <VBtn
                block
                size="large"
                variant="outlined"
                color="primary"
                class="font-weight-bold py-3 rounded-lg action-btn"
              >
                Continue Manually
              </VBtn>
            </VCardText>
          </VCard>
        </VCol>

      </VRow>

      <div class="text-center mt-6 text-caption text-medium-emphasis">
        Making a selection will configure your localization stack for <strong>{{ languageName }}</strong>.
      </div>

    </div>
  </ReusableDialog>
</template>

<style scoped>
/* ========== grey Body Container ========== */
.dialog-content-grey {
  background-color: #f3f4f6;
  padding: 1.5rem 1rem;
  height: auto;
  overflow: visible;
  margin: 0;
}


/* Choice Card Styling */
.choice-card {
  border-radius: 20px !important;
  border: 2px solid #e5e7eb !important;
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  background-color: white !important;
}

.choice-card:hover {
  transform: translateY(-10px);
  border-color: #003b6f !important;
  box-shadow: 0 20px 25px -5px rgba(0, 59, 111, 0.1) !important;
}

/* Path Specifics */
.pro-path {
  background: linear-gradient(to bottom, #ffffff, #f8fafc) !important;
  position: relative;
  overflow: hidden !important;
}

/* THE RIBBON: Optimized for no clipping */
.card-highlight {
  position: absolute;
  top: 20px;
  right: -35px;
  background: #ffb400;
  color: #000;
  padding: 5px 0;
  width: 140px;
  font-size: 10px;
  font-weight: 800;
  transform: rotate(45deg);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  letter-spacing: 0.5px;
  z-index: 10;
  text-align: center;
}

/* Icon Orbs */
.icon-orb {
  width: 64px;
  height: 64px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  transition: transform 0.3s ease;
}


.choice-card:hover .icon-orb {
  transform: scale(1.1) rotate(5deg);
}

.pro-orb {
  background: linear-gradient(135deg, #003b6f 0%, #0056a3 100%);
  box-shadow: 0 10px 20px -5px rgba(0, 59, 111, 0.3);
}

.manual-orb {
  background: #f1f5f9;
  border: 2px solid #e2e8f0;
}

/* Benefit List */
.benefit-list {
  list-style: none;
  padding: 0;
  line-height: 1.6;
}


.benefit-list li {
  display: flex;
  align-items: center;
  font-size: 15px;
  color: #4b5563;
}

/* Buttons */
.action-btn {
  letter-spacing: 0.5px;
  text-transform: none;
  font-size: 1rem !important;
}

.opacity-90 {
  opacity: 0.9;
}

/* Animations */
.bounce-animation {
  animation: float 4s ease-in-out infinite;
}

@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
}

/* Responsive */
@media (max-width: 960px) {
  .dialog-content-grey {
    padding: 2rem 1.5rem;
  }
}
</style>
