<script setup lang="ts">
import { __ } from '@wordpress/i18n'
import { ref, toRefs, computed, onMounted, onBeforeUnmount, PropType } from 'vue'
import { ArrowLeft, Save, Plus, Trash, ChevronDown } from 'lucide-vue-next'
import {
  getI18n,
} from '@/helper'
import { getSavetoWishlistObj } from '@/config'
import { Listbox, ListboxButton, ListboxOptions, ListboxOption } from '@headlessui/vue'

/**
 * Pro License Notice.
 */
import LicenseNotice from '@/apps/partials/LicenseNotice.vue'

/**
 * Props.
 */
const props = defineProps({
  infoData: {
    type: Object,
    required: true
  },
  showButton: {
    type: Boolean,
    required: false,
    default: false
  },
  buttonIcon: {
    type: String,
    required: false,
    default: ''
  },
  buttonText: {
    type: String,
    required: false,
    default: getI18n('submitText', __('Save Changes', 'saveto-wishlist-lite-for-woocommerce'))
  },
  buttonLoadingText: {
    type: String,
    required: false,
    default: getI18n('saving', __('Saving...', 'saveto-wishlist-lite-for-woocommerce'))
  },
  showBackButton: {
    type: Boolean,
    required: false,
    default: false
  },
  showDeleteButton: {
    type: Boolean,
    required: false,
    default: false
  },
  isLoading: {
    type: Boolean,
    required: false,
    default: false
  },
  selectedOption: {
    type: String as PropType<string | null>,
    required: false,
    default: null
  },
  showSelect: {
    type: Boolean,
    required: false,
    default: false
  },
  selectOptions: {
    type: Array as PropType<{ value: string, label: string, description: string, icon: any }[]>,
    required: false,
    default: []
  }
})

const {
  infoData,
  showButton,
  buttonText,
  buttonLoadingText,
  showBackButton,
  showDeleteButton,
  isLoading,
  showSelect,
  selectOptions,
  selectedOption
} = toRefs(props)
const title = computed(() => infoData.value.title)
const description = computed(() => infoData.value.description || '')
const details = getSavetoWishlistObj.details
const emit = defineEmits(['trigger-button', 'trigger-back', 'trigger-delete', 'select-change'])
const isSelectOpen = ref(false)

/**
 * The settings page sidebar/preview panel stick just below this header, so
 * its real rendered height (which varies with title/description length) is
 * measured and published as a CSS var they read from — a hardcoded guess
 * drifts out of sync and causes the sticky panels to overlap the header.
 */
const headerRef = ref<HTMLElement | null>(null)
let headerResizeObserver: ResizeObserver | null = null

const publishHeaderHeight = () => {
  const settingsAppRoot = document.getElementById('saveto-wishlist-admin-app-settings')
  if (settingsAppRoot && headerRef.value) {
    settingsAppRoot.style.setProperty('--stwlite-header-height', `${headerRef.value.offsetHeight}px`)
  }
}

/**
 * The header only needs a shadow once it's actually pinned to the top —
 * showing it while the header is still in normal flow makes it look like a
 * permanent design element rather than a cue that content is scrolling
 * underneath it. A sentinel placed just above the header flips `isStuck`
 * once it scrolls past the header's own sticky offset.
 */
const isStuck = ref(false)
const sentinelRef = ref<HTMLElement | null>(null)
let stuckObserver: IntersectionObserver | null = null

onMounted(() => {
  publishHeaderHeight()
  headerResizeObserver = new ResizeObserver(publishHeaderHeight)
  if (headerRef.value) {
    headerResizeObserver.observe(headerRef.value)
  }

  /*
   * WordPress already pushes page content down by the admin-bar height
   * (html.wp-toolbar padding-top), so the header's natural resting position
   * already matches where sticky pins it at scrollTop 0 — there's no gap to
   * close. "Stuck" is simply "has the page scrolled at all," so the
   * sentinel needs no extra offset margin.
   */
  stuckObserver = new IntersectionObserver(
    ([entry]) => { isStuck.value = !entry.isIntersecting },
    { rootMargin: '0px', threshold: 0 }
  )
  if (sentinelRef.value) {
    stuckObserver.observe(sentinelRef.value)
  }
})

onBeforeUnmount(() => {
  headerResizeObserver?.disconnect()
  stuckObserver?.disconnect()
})

const handleButtonClick = () => {
  emit('trigger-button')
}

const handleBack = () => {
  emit('trigger-back')
}

