'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import {
  Terminal, BookOpen, Search, ExternalLink, X, Hash
} from 'lucide-react';

// ── Search index type (import from docs page if co-located) ──────────────────
export interface SearchEntry {
  id: string;
  label: string;
  section: string;
  keywords: string[];
}

interface DocsHeaderProps {
  /** Pass the full search index from the docs page */
  searchIndex: SearchEntry[];
  /** Pinned section IDs shown in the empty search state */
  pinnedIds?: string[];
}

// ── Inline search modal ───────────────────────────────────────────────────────

function score(entry: SearchEntry, q: string): number {
  const label = entry.label.toLowerCase();
  if (label === q)            return 100;
  if (label.startsWith(q))    return 80;
  if (label.includes(q))      return 60;
  if (entry.keywords.some(k => k === q))           return 50;
  if (entry.keywords.some(k => k.startsWith(q)))   return 40;
  if (entry.keywords.some(k => k.includes(q)))     return 30;
  if (entry.section.toLowerCase().includes(q))     return 10;
  return 0;
}

function highlight(text: string, q: string): React.ReactNode {
  if (!q) return text;
  const idx = text.toLowerCase().indexOf(q.toLowerCase());
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <mark className="bg-yellow-100 text-yellow-900 rounded px-0.5 not-italic">
        {text.slice(idx, idx + q.length)}
      </mark>
      {text.slice(idx + q.length)}
    </>
  );
}

