<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
import { RouterLink } from "vue-router";
import {
  Menu, X, Phone, Mail, ChevronDown, Search, User,
  Wifi, PhoneCall, Building2, Signal, Server, Network,
  Cable, Cloud, Shield, Settings, Laptop, Globe,
} from "lucide-vue-next";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import SearchDialog from "@/components/SearchDialog.vue";
import targoLogo from "@/assets/targo-logo.png";

// Business menu items with icons and descriptions
const businessMenuItems = [
  {
    category: "CONNECTIVITÉ",
    items: [
      { label: "Internet affaires", href: "/business/internet", icon: Globe, description: "Connexion fibre haute vitesse pour entreprises" },
      { label: "SD-WAN", href: "/business/sd-wan", icon: Network, description: "Réseau intelligent multi-sites" },
      { label: "Réseaux inter-sites", href: "/business/reseau-inter-sites", icon: Cable, description: "Liaisons dédiées entre vos succursales" },
    ],
  },
  {
    category: "COMMUNICATIONS",
    items: [
      { label: "Téléphonie IP", href: "/business/telephonie", icon: PhoneCall, description: "Système téléphonique cloud complet" },
      { label: "Liaisons SIP", href: "/business/sip", icon: Phone, description: "Trunks SIP pour votre PBX" },
      { label: "Amplification cellulaire", href: "/business/amplification-cellulaire", icon: Signal, description: "Signal mobile amplifié partout" },
    ],
  },
  {
    category: "INFRASTRUCTURE",
    items: [
      { label: "Services cloud", href: "/business/cloud", icon: Cloud, description: "Hébergement et sauvegarde sécurisés" },
      { label: "Virtualisation", href: "/business/virtualisation", icon: Server, description: "Infrastructure virtualisée sur mesure" },
      { label: "Microsoft 365", href: "/business/microsoft-365", icon: Laptop, description: "Suite Microsoft pour entreprises" },
    ],
  },
  {
    category: "SERVICES",
    items: [
      { label: "WiFi commercial", href: "/business/wifi", icon: Wifi, description: "WiFi haute densité pour commerces" },
      { label: "Câblage structuré", href: "/business/cablage", icon: Cable, description: "Installation réseau professionnelle" },
      { label: "Services gérés", href: "/business/services-geres", icon: Settings, description: "Gestion TI complète externalisée" },
      { label: "Sécurité DDoS", href: "/business/securite", icon: Shield, description: "Protection contre les cyberattaques" },
      { label: "Multilogement", href: "/business/multilogement", icon: Building2, description: "Solutions pour immeubles résidentiels" },
    ],
  },
];

interface NavLink {
  label: string;
  href: string;
  isMegaMenu?: boolean;
  submenu?: { label: string; href: string }[];
}

const navLinks: NavLink[] = [
  { label: "Internet", href: "/internet" },
  { label: "Télévision", href: "/television" },
  { label: "Téléphone", href: "/telephone" },
  { label: "Affaires", href: "/business", isMegaMenu: true },
  {
    label: "À propos",
    href: "/support",
    submenu: [
      { label: "Actualités", href: "/actualites" },
      { label: "Support", href: "/support" },
    ],
  },
];

const businessMenuItemsFlat = businessMenuItems.flatMap((cat) => cat.items);

const isMenuOpen = ref(false);
const isSearchOpen = ref(false);
const isScrolled = ref(false);

const handleScroll = () => {
  isScrolled.value = window.scrollY > 20;
};

const down = (e: KeyboardEvent) => {
  if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
    e.preventDefault();
    isSearchOpen.value = !isSearchOpen.value;
  }
};

onMounted(() => {
  window.addEventListener("scroll", handleScroll);
  document.addEventListener("keydown", down);
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
  document.removeEventListener("keydown", down);
  document.body.style.overflow = "";
});

// Lock body scroll when mobile menu is open
watch(isMenuOpen, (open) => {
  if (open) {
    document.body.style.overflow = "hidden";
  } else {
    document.body.style.overflow = "";
  }
});
</script>

