'use client';

import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';

export default function ShopifyNavMenu() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // Normalize path by stripping subpath prefixes (/meta-connector or /meta_connector)
  const normalizePath = useCallback((p: string | null | undefined): string => {
    if (!p) return '/';
    let clean = p.trim();
    // Strip all repeated subpath prefixes
    clean = clean.replace(/^(\/meta[-_]connector)+/i, '') || '/';
    clean = clean.split('?')[0];
    if (clean.length > 1 && clean.endsWith('/')) {
      clean = clean.slice(0, -1);
    }
    return clean || '/';
  }, []);

  const routePath = useMemo(() => normalizePath(pathname), [pathname, normalizePath]);

  // Reactive state for immediate active menu selection on first click (0ms latency)
  const [activePath, setActivePath] = useState<string>(routePath);

  // Keep activePath synchronized when pathname changes (Back/Forward or completed navigation)
  useEffect(() => {
    setActivePath(routePath);
  }, [routePath]);

  // Synchronize immediately on browser Back / Forward (popstate)
  useEffect(() => {
    const handlePopState = () => {
      if (typeof window === 'undefined') return;
      const browserPath = normalizePath(window.location.pathname);
      const targetSearch = window.location.search;
      setActivePath(browserPath);
      if (browserPath && browserPath !== routePath) {
        const nextJsRoute = `${browserPath === '/' ? '' : browserPath}${targetSearch}` || '/';
        router.push(nextJsRoute);
      }
    };

    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [normalizePath, routePath, router]);

  // Intercept click on navigation menu elements immediately on first click
  useEffect(() => {
    const handleNavClick = (e: MouseEvent) => {
      const target = (e.target as HTMLElement).closest('ui-nav-menu a, s-app-nav a, s-link, ui-nav-menu s-link');
      if (!target) return;

      const rawHref = target.getAttribute('href');
      if (!rawHref) return;

      const targetPath = normalizePath(rawHref);

      // 1. UPDATE ACTIVE STATE IMMEDIATELY ON FIRST CLICK
      setActivePath(targetPath);

      if (rawHref.startsWith('/') && !rawHref.startsWith('//')) {
        e.preventDefault();

        // Preserve current query parameters (such as ?shop=...&host=...)
        const currentSearch = (typeof window !== 'undefined' && window.location.search)
          ? window.location.search
          : (searchParams?.toString() ? `?${searchParams.toString()}` : '');

        // Ensure every destination URL preserves the /meta-connector subpath prefix
        const cleanSubPath = targetPath === '/' ? '' : targetPath;
        const targetUrl = `/meta-connector${cleanSubPath}${currentSearch}`;
        const nextJsRoute = `${cleanSubPath || '/'}${currentSearch}`;

        // Synchronously update window.history so App Bridge v4 catches the URL change on first click
        try {
          if (typeof window !== 'undefined') {
            window.history.pushState({ path: targetPath }, '', targetUrl);
          }
        } catch {}

        // Navigate client-side in Next.js (Next.js automatically prefixes basePath)
        router.push(nextJsRoute);
      }
    };

    // Use capture phase (true) to intercept immediately before any child suppression
    document.addEventListener('click', handleNavClick, true);
    return () => document.removeEventListener('click', handleNavClick, true);
  }, [normalizePath, router, searchParams]);

  // Determine active states for App Bridge highlighting from reactive activePath
  const isHomeActive = activePath === '/' || activePath === '' || activePath === '/meta-connector';
  const isPixelActive = activePath === '/pixel' || activePath.startsWith('/pixel');
  const isCatalogActive = activePath === '/catalog' || activePath.startsWith('/catalog');
  const isTemplatesActive = activePath === '/templates' || activePath.startsWith('/templates');
  const isSettingsActive = activePath === '/settings' || activePath.startsWith('/settings');
  const isPricingActive = activePath === '/pricing' || activePath.startsWith('/pricing');
  const isHelpActive = activePath === '/help' || activePath.startsWith('/help');

  // Hardcode canonical subpath links so Shopify App Bridge and Shopify Admin sidebar ALWAYS receive /meta-connector/...
  const homeHref = '/meta-connector';
  const pixelHref = '/meta-connector/pixel';
  const catalogHref = '/meta-connector/catalog';
  const templatesHref = '/meta-connector/templates';
  const settingsHref = '/meta-connector/settings';
  const pricingHref = '/meta-connector/pricing';
  const helpHref = '/meta-connector/help';

  // Dynamic key ensures that changing activePath forces the custom web component
  // to re-evaluate its internal state binder immediately without requiring a second click
  const componentKey = `app-nav-${activePath}`;

  return (
    <>
      {/* Modern Shopify App Bridge v4 Navigation Component */}
      <s-app-nav key={`s-${componentKey}`}>
        <s-link href={homeHref} rel="home" {...(isHomeActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Home
        </s-link>
        <s-link href={pixelHref} {...(isPixelActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Facebook Pixel &amp; CAPI
        </s-link>
        <s-link href={catalogHref} {...(isCatalogActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Catalog &amp; Feeds
        </s-link>
        <s-link href={templatesHref} {...(isTemplatesActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Product Templates
        </s-link>
        <s-link href={settingsHref} {...(isSettingsActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          App Embed &amp; Settings
        </s-link>
        <s-link href={pricingHref} {...(isPricingActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Pricing &amp; Plans
        </s-link>
        <s-link href={helpHref} {...(isHelpActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Help &amp; Guides
        </s-link>
      </s-app-nav>

      {/* Legacy / Compatible Shopify App Bridge Navigation Component */}
      <ui-nav-menu key={`ui-${componentKey}`}>
        <a href={homeHref} rel="home" {...(isHomeActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Home
        </a>
        <a href={pixelHref} {...(isPixelActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Facebook Pixel &amp; CAPI
        </a>
        <a href={catalogHref} {...(isCatalogActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Catalog &amp; Feeds
        </a>
        <a href={templatesHref} {...(isTemplatesActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Product Templates
        </a>
        <a href={settingsHref} {...(isSettingsActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          App Embed &amp; Settings
        </a>
        <a href={pricingHref} {...(isPricingActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Pricing &amp; Plans
        </a>
        <a href={helpHref} {...(isHelpActive ? { active: 'true', 'aria-current': 'page' } : {})}>
          Help &amp; Guides
        </a>
      </ui-nav-menu>
    </>
  );
}
