<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import NotificationTogglesWidget from './NotificationTogglesWidget.vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import SubscribeFormWidget from './SubscribeFormWidget.vue';
import { CpvCode } from '../models/CpvCode';
import { appUser, fetchAppUser } from '../globals/user.js';

const props = defineProps({
  cpvCodes: {
    type: Array,
    required: true
  }
});

const showDialog = ref(false);
const selectedCpv = ref('');
const showNotificationToggles = ref(false);

// Carousel functionality
const carouselRef = ref(null);
const currentSlide = ref(0);
const isMobile = ref(false);

const cpvCodeModels = computed(() => props.cpvCodes.map(c => new CpvCode(c)));
const userTopics = computed(() => {
  const userObj = appUser.value;
  return Array.isArray(userObj?.topics) ? userObj.topics : [];
});

function openSubscribe(cpv) {
  selectedCpv.value = cpv;
  showDialog.value = true;

  // Check if user is not subscribed to any notification service
  // If not subscribed to any, show the toggles and keep them visible during this dialog session
  if (appUser.value) {
    const hasAnyNotification = appUser.value.notifyWhatsapp || appUser.value.notifySms || appUser.value.notifyEmail;
    showNotificationToggles.value = !hasAnyNotification;
  }
}
function closeDialog() {
  showDialog.value = false;
  showNotificationToggles.value = false;
}
async function subscribe(payload) {
  if (appUser.value && Array.isArray(appUser.value.topics) && payload && payload.cpvCode) {
    let topics = [...appUser.value.topics];
    if (payload.action === 'subscribe') {
      if (!topics.includes(payload.cpvCode)) {
        topics.push(payload.cpvCode);
      }
    } else if (payload.action === 'unsubscribe') {
      topics = topics.filter(t => t !== payload.cpvCode);
    }
    // Replace topics array for reactivity
    appUser.value.topics = topics;
    await fetchAppUser();
  }
  closeDialog();
}
function isSubscribed(cpvCode) {
  return userTopics.value.includes(cpvCode);
}

// Carousel functions
function checkMobile() {
  isMobile.value = window.innerWidth < 768;
}

function updateCurrentSlide() {
  if (!carouselRef.value || !isMobile.value) return;

  const container = carouselRef.value;
  const itemWidth = container.children[0]?.offsetWidth || 320;
  const scrollLeft = container.scrollLeft;
  currentSlide.value = Math.round(scrollLeft / itemWidth);
}

function scrollToSlide(index) {
  if (!carouselRef.value || !isMobile.value) return;

  const container = carouselRef.value;
  const itemWidth = container.children[0]?.offsetWidth || 320;
  container.scrollTo({
    left: index * itemWidth,
    behavior: 'smooth'
  });
}

onMounted(() => {
  checkMobile();
  window.addEventListener('resize', checkMobile);

  if (carouselRef.value) {
    carouselRef.value.addEventListener('scroll', updateCurrentSlide);

    // Add touch event handling for better mobile experience
    let startX = 0;
    let isScrolling = false;

    carouselRef.value.addEventListener('touchstart', (e) => {
      startX = e.touches[0].clientX;
      isScrolling = false;
    });

    carouselRef.value.addEventListener('touchmove', (e) => {
      if (!startX) return;
      isScrolling = true;
    });

    carouselRef.value.addEventListener('touchend', (e) => {
      if (!isScrolling || !startX) return;

      const endX = e.changedTouches[0].clientX;
      const diff = startX - endX;

      // Minimum swipe distance
      if (Math.abs(diff) > 50) {
        if (diff > 0 && currentSlide.value < cpvCodeModels.value.length - 1) {
          // Swipe left - next slide
          scrollToSlide(currentSlide.value + 1);
        } else if (diff < 0 && currentSlide.value > 0) {
          // Swipe right - previous slide
          scrollToSlide(currentSlide.value - 1);
        }
      }

      startX = 0;
      isScrolling = false;
    });
  }
});

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile);

  if (carouselRef.value) {
    carouselRef.value.removeEventListener('scroll', updateCurrentSlide);
  }
});


</script>

<template>
  <div class="cpv-legend-widget">
    <div class="cpv-list" ref="carouselRef">
      <div v-for="cpv in cpvCodeModels" :key="cpv.cpv" class="cpv-item">
        <div class="cpv-code-row">
          <span class="cpv-icon"><font-awesome-icon icon="paper-plane" /></span>
          <span class="cpv-code" @click="$emit('select-cpv', cpv.cpv)"
            :title="cpv.title && cpv.title.trim() ? cpv.title.trim() : ''"
            style="cursor:pointer; color:#007bff; text-decoration:underline;">{{ cpv.cpv }}</span>
          <span v-if="isSubscribed(cpv.cpv)" class="cpv-checkmark"><font-awesome-icon icon="check" /></span>
        </div>
        <div class="cpv-body" :title="cpv.title ? cpv.title.trim() : ''">
          {{ cpv.title && cpv.title.trim() ? cpv.title.trim() : '— fără titlu —' }}
        </div>
        <div class="cpv-divider"></div>
        <button class="cpv-subscribe-btn" @click="openSubscribe(cpv.cpv)">
          {{ isSubscribed(cpv.cpv) ? 'Modifica' : 'Subscrie' }}
        </button>
      </div>
    </div>

    <!-- Mobile carousel indicators -->
    <div v-if="isMobile && cpvCodeModels.length > 1" class="carousel-indicators">
      <div v-for="(cpv, index) in cpvCodeModels" :key="`dot-${index}`" class="carousel-dot"
        :class="{ active: currentSlide === index }" @click="scrollToSlide(index)"></div>
    </div>

    <div class="legend-text">
      Subscrie și te notificăm noi când sunt licitații noi de interes pentru tine.
    </div>
    <div v-if="showDialog" class="subscribe-dialog">
      <div class="dialog-content">
        <!-- Show notification toggles only if user has no active notifications when dialog opens -->
        <NotificationTogglesWidget v-if="showNotificationToggles" :forceShow="true" />
        <SubscribeFormWidget v-if="showDialog" :cpvCode="selectedCpv" :onSubscribe="subscribe" />
        <button @click="closeDialog" style="margin-top:1em;">Anulează</button>
      </div>
    </div>
  </div>
</template>