function SearchModal({
  searchIndex,
  pinnedIds = [],
  onClose,
}: {
  searchIndex: SearchEntry[];
  pinnedIds?: string[];
  onClose: () => void;
}) {
  const [query,     setQuery]     = useState('');
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef  = useRef<HTMLInputElement>(null);
  const listRef   = useRef<HTMLUListElement>(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  const results: SearchEntry[] = query.trim().length > 0
    ? searchIndex
        .map(e => ({ e, s: score(e, query.trim().toLowerCase()) }))
        .filter(r => r.s > 0)
        .sort((a, b) => b.s - a.s)
        .slice(0, 8)
        .map(r => r.e)
    : [];

  const grouped = results.reduce<Record<string, SearchEntry[]>>((acc, e) => {
    (acc[e.section] ??= []).push(e); return acc;
  }, {});

  useEffect(() => { setActiveIdx(0); }, [query]);

  const navigate = (id: string) => {
    onClose();
    setTimeout(() => {
      document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 50);
  };

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') { onClose(); return; }
      if (!results.length)    return;
      if (e.key === 'ArrowDown') { e.preventDefault(); setActiveIdx(i => Math.min(i + 1, results.length - 1)); }
      if (e.key === 'ArrowUp')   { e.preventDefault(); setActiveIdx(i => Math.max(i - 1, 0)); }
      if (e.key === 'Enter')     { e.preventDefault(); navigate(results[activeIdx]?.id ?? ''); }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [results, activeIdx, onClose]);

  useEffect(() => {
    listRef.current?.querySelector(`[data-idx="${activeIdx}"]`)?.scrollIntoView({ block: 'nearest' });
  }, [activeIdx]);

  // Flat index counter across groups for keyboard nav
  let flatIdx = 0;

  return (
    <div
      className="fixed inset-0 z-200 flex items-start justify-center pt-[12vh]"
      onClick={onClose}
    >
      <div className="absolute inset-0 bg-gray-900/30 backdrop-blur-sm" />

      <div
        className="relative w-full max-w-xl mx-4 bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-2xl"
        onClick={e => e.stopPropagation()}
        style={{ fontFamily: "'DM Sans', system-ui, sans-serif" }}
      >
        {/* Input */}
        <div className="flex items-center gap-3 px-4 py-3.5 border-b border-gray-100">
          <Search className="w-4 h-4 text-gray-400 shrink-0" />
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Search docs — try 'refresh token', 'docker', 'bcrypt'…"
            className="flex-1 bg-transparent text-sm text-gray-900 placeholder-gray-400 outline-none"
          />
          {query
            ? <button onClick={() => setQuery('')} className="p-0.5 rounded hover:bg-gray-100 transition-colors"><X className="w-3.5 h-3.5 text-gray-400" /></button>
            : null
          }
          <button
            onClick={onClose}
            className="text-[10px] text-gray-400 border border-gray-200 rounded px-1.5 py-1 font-mono bg-gray-50 hover:bg-gray-100 transition-colors"
          >
            esc
          </button>
        </div>

        {/* Results */}
        {query.trim().length > 0 ? (
          results.length > 0 ? (
            <ul ref={listRef} className="max-h-80 overflow-y-auto py-2">
              {Object.entries(grouped).map(([section, entries]) => (
                <div key={section}>
                  <li className="px-4 pt-3 pb-1">
                    <span className="text-[10px] font-semibold uppercase tracking-widest text-gray-400">
                      {section}
                    </span>
                  </li>
                  {entries.map(entry => {
                    const idx = flatIdx++;
                    return (
                      <li key={entry.id} data-idx={idx}>
                        <button
                          onClick={() => navigate(entry.id)}
                          onMouseEnter={() => setActiveIdx(idx)}
                          className={`w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors ${
                            activeIdx === idx ? 'bg-indigo-50' : 'hover:bg-gray-50'
                          }`}
                        >
                          <Hash className={`w-3.5 h-3.5 shrink-0 ${activeIdx === idx ? 'text-indigo-400' : 'text-gray-300'}`} />
                          <span className={`text-sm flex-1 ${activeIdx === idx ? 'text-indigo-700 font-medium' : 'text-gray-700'}`}>
                            {highlight(entry.label, query)}
                          </span>
                          {activeIdx === idx && (
                            <span className="text-[10px] font-mono text-indigo-400 border border-indigo-200 rounded px-1.5 py-0.5 bg-indigo-50/50">
                              ↵ go
                            </span>
                          )}
                        </button>
                      </li>
                    );
                  })}
                </div>
              ))}
            </ul>
          ) : (
            <div className="px-4 py-10 text-center">
              <p className="text-sm text-gray-500 mb-1">
                No results for <span className="font-medium text-gray-700">`{query}`</span>
              </p>
              <p className="text-xs text-gray-400">Try a different term or browse the sidebar</p>
            </div>
          )
        ) : (
          /* Empty state */
          <div className="px-4 py-5">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-gray-400 mb-3">
              Quick jump
            </p>
            <div className="grid grid-cols-2 gap-1.5">
              {pinnedIds.map(id => {
                const entry = searchIndex.find(e => e.id === id);
                if (!entry) return null;
                return (
                  <button
                    key={id}
                    onClick={() => navigate(id)}
                    className="flex items-center gap-2.5 px-3 py-2 rounded-lg border border-gray-100 bg-gray-50 hover:bg-indigo-50 hover:border-indigo-200 transition-colors group text-left"
                  >
                    <Hash className="w-3 h-3 text-gray-300 group-hover:text-indigo-400 shrink-0" />
                    <span className="text-xs text-gray-600 group-hover:text-indigo-700 flex-1">{entry.label}</span>
                    <span className="text-[10px] text-gray-400 group-hover:text-indigo-400">{entry.section}</span>
                  </button>
                );
              })}
            </div>
            <p className="text-[10px] text-gray-300 mt-4 text-center">
              ↑ ↓ to navigate · ↵ to jump · esc to close
            </p>
          </div>
        )}

        {/* Footer hint */}
        {query.trim() && results.length > 0 && (
          <div className="border-t border-gray-100 px-4 py-2 flex items-center gap-4 text-[10px] text-gray-300">
            <span>↑ ↓ navigate</span>
            <span>↵ jump</span>
            <span>esc close</span>
            <span className="ml-auto">
              {results.length} result{results.length !== 1 ? 's' : ''}
            </span>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Main header component ─────────────────────────────────────────────────────

export default function DocsHeader({ searchIndex, pinnedIds = [] }: DocsHeaderProps) {
  const [searchOpen, setSearchOpen] = useState(false);

  // ⌘K / Ctrl+K shortcut
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  return (
    <>
      {searchOpen && (
        <SearchModal
          searchIndex={searchIndex}
          pinnedIds={pinnedIds}
          onClose={() => setSearchOpen(false)}
        />
      )}

      <header
        className="fixed top-0 inset-x-0 z-50 h-12 border-b border-gray-100 bg-white/95 backdrop-blur-sm flex items-center px-4 gap-3"
        style={{ fontFamily: "'DM Sans', system-ui, sans-serif" }}
      >
        {/* Logo + breadcrumb */}
        <Link
          href="/"
          className="flex items-center gap-2 shrink-0 group"
          aria-label="NextDash home"
        >
          <div className="w-6 h-6 rounded bg-gray-900 flex items-center justify-center group-hover:bg-gray-700 transition-colors">
            <Terminal className="w-3.5 h-3.5 text-white" />
          </div>
          <span className="font-semibold text-sm text-gray-900">NextDash</span>
        </Link>

        <span className="text-gray-200">/</span>

        <div className="flex items-center gap-1.5">
          <BookOpen className="w-3.5 h-3.5 text-gray-400" />
          <span className="text-sm text-gray-500">Docs</span>
        </div>

        {/* Search button */}
        <button
          onClick={() => setSearchOpen(true)}
          className="ml-4 hidden md:flex items-center gap-2 px-3 py-1.5 bg-gray-50 border border-gray-200 rounded-lg text-xs text-gray-400 hover:bg-white hover:border-gray-300 transition-colors w-52"
          aria-label="Search documentation"
        >
          <Search className="w-3 h-3 shrink-0" />
          <span className="flex-1 text-left">Search docs…</span>
          <span className="font-mono text-gray-300 text-[10px] border border-gray-200 rounded px-1 py-0.5 bg-white">
            ⌘K
          </span>
        </button>

        {/* Mobile search icon */}
        <button
          onClick={() => setSearchOpen(true)}
          className="md:hidden ml-2 p-1.5 rounded-lg text-gray-400 hover:bg-gray-100 transition-colors"
          aria-label="Search documentation"
        >
          <Search className="w-4 h-4" />
        </button>

        {/* Right side */}
        <div className="ml-auto flex items-center gap-4">
          <Link
            href="/demo"
            className="hidden md:flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-900 transition-colors"
          >
            <ExternalLink className="w-3 h-3" />
            Live demo
          </Link>
          <Link
            href="/checkout"
            className="text-xs bg-gray-900 text-white rounded-lg px-3 py-1.5 font-semibold hover:bg-gray-800 transition-colors"
          >
            Buy — $49
          </Link>
        </div>
      </header>
    </>
  );
}