// components/sections/StickyNav.tsx
// Horizontal navigation bar with anchor links to page sections
// Supports 3 modes: fixed-top, fixed-bottom, inline
// Uses position:fixed (not sticky) so it works inside any Puck wrapper
'use client';

import React, { useState, useEffect, useRef } from 'react';

type ThemeKey = 'default' | 'warm' | 'professional' | 'ocean' | 'forest';
type PositionKey = 'top' | 'bottom' | 'inline';

interface ThemeStyles {
  bar: string;
  fixedBar: string;
  link: string;
  linkActive: string;
  linkHover: string;
  activePill: string;
  indicator: string;
  shadow: string;
}

const THEMES: Record<ThemeKey, ThemeStyles> = {
  default: {
    bar: 'bg-white border border-slate-200 shadow-sm rounded-xl',
    fixedBar: 'bg-white/95 backdrop-blur-md border-b border-slate-200 shadow-md',
    link: 'text-slate-600 font-medium',
    linkActive: 'text-white font-bold',
    linkHover: 'hover:text-crimson-red hover:bg-crimson-red/5',
    activePill: 'bg-crimson-red shadow-lg shadow-crimson-red/25',
    indicator: 'bg-crimson-red',
    shadow: 'shadow-lg shadow-slate-200/50',
  },
  warm: {
    bar: 'bg-white border border-orange-200 shadow-sm rounded-xl',
    fixedBar: 'bg-white/95 backdrop-blur-md border-b border-orange-200 shadow-md',
    link: 'text-slate-500 font-medium',
    linkActive: 'text-white font-bold',
    linkHover: 'hover:text-orange-500 hover:bg-orange-50',
    activePill: 'bg-gradient-to-r from-orange-500 to-red-500 shadow-lg shadow-orange-500/25',
    indicator: 'bg-orange-500',
    shadow: 'shadow-lg shadow-orange-200/50',
  },
  professional: {
    bar: 'bg-slate-900 border border-slate-700 shadow-sm rounded-xl',
    fixedBar: 'bg-slate-900/95 backdrop-blur-md border-b border-slate-700 shadow-md',
    link: 'text-slate-400 font-medium',
    linkActive: 'text-slate-900 font-bold',
    linkHover: 'hover:text-white hover:bg-white/10',
    activePill: 'bg-amber-400 shadow-lg shadow-amber-400/25',
    indicator: 'bg-amber-400',
    shadow: 'shadow-lg shadow-slate-800/50',
  },
  ocean: {
    bar: 'bg-white border border-blue-200 shadow-sm rounded-xl',
    fixedBar: 'bg-white/95 backdrop-blur-md border-b border-blue-200 shadow-md',
    link: 'text-slate-500 font-medium',
    linkActive: 'text-white font-bold',
    linkHover: 'hover:text-blue-500 hover:bg-blue-50',
    activePill: 'bg-gradient-to-r from-blue-600 to-indigo-600 shadow-lg shadow-blue-600/25',
    indicator: 'bg-blue-600',
    shadow: 'shadow-lg shadow-blue-200/50',
  },
  forest: {
    bar: 'bg-white border border-emerald-200 shadow-sm rounded-xl',
    fixedBar: 'bg-white/95 backdrop-blur-md border-b border-emerald-200 shadow-md',
    link: 'text-slate-500 font-medium',
    linkActive: 'text-white font-bold',
    linkHover: 'hover:text-emerald-500 hover:bg-emerald-50',
    activePill: 'bg-gradient-to-r from-emerald-600 to-teal-600 shadow-lg shadow-emerald-600/25',
    indicator: 'bg-emerald-600',
    shadow: 'shadow-lg shadow-emerald-200/50',
  },
};

interface NavItem {
  label: string;
  anchorId: string;
}

interface StickyNavProps {
  items?: NavItem[];
  position?: PositionKey;
  theme?: ThemeKey;
  // Legacy prop for backward compat
  sticky?: boolean;
}