const handleDelete = () => {
  emit('trigger-delete')
}

const handleSelectChange = (value: string) => {
  emit('select-change', value || '')
  isSelectOpen.value = false
}
</script>

<template>
  <div ref="sentinelRef" class="stw-header-sentinel" aria-hidden="true" />
  <div
    ref="headerRef"
    :class="[
      'global-header stwlite-tw-sticky stwlite-tw-top-0 stwlite-tw-z-40 stwlite-tw-bg-white stwlite-tw-border-0 stwlite-tw-border-b stwlite-tw-border-gray-200 stwlite-tw-border-solid stwlite-tw-transition-shadow',
      isStuck ? 'stwlite-tw-shadow-lg' : 'stwlite-tw-shadow-none',
    ]"
  >
    <div class="stwlite-tw-px-4 sm:stwlite-tw-px-6 lg:stwlite-tw-px-8">
      <div class="stwlite-tw-flex stwlite-tw-justify-between stwlite-tw-items-center stwlite-tw-py-4">
        <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-4">
          <img 
            :src="details.logo" 
            :alt="details.logo_alt" 
            class="stwlite-tw-max-w-12"
          />
          <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-4">
            <button
              v-if="showBackButton"
              @click="handleBack"
              class="stwlite-tw-inline-flex stwlite-tw-border-0 stwlite-tw-items-center stwlite-tw-text-gray-600 hover:stwlite-tw-text-gray-900 stwlite-tw-transition-colors stwlite-tw-duration-200 stwlite-tw-text-base stwlite-tw-bg-transparent stwlite-tw-cursor-pointer"
            >
              <ArrowLeft class="stwlite-tw-w-5 stwlite-tw-h-5 stwlite-tw-mr-2" />
              {{ getI18n('back', __( 'Back', 'saveto-wishlist-lite-for-woocommerce' )) }}
            </button>
            <div>
              <h1 class="stwlite-tw-text-2xl stwlite-tw-font-semibold stwlite-brand-text-dark stwlite-tw-my-0 stwlite-tw-py-0">{{ title }}</h1>
              <p class="stwlite-tw-text-sm stwlite-brand-text-gray stwlite-tw-mt-1 stwlite-tw-mb-0" v-if="description">{{ description }}</p>
            </div>
          </div>
        </div>
        <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-end stwlite-tw-space-x-4">
          <button
            v-if="showButton"
            type="button"
            :class="[ 'stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-bg-blue-600 stwlite-tw-text-white stwlite-tw-px-4 stwlite-tw-py-2 stwlite-tw-rounded-md stwlite-tw-font-medium stwlite-tw-text-sm hover:stwlite-tw-bg-blue-700 stwlite-tw-transition-colors stwlite-tw-border-0 stwlite-tw-cursor-pointer', isLoading ? 'stwlite-tw-bg-gray-400 stwlite-tw-cursor-not-allowed hover:stwlite-tw-bg-gray-400' : 'stwlite-tw-bg-blue-600 hover:stwlite-tw-bg-blue-700', ]"
            @click="handleButtonClick"
            :disabled="isLoading"
          >
            <component
              v-if="buttonIcon"
              :is="buttonIcon === 'save' ? Save : Plus"
              class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2"
            />
            <span v-if="isLoading">{{ buttonLoadingText }}</span>
            <span v-else>{{ buttonText }}</span>
          </button>
          <Listbox v-if="showSelect" :model-value="selectedOption" @update:model-value="handleSelectChange">
            <div class="stwlite-tw-relative stwlite-tw-w-96">
              <ListboxButton
                class="stwlite-tw-relative stwlite-tw-w-full stwlite-tw-bg-white stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-lg stwlite-tw-px-5 stwlite-tw-py-3 stwlite-tw-text-left stwlite-tw-shadow-sm hover:stwlite-tw-border-gray-400 stwlite-tw-transition-colors focus:stwlite-tw-outline-none focus-visible:stwlite-tw-ring-2 focus-visible:stwlite-tw-ring-offset-2 focus-visible:stwlite-tw-ring-blue-500 stwlite-tw-text-lg stwlite-tw-cursor-pointer"
              >
                <div class="stwlite-tw-flex stwlite-tw-items-center">
                  <component
                    v-if="selectOptions.find(opt => opt.value === selectedOption)?.icon"
                    :is="selectOptions.find(opt => opt.value === selectedOption)?.icon"
                    class="stwlite-tw-w-6 stwlite-tw-h-6 stwlite-tw-mr-3 stwlite-tw-text-blue-600"
                  />
                  <div class="stwlite-tw-flex stwlite-tw-flex-col">
                    <span class="stwlite-tw-block stwlite-tw-truncate stwlite-tw-text-lg stwlite-tw-font-medium stwlite-tw-text-gray-900">
                      {{ selectOptions.find(opt => opt.value === selectedOption)?.label || '' }}
                    </span>
                    <span class="stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-mt-0.5">
                      {{ selectOptions.find(opt => opt.value === selectedOption)?.description || '' }}
                    </span>
                  </div>
                </div>
                <ChevronDown
                  :class="[
                    'stwlite-tw-absolute stwlite-tw-right-4 stwlite-tw-top-1/2 stwlite-tw--translate-y-1/2 stwlite-tw-w-6 stwlite-tw-h-6 stwlite-tw-transition-transform',
                    isSelectOpen ? 'stwlite-tw-rotate-180' : ''
                  ]"
                />
              </ListboxButton>
              <transition
                leave-active-class="stwlite-tw-transition stwlite-tw-duration-100 stwlite-tw-ease-in"
                leave-from-class="stwlite-tw-opacity-100"
                leave-to-class="stwlite-tw-opacity-0"
              >
                <ListboxOptions
                  class="stwlite-tw-absolute stwlite-tw-right-0 stwlite-tw-z-50 stwlite-tw-w-96 stwlite-tw-mt-2 stwlite-tw-bg-white stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-rounded-lg stwlite-tw-shadow-lg stwlite-tw-ring-1 stwlite-tw-ring-black stwlite-tw-ring-opacity-5"
                >
                  <div class="stwlite-tw-py-1 stwlite-tw-max-h-64 stwlite-tw-overflow-y-auto">
                    <ListboxOption
                      v-for="option in selectOptions"
                      :key="option.value"
                      v-slot="{ active, selected }"
                      :value="option.value"
                      as="template"
                    >
                      <li
                        :class="[
                          'stwlite-tw-px-4 stwlite-tw-py-3 stwlite-tw-cursor-pointer stwlite-tw-transition-colors',
                          active ? 'stwlite-tw-bg-blue-50' : '',
                          selected ? 'stwlite-tw-bg-blue-100 stwlite-tw-border-l-4 stwlite-tw-border-l-blue-600' : 'stwlite-tw-border-l-4 stwlite-tw-border-l-transparent'
                        ]"
                      >
                        <div class="stwlite-tw-flex stwlite-tw-flex-col">
                          <div class="stwlite-tw-flex stwlite-tw-items-center">
                            <component
                              v-if="option.icon"
                              :is="option.icon"
                              class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2"
                            />
                            <div class="stwlite-tw-flex stwlite-tw-flex-col">
                              <span :class="['stwlite-tw-font-medium stwlite-tw-text-sm', selected ? 'stwlite-tw-text-blue-900' : 'stwlite-tw-text-gray-900']">
                                {{ option.label }}
                              </span>
                              <span class="stwlite-tw-text-xs stwlite-tw-text-gray-500 stwlite-tw-mt-0.5">
                                {{ option.description }}
                              </span>
                            </div>
                          </div>
                        </div>
                      </li>
                    </ListboxOption>
                  </div>
                </ListboxOptions>
              </transition>
            </div>
          </Listbox>
          <button
            v-if="showDeleteButton"
            @click="handleDelete"
            class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-px-4 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-transparent stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-text-white stwlite-tw-bg-red-600 hover:stwlite-tw-bg-red-700 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-offset-2 focus:stwlite-tw-ring-red-500 stwlite-tw-transition-colors stwlite-tw-duration-200 stwlite-tw-cursor-pointer"
          >
            <Trash class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2" />
            {{ getI18n('delete', __( 'Delete', 'saveto-wishlist-lite-for-woocommerce' )) }}
          </button>
        </div>
      </div>
    </div>
  </div>

  <LicenseNotice />
</template>

<style scoped lang="scss">
h1 {
  padding: 0;
}

.global-header {
  top: var(--stwlite-admin-bar-height, 32px);
}

.stw-header-sentinel {
  height: 1px;
  margin-bottom: -1px;
}

/* Brand color classes */
.stwlite-brand-text-dark {
  color: #333333 !important;
}

.stwlite-brand-text-gray {
  color: #666666 !important;
}
</style>
