'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { clsx } from 'clsx';
import { useBranding } from '@/context/BrandingContext';
import AppLogo from '@/components/common/AppLogo';

const NAV_ITEMS = [
  { href: '/', label: 'Overview', faIcon: 'fa-solid fa-gauge-high' },
  { href: '/onboarding', label: 'Onboarding Wizard', faIcon: 'fa-solid fa-wand-magic-sparkles', badge: 'Guide' },
  { href: '/catalog', label: 'Catalog Feeds', faIcon: 'fa-solid fa-layer-group' },
  { href: '/pixel', label: 'Pixel & CAPI', faIcon: 'fa-solid fa-satellite-dish' },
  { href: '/events', label: 'Live Events', faIcon: 'fa-solid fa-bolt' },
  { href: '/pricing', label: 'Pricing & Plans', faIcon: 'fa-solid fa-credit-card', badge: 'Plans' },
  { href: '/settings', label: 'Settings', faIcon: 'fa-solid fa-gear' },
];

export default function Sidebar() {
  const pathname = usePathname();
  const { branding } = useBranding();
  const [optimisticPath, setOptimisticPath] = useState<string | null>(null);

  useEffect(() => {
    setOptimisticPath(null);
  }, [pathname]);

  useEffect(() => {
    const handlePopState = () => setOptimisticPath(null);
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, []);

  const activePath = optimisticPath || pathname || '/';

  const isItemActive = (href: string) => {
    let current = activePath.split('?')[0];
    if (current.startsWith('/meta-connector')) current = current.replace('/meta-connector', '') || '/';
    if (current.startsWith('/meta_connector')) current = current.replace('/meta_connector', '') || '/';

    let target = href.split('?')[0];
    if (target.startsWith('/meta-connector')) target = target.replace('/meta-connector', '') || '/';
    if (target.startsWith('/meta_connector')) target = target.replace('/meta_connector', '') || '/';

    if (target === '/pixel' || target === '/') {
      return current === '/' || current === '/pixel';
    }
    return current === target || current.startsWith(`${target}/`);
  };

  return (
    <aside className="w-64 bg-white border-r border-slate-200 flex flex-col justify-between shrink-0 min-h-screen">
      <div>
        {/* App Logo & Title */}
        <div className="h-16 px-6 border-b border-slate-100 flex items-center gap-3">
          <AppLogo size="md" />
          <div className="min-w-0">
            <h1 className="font-semibold text-sm tracking-tight text-slate-900 leading-tight truncate">
              {branding.appName}
            </h1>
            <p className="text-[11px] font-medium text-emerald-600 flex items-center gap-1">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span> App Store Ready
            </p>
          </div>
        </div>

        {/* Navigation Links */}
        <nav className="p-3 space-y-1">
          {NAV_ITEMS.map((item) => {
            const isActive = isItemActive(item.href);

            return (
              <Link
                key={item.href}
                href={item.href}
                onClick={() => setOptimisticPath(item.href)}
                className={clsx(
                  'flex items-center justify-between px-3.5 py-2.5 rounded-lg text-sm font-medium transition-colors',
                  isActive
                    ? 'bg-theme/10 text-theme font-semibold'
                    : 'text-slate-600 hover:text-slate-900 hover:bg-slate-50'
                )}
              >
                <div className="flex items-center gap-3">
                  <i className={clsx(item.faIcon, 'w-4 text-center text-xs', isActive ? 'text-theme' : 'text-slate-400')} />
                  <span>{item.label}</span>
                </div>
                {item.badge && (
                  <span className="px-2 py-0.5 text-[10px] uppercase tracking-wider font-bold rounded-full bg-theme/10 text-theme border border-theme/20">
                    {item.badge}
                  </span>
                )}
              </Link>
            );
          })}
        </nav>
      </div>

      {/* Footer Info */}
      <div className="p-4 border-t border-slate-100 bg-slate-50/50 space-y-2">
        <div className="flex items-center gap-2 text-xs text-slate-500">
          <i className="fa-solid fa-shield-halved text-emerald-600 text-sm" />
          <span>AES-256 Encrypted</span>
        </div>
        <a
          href="https://business.facebook.com/commerce"
          target="_blank"
          rel="noreferrer"
          className="text-xs font-medium text-theme hover:underline flex items-center gap-1.5"
        >
          <span>Meta Commerce Manager</span>
          <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
        </a>
      </div>
    </aside>
  );
}
