'use client';

// Bottom Navigation Bar — NiceUI (MIT) · https://niceui.dev/c/marketing/bottom-navigation
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, createElement, type SVGProps } from 'react';

function cn(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(' ');
}

// Icons from Lucide (ISC licence, lucide.dev), inlined so there is nothing to install.
type NiceIconProps = SVGProps<SVGSVGElement> & { size?: number | string; absoluteStrokeWidth?: boolean };
type LucideIcon = (props: NiceIconProps) => JSX.Element;
type LucideProps = NiceIconProps;
const niceIcon = (node: Array<[string, Record<string, string>]>): LucideIcon =>
  function Icon({ size = 24, strokeWidth = 2, absoluteStrokeWidth, children, ...rest }: NiceIconProps) {
    const sw = absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth;
    return createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, ...rest }, ...node.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })), children);
  };
const Bell = niceIcon([["path",{"d":"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}],["path",{"d":"M10.3 21a1.94 1.94 0 0 0 3.4 0"}]]);
const Compass = niceIcon([["path",{"d":"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z"}],["circle",{"cx":"12","cy":"12","r":"10"}]]);
const Heart = niceIcon([["path",{"d":"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"}]]);
const Home = niceIcon([["path",{"d":"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{"d":"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]]);
const MessageCircle = niceIcon([["path",{"d":"M7.9 20A9 9 0 1 0 4 16.1L2 22Z"}]]);
const Plus = niceIcon([["path",{"d":"M5 12h14"}],["path",{"d":"M12 5v14"}]]);
const Search = niceIcon([["circle",{"cx":"11","cy":"11","r":"8"}],["path",{"d":"m21 21-4.3-4.3"}]]);
const User = niceIcon([["path",{"d":"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{"cx":"12","cy":"7","r":"4"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = ".focus-ring{outline:none}.focus-ring:focus-visible{box-shadow:0 0 0 2px #000,0 0 0 4px rgba(14,165,233,.6)}";
if (typeof document !== 'undefined' && !document.getElementById('niceui-css-10x759f')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-10x759f';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/marketing/nav/BottomNavigation.tsx ───────────────
export type BottomNavItem = { label: string; icon: LucideIcon; badge?: number };

const ITEMS: BottomNavItem[] = [
  { label: 'Home', icon: Home },
  { label: 'Explore', icon: Compass },
  { label: 'Inbox', icon: MessageCircle, badge: 3 },
  { label: 'Alerts', icon: Bell, badge: 12 },
  { label: 'Profile', icon: User },
];

function Badge({ n }: { n: number }) {
  return (
    <span key={n} className="absolute -right-2 -top-1.5 min-w-[17px] rounded-full bg-rose-500 px-1 text-center text-[10px] font-semibold leading-[17px] text-white ring-2 ring-[#000000] motion-safe:animate-[bn-pop_.35s_cubic-bezier(.3,1.6,.5,1)]">
      {n > 9 ? '9+' : n}
    </span>
  );
}

/** Arrow keys move focus between tabs, like a real tablist. */
function onArrows(e: ReactKeyboardEvent<HTMLDivElement>) {
  const tabs = [...e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')];
  const i = tabs.indexOf(document.activeElement as HTMLButtonElement);
  if (i < 0) return;
  const next = e.key === 'ArrowRight' ? (i + 1) % tabs.length : e.key === 'ArrowLeft' ? (i - 1 + tabs.length) % tabs.length : -1;
  if (next >= 0) {
    e.preventDefault();
    tabs[next].focus();
    tabs[next].click();
  }
}

export type BottomNavigationProps = {
  items?: BottomNavItem[];
  /** 'blob': a glowing pill slides under the active tab. 'notch': the bar dips around a raised active icon. */
  variant?: 'blob' | 'notch';
  defaultActive?: number;
  onChange?: (index: number) => void;
  className?: string;
};

/**
 * A floating bottom navigation bar for mobile apps: icons with labels, badge
 * counts and an animated active indicator that glides between tabs.
 */
export function BottomNavigation({ items = ITEMS, variant = 'blob', defaultActive = 0, onChange, className }: BottomNavigationProps) {
  const [active, setActive] = useState(defaultActive);
  const rowRef = useRef<HTMLDivElement>(null);
  const [x, setX] = useState<number | null>(null);
  const [w, setW] = useState(0);

  useLayoutEffect(() => {
    const el = rowRef.current?.children[active] as HTMLElement | undefined;
    if (el) {
      setX(el.offsetLeft + el.offsetWidth / 2);
      setW(el.offsetWidth);
    }
  }, [active, items.length]);

  const pick = (i: number) => {
    setActive(i);
    onChange?.(i);
  };

  return (
    <nav aria-label="Primary" className={cn('relative w-full max-w-[380px]', className)}>
      <style>{`@keyframes bn-pop{from{transform:scale(.4)}to{transform:scale(1)}}`}</style>
      {variant === 'notch' && x !== null && (
        // the raised disc that sits in the notch
        <span
          aria-hidden
          className="absolute -top-5 z-10 grid h-12 w-12 -translate-x-1/2 place-items-center rounded-full bg-[#7dd3fc] text-[#000000] shadow-[0_10px_30px_-6px_rgba(56,189,248,.8)] transition-[left] duration-500 ease-[cubic-bezier(.3,1.3,.5,1)] motion-reduce:transition-none"
          style={{ left: x }}
        >
          {(() => {
            const Icon = items[active].icon;
            return <Icon className="h-5 w-5" strokeWidth={2} />;
          })()}
        </span>
      )}
      <div
        className="relative overflow-hidden rounded-[26px] border border-white/[.08] bg-[#0b0c0e]/85 shadow-[0_24px_50px_-20px_rgba(0,0,0,.9),inset_0_1px_0_rgba(255,255,255,.06)] backdrop-blur-xl"
        style={
          variant === 'notch' && x !== null
            ? {
                WebkitMaskImage: `radial-gradient(circle 30px at ${x}px 0px, transparent 29px, #000 30px)`,
                maskImage: `radial-gradient(circle 30px at ${x}px 0px, transparent 29px, #000 30px)`,
                transition: 'none',
              }
            : undefined
        }
      >
        {variant === 'blob' && x !== null && (
          <span
            aria-hidden
            className="absolute top-2 h-[calc(100%-16px)] -translate-x-1/2 rounded-[18px] bg-[#7dd3fc]/[.13] shadow-[inset_0_0_0_1px_rgba(125,211,252,.25),0_0_24px_rgba(56,189,248,.18)] transition-[left] duration-500 ease-[cubic-bezier(.3,1.3,.5,1)] motion-reduce:transition-none"
            style={{ left: x, width: Math.max(0, w - 10) }}
          />
        )}
        <div ref={rowRef} role="tablist" aria-label="Sections" onKeyDown={onArrows} className="relative grid h-[68px]" style={{ gridTemplateColumns: `repeat(${items.length}, 1fr)` }}>
          {items.map((it, i) => {
            const on = active === i;
            const Icon = it.icon;
            return (
              <button
                key={it.label}
                role="tab"
                aria-selected={on}
                tabIndex={on ? 0 : -1}
                onClick={() => pick(i)}
                className="group relative flex flex-col items-center justify-center gap-1 outline-none focus-visible:after:absolute focus-visible:after:inset-1.5 focus-visible:after:rounded-2xl focus-visible:after:ring-1 focus-visible:after:ring-[#7dd3fc]/60"
              >
                <span className={cn('relative transition-all duration-300 motion-reduce:transition-none', variant === 'notch' && on && 'translate-y-1 opacity-0', on ? 'text-[#bae6fd]' : 'text-[#8b9099] group-hover:text-[#c9cdd3]')}>
                  <Icon className={cn('h-[22px] w-[22px] transition-transform duration-300', on && variant === 'blob' && 'scale-110')} strokeWidth={on ? 2.1 : 1.7} />
                  {it.badge ? <Badge n={it.badge} /> : null}
                </span>
                <span className={cn('text-[10.5px] font-medium tracking-wide transition-colors', on ? 'text-[#f3f4f6]' : 'text-[#6b7079]', variant === 'notch' && on && 'translate-y-2')}>{it.label}</span>
              </button>
            );
          })}
        </div>
      </div>
    </nav>
  );
}

export type BottomNavigationFabProps = { onAction?: () => void; className?: string };

/** A bottom navigation bar with a raised floating action button in the middle. */
export function BottomNavigationFab({ onAction, className }: BottomNavigationFabProps) {
  const left: BottomNavItem[] = [
    { label: 'Home', icon: Home },
    { label: 'Search', icon: Search },
  ];
  const right: BottomNavItem[] = [
    { label: 'Saved', icon: Heart, badge: 2 },
    { label: 'Me', icon: User },
  ];
  const [active, setActive] = useState('Home');
  const [spin, setSpin] = useState(false);
  const tab = (it: BottomNavItem) => {
    const on = active === it.label;
    const Icon = it.icon;
    return (
      <button key={it.label} role="tab" aria-selected={on} onClick={() => setActive(it.label)} className="relative flex flex-col items-center justify-center gap-1 outline-none focus-visible:text-[#f3f4f6]">
        <span className={cn('relative transition-colors', on ? 'text-[#bae6fd]' : 'text-[#8b9099] hover:text-[#c9cdd3]')}>
          <Icon className="h-[21px] w-[21px]" strokeWidth={on ? 2.1 : 1.7} />
          {it.badge ? <Badge n={it.badge} /> : null}
        </span>
        <span className={cn('text-[10.5px] font-medium', on ? 'text-[#f3f4f6]' : 'text-[#6b7079]')}>{it.label}</span>
        <span aria-hidden className={cn('absolute bottom-1.5 h-1 w-1 rounded-full bg-[#7dd3fc] transition-all duration-300', on ? 'scale-100 opacity-100' : 'scale-0 opacity-0')} />
      </button>
    );
  };
  return (
    <nav aria-label="Primary" className={cn('relative w-full max-w-[380px] pt-6', className)}>
      <div
        className="rounded-[26px] border border-white/[.08] bg-[#0b0c0e]/85 shadow-[0_24px_50px_-20px_rgba(0,0,0,.9)] backdrop-blur-xl"
        style={{ WebkitMaskImage: 'radial-gradient(circle 38px at 50% 0, transparent 37px, #000 38px)', maskImage: 'radial-gradient(circle 38px at 50% 0, transparent 37px, #000 38px)' }}
      >
        <div role="tablist" aria-label="Sections" className="grid h-[68px] grid-cols-5">
          {left.map(tab)}
          <span aria-hidden />
          {right.map(tab)}
        </div>
      </div>
      <button
        onClick={() => {
          setSpin(true);
          onAction?.();
          window.setTimeout(() => setSpin(false), 450);
        }}
        aria-label="Create"
        className="focus-ring absolute left-1/2 top-0 grid h-14 w-14 -translate-x-1/2 place-items-center rounded-full bg-[#7dd3fc] text-[#000000] shadow-[0_12px_30px_-6px_rgba(56,189,248,.85),inset_0_1px_0_rgba(255,255,255,.6)] transition-transform duration-200 hover:scale-105 active:scale-95"
      >
        <Plus className={cn('h-6 w-6 transition-transform duration-500 ease-[cubic-bezier(.3,1.4,.5,1)] motion-reduce:transition-none', spin && 'rotate-90')} strokeWidth={2.4} />
      </button>
    </nav>
  );
}

/* ——— demo ——— */

function Phone({ children, label }: { children: ReactNode; label: string }) {
  return (
    <div className="flex flex-col items-center gap-3">
      <div className="relative flex h-[360px] w-[300px] flex-col justify-end overflow-hidden rounded-[34px] border border-white/[.08] bg-[radial-gradient(90%_60%_at_50%_0%,rgba(56,189,248,.12),transparent),#050607] p-3">
        <div className="absolute inset-x-5 top-6 space-y-2.5" aria-hidden>
          <div className="h-3 w-24 rounded bg-white/10" />
          <div className="h-20 rounded-2xl bg-white/[.04]" />
          <div className="grid grid-cols-2 gap-2.5">
            <div className="h-16 rounded-xl bg-white/[.03]" />
            <div className="h-16 rounded-xl bg-white/[.03]" />
          </div>
        </div>
        <div className="relative flex justify-center">{children}</div>
      </div>
      <p className="font-mono text-[10.5px] uppercase tracking-[0.16em] text-[#6b7079]">{label}</p>
    </div>
  );
}

export function BottomNavigationDemo() {
  return (
    <div className="flex flex-wrap items-start justify-center gap-6">
      <Phone label="Sliding blob">
        <BottomNavigation variant="blob" />
      </Phone>
      <Phone label="Notch">
        <BottomNavigation variant="notch" defaultActive={2} />
      </Phone>
      <Phone label="Floating action button">
        <BottomNavigationFab />
      </Phone>
    </div>
  );
}