export function StickyNav({
  items = [],
  position: positionProp,
  theme = 'default',
  sticky,
}: StickyNavProps) {
  // Backward compat: if old `sticky` boolean was passed but no `position`,
  // map it: sticky=true → 'top', sticky=false → 'inline'
  const position: PositionKey = positionProp
    ? positionProp
    : sticky === false
      ? 'inline'
      : sticky === true
        ? 'top'
        : 'top';

  const t = THEMES[theme] || THEMES.default;
  const [activeId, setActiveId] = useState<string>('');
  const [isVisible, setIsVisible] = useState(position === 'inline');
  const placeholderRef = useRef<HTMLDivElement>(null);

  // For fixed modes: show the bar once the user scrolls past the placeholder position
  useEffect(() => {
    if (position === 'inline' || typeof window === 'undefined') {
      setIsVisible(true);
      return;
    }

    // For bottom mode, always show
    if (position === 'bottom') {
      setIsVisible(true);
      return;
    }

    // For top mode, show after scrolling past the placeholder
    const handleScroll = () => {
      if (placeholderRef.current) {
        const rect = placeholderRef.current.getBoundingClientRect();
        setIsVisible(rect.top < 0);
      } else {
        setIsVisible(window.scrollY > 100);
      }
    };

    // Show immediately if already scrolled
    handleScroll();
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, [position]);

  // Intersection Observer to highlight current section
  useEffect(() => {
    if (typeof window === 'undefined' || items.length === 0) return;

    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        }
      },
      { rootMargin: '-100px 0px -60% 0px', threshold: 0.1 }
    );

    const timer = setTimeout(() => {
      items.forEach((item) => {
        const cleanId = item.anchorId.replace(/^#/, '');
        const el = document.getElementById(cleanId);
        if (el) observer.observe(el);
      });
    }, 500);

    return () => {
      clearTimeout(timer);
      observer.disconnect();
    };
  }, [items]);

  const handleClick = (rawAnchorId: string) => {
    const anchorId = rawAnchorId.replace(/^#/, '');
    setActiveId(anchorId);
    
    // In Puck Editor, scrolling might be blocked by the editor's click handler.
    // Try to scroll the window.
    const el = document.getElementById(anchorId);
    if (el) {
      const offset = position === 'top' ? 80 : position === 'bottom' ? 40 : 40;
      const y = el.getBoundingClientRect().top + window.scrollY - offset;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  };

  if (items.length === 0) {
    return (
      <div className="w-full py-4">
        <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center py-4 text-text-light-gray italic text-sm bg-white rounded-xl border border-slate-200 shadow-sm">
            Add navigation items using the editor panel →
          </div>
        </div>
      </div>
    );
  }

  // ── Inline mode ──────────────────────────────────────────────────
  if (position === 'inline') {
    return (
      <div className="w-full py-2">
        <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <nav className={`${t.bar} transition-all duration-300`}>
            <div className="flex items-center gap-1 overflow-x-auto scrollbar-hide py-2 px-2">
              {items.map((item, i) => {
                const isActive = activeId === item.anchorId;
                return (
                  <button
                    key={i}
                    onClick={() => handleClick(item.anchorId)}
                    className={`relative px-5 py-2.5 text-sm whitespace-nowrap transition-all duration-300 rounded-lg ${
                      isActive
                        ? `${t.linkActive} ${t.activePill}`
                        : `${t.link} ${t.linkHover}`
                    }`}
                  >
                    {item.label}
                  </button>
                );
              })}
            </div>
          </nav>
        </div>
      </div>
    );
  }

  // ── Fixed top / bottom mode ──────────────────────────────────────
  const fixedClasses = position === 'top'
    ? 'fixed top-0 left-0 right-0 z-[999]'
    : 'fixed bottom-0 left-0 right-0 z-[999]';

  const borderSide = position === 'top' ? 'border-b' : 'border-t';

  return (
    <>
      {/* Placeholder: reserves space where the nav was placed and acts as scroll trigger */}
      <div ref={placeholderRef} className="w-full py-2">
        <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className={`${t.bar} transition-all duration-300`}>
            <div className="flex items-center gap-1 overflow-x-auto scrollbar-hide py-2 px-2">
              {items.map((item, i) => {
                const isActive = activeId === item.anchorId;
                return (
                  <button
                    key={i}
                    onClick={() => handleClick(item.anchorId)}
                    className={`relative px-5 py-2.5 text-sm whitespace-nowrap transition-all duration-300 rounded-lg ${
                      isActive
                        ? `${t.linkActive} ${t.activePill}`
                        : `${t.link} ${t.linkHover}`
                    }`}
                  >
                    {item.label}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* Fixed bar — rendered via portal-like absolute positioning */}
      <div
        className={`${fixedClasses} transition-all duration-300 ${
          isVisible
            ? 'translate-y-0 opacity-100'
            : position === 'top'
              ? '-translate-y-full opacity-0'
              : 'translate-y-full opacity-0'
        }`}
      >
        <nav
          className={`${t.fixedBar} ${borderSide} ${t.shadow} transition-all duration-300`}
        >
          <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center gap-1 overflow-x-auto scrollbar-hide py-2">
              {items.map((item, i) => {
                const isActive = activeId === item.anchorId;
                return (
                  <button
                    key={i}
                    onClick={() => handleClick(item.anchorId)}
                    className={`relative px-5 py-2.5 text-sm whitespace-nowrap transition-all duration-300 rounded-lg ${
                      isActive
                        ? `${t.linkActive} ${t.activePill}`
                        : `${t.link} ${t.linkHover}`
                    }`}
                  >
                    {item.label}
                  </button>
                );
              })}
            </div>
          </div>
        </nav>
      </div>
    </>
  );
}