<template>
  <header :class="`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${isScrolled ? 'bg-white/90 backdrop-blur-xl shadow-2xl py-0' : 'bg-white py-0'}`">
    <SearchDialog v-model:open="isSearchOpen" />
    <!-- Top bar -->
    <div
      v-motion
      :animate="{ height: isScrolled ? 0 : 'auto', opacity: isScrolled ? 0 : 1, transition: { duration: 300 } }"
      class="bg-targo-green text-white py-2 px-4 shadow-md z-50 relative overflow-hidden hidden md:block"
    >
      <div class="container flex items-center justify-between text-xs font-semibold uppercase tracking-wider">
        <div class="flex items-center gap-8">
          <a href="tel:514.448.0773" class="flex items-center gap-2 hover:text-white/80 transition-colors">
            <Phone class="w-3.5 h-3.5" />
            <span>514.448.0773</span>
          </a>
          <a href="mailto:support@targo.ca" class="flex items-center gap-2 hover:text-white/80 transition-colors">
            <Mail class="w-3.5 h-3.5" />
            <span>support@targo.ca</span>
          </a>
        </div>
        <span class="opacity-90">La puissance de la fibre locale</span>
      </div>
    </div>

    <!-- Main nav -->
    <nav :class="`container py-4 transition-all duration-300 ${isScrolled ? 'py-2' : 'py-4'}`">
      <div class="flex items-center justify-between">
        <!-- Logo -->
        <RouterLink to="/" class="flex items-center group">
          <img
            :src="targoLogo"
            alt="Targo - 100% Fibre"
            class="transition-transform group-hover:scale-105 flex-shrink-0 object-contain"
            :style="{ height: isScrolled ? '32px' : '40px', width: 'auto' }"
          />
        </RouterLink>

        <!-- Desktop nav -->
        <div class="hidden md:flex items-center gap-8">
          <template v-for="link in navLinks" :key="link.href">
            <Popover v-if="link.isMegaMenu">
              <PopoverTrigger class="flex items-center gap-1 text-gray-700 hover:text-targo-green transition-colors font-medium text-sm lg:text-base outline-none">
                {{ link.label }}
                <ChevronDown class="h-4 w-4" />
              </PopoverTrigger>
              <PopoverContent
                class="w-[800px] p-6 bg-white border-gray-100 shadow-2xl rounded-xl"
                align="center"
                :side-offset="20"
              >
                <div class="grid grid-cols-4 gap-6">
                  <div v-for="category in businessMenuItems" :key="category.category" class="space-y-3">
                    <h4 class="text-xs font-bold text-gray-400 uppercase tracking-wider">
                      {{ category.category }}
                    </h4>
                    <div class="space-y-1">
                      <RouterLink
                        v-for="item in category.items"
                        :key="item.href"
                        :to="item.href"
                        class="group flex items-start gap-3 p-2 rounded-lg hover:bg-gray-50 transition-colors"
                      >
                        <div class="w-8 h-8 rounded-md bg-targo-green/10 flex items-center justify-center flex-shrink-0 group-hover:bg-targo-green/20 transition-colors">
                          <component :is="item.icon" class="w-4 h-4 text-targo-green" />
                        </div>
                        <div class="min-w-0">
                          <div class="font-medium text-gray-900 text-sm group-hover:text-targo-green transition-colors">
                            {{ item.label }}
                          </div>
                          <div class="text-xs text-gray-500 line-clamp-2">
                            {{ item.description }}
                          </div>
                        </div>
                      </RouterLink>
                    </div>
                  </div>
                </div>
                <div class="mt-6 pt-4 border-t border-gray-100">
                  <RouterLink
                    to="/business"
                    class="inline-flex items-center text-sm font-medium text-targo-green hover:text-targo-green/80 transition-colors"
                  >
                    Voir toutes les solutions affaires
                    <ChevronDown class="w-4 h-4 ml-1 rotate-[-90deg]" />
                  </RouterLink>
                </div>
              </PopoverContent>
            </Popover>
            <DropdownMenu v-else-if="link.submenu">
              <DropdownMenuTrigger class="flex items-center gap-1 text-gray-700 hover:text-targo-green transition-colors font-medium text-sm lg:text-base outline-none">
                {{ link.label }}
                <ChevronDown class="h-4 w-4" />
              </DropdownMenuTrigger>
              <DropdownMenuContent class="bg-white border-gray-100 text-gray-800 shadow-xl">
                <DropdownMenuItem
                  v-for="sublink in link.submenu"
                  :key="sublink.href"
                  class="focus:bg-gray-50 focus:text-targo-green cursor-pointer"
                  as-child
                >
                  <RouterLink :to="sublink.href" class="w-full">
                    {{ sublink.label }}
                  </RouterLink>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
            <RouterLink
              v-else
              :to="link.href"
              class="text-gray-700 hover:text-targo-green transition-colors font-medium text-sm lg:text-base"
            >
              {{ link.label }}
            </RouterLink>
          </template>
        </div>

        <!-- CTA -->
        <div class="hidden md:flex items-center gap-4">
          <Button
            variant="ghost"
            size="icon"
            class="text-gray-700 hover:text-black hover:bg-black/5"
            @click="isSearchOpen = true"
          >
            <Search class="w-5 h-5" />
          </Button>
          <Button variant="outline" class="border-gray-200 text-gray-700 bg-transparent hover:bg-gray-100 hover:text-black backdrop-blur-sm" as-child>
            <a href="https://store.targo.ca/clients" target="_blank" rel="noopener noreferrer">Mon compte</a>
          </Button>
          <Button class="gradient-targo text-white shadow-lg shadow-targo-green/20 glow-targo border-none" as-child>
            <a href="/#contact">Nous joindre</a>
          </Button>
        </div>

        <!-- Mobile menu button -->
        <div class="flex items-center gap-2 md:hidden">
          <button
            class="p-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            aria-label="Search"
            @click="isSearchOpen = true"
          >
            <Search class="w-6 h-6" />
          </button>
          <button
            class="p-2 text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
            aria-label="Toggle menu"
            @click="isMenuOpen = !isMenuOpen"
          >
            <X v-if="isMenuOpen" class="w-6 h-6" />
            <Menu v-else class="w-6 h-6" />
          </button>
        </div>
      </div>

      <!-- Mobile menu -->
      <Transition>
        <div
          v-if="isMenuOpen"
          v-motion
          :initial="{ height: 0, opacity: 0 }"
          :enter="{ height: '100vh', opacity: 1 }"
          :leave="{ height: 0, opacity: 0 }"
          class="md:hidden overflow-y-auto bg-white absolute left-0 right-0 top-full px-6 shadow-2xl border-t border-gray-100 z-50"
        >
          <div class="flex flex-col gap-6 py-10">
            <div
              v-for="(link, idx) in navLinks"
              :key="link.href"
              v-motion
              :initial="{ x: -20, opacity: 0 }"
              :enter="{ x: 0, opacity: 1, transition: { delay: idx * 50 } }"
            >
              <div v-if="link.isMegaMenu" class="flex flex-col gap-4">
                <span class="text-gray-900 font-bold text-lg">{{ link.label }}</span>
                <div class="grid grid-cols-2 gap-3">
                  <RouterLink
                    v-for="item in businessMenuItemsFlat"
                    :key="item.href"
                    :to="item.href"
                    class="flex items-center gap-2 text-gray-600 hover:text-targo-green transition-colors text-sm"
                    @click="isMenuOpen = false"
                  >
                    <component :is="item.icon" class="w-4 h-4 text-targo-green" />
                    {{ item.label }}
                  </RouterLink>
                </div>
              </div>
              <div v-else-if="link.submenu" class="flex flex-col gap-4">
                <span class="text-gray-900 font-bold text-lg">{{ link.label }}</span>
                <div class="pl-4 flex flex-col gap-4 py-2 border-l-2 border-targo-green/20">
                  <RouterLink
                    v-for="sublink in link.submenu"
                    :key="sublink.href"
                    :to="sublink.href"
                    class="text-gray-600 hover:text-targo-green transition-colors text-base"
                    @click="isMenuOpen = false"
                  >
                    {{ sublink.label }}
                  </RouterLink>
                </div>
              </div>
              <RouterLink
                v-else
                :to="link.href"
                class="text-gray-900 hover:text-targo-green transition-colors font-bold text-lg"
                @click="isMenuOpen = false"
              >
                {{ link.label }}
              </RouterLink>
            </div>

            <div
              v-motion
              :initial="{ y: 20, opacity: 0 }"
              :enter="{ y: 0, opacity: 1, transition: { delay: 300 } }"
              class="flex flex-col gap-4 pt-10 border-t border-gray-100"
            >
              <Button variant="outline" class="w-full border-gray-200 text-gray-700 hover:bg-gray-50 bg-white h-14 text-lg font-semibold shadow-sm" as-child>
                <a href="https://store.targo.ca/clients" target="_blank" rel="noopener noreferrer">
                  <User class="w-5 h-5 mr-2" />
                  Mon compte
                </a>
              </Button>
              <Button class="w-full gradient-targo text-white h-14 text-lg font-bold glow-targo border-none" as-child>
                <a href="/#contact">Nous joindre</a>
              </Button>

              <div class="flex flex-col gap-3 mt-4 text-gray-500">
                <a href="tel:514.448.0773" class="flex items-center gap-3">
                  <div class="w-10 h-10 rounded-full bg-targo-green/10 flex items-center justify-center">
                    <Phone class="w-5 h-5 text-targo-green" />
                  </div>
                  <span class="font-semibold text-gray-900">514.448.0773</span>
                </a>
                <a href="mailto:support@targo.ca" class="flex items-center gap-3">
                  <div class="w-10 h-10 rounded-full bg-targo-green/10 flex items-center justify-center">
                    <Mail class="w-5 h-5 text-targo-green" />
                  </div>
                  <span class="font-semibold text-gray-900">support@targo.ca</span>
                </a>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </nav>
  </header>
</template>
