import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  Settings as SettingsIcon,
  Bot,
  FolderOpen,
  Info,
  Check,
  AlertTriangle,
  X,
  XCircle,
  Loader2,
  Wifi,
  WifiOff,
  KeyRound,
  Key,
  Command,
  RefreshCw,
  Keyboard,
  ChevronRight,
  Search,
  RotateCcw,
} from "lucide-react";
import {
  AgentConfigStatus,
} from "../../types/agentSettings";
import { WorkspacePreferences } from "../../types/terminal";
import { sanitizeAgentConfigStatus } from "../../lib/agentConfigStatus";
import { AgentSettingsForm } from "./AgentSettingsForm";
import { MappingsSettingsCard } from "./MappingsSettingsCard";
import { NewsFeedSettingsCard } from "./NewsFeedSettingsCard";
import { SecEdgarSettingsCard } from "./SecEdgarSettingsCard";
import { ToastContainer, type Toast, type ToastType } from "./Toast";

type SettingsSectionId = "general" | "ai" | "workspace" | "about";

interface SettingsPageProps {
  status: AgentConfigStatus | null;
  onRefreshStatus: () => Promise<AgentConfigStatus>;
  onStatusChange: (status: AgentConfigStatus) => void;
  onBackToTerminal: () => void;
  workspacePreferences: WorkspacePreferences;
  onWorkspacePreferencesChange: (patch: Partial<WorkspacePreferences>) => void;
}

interface SettingsSection {
  id: SettingsSectionId;
  label: string;
  description: string;
  icon: React.ReactNode;
}

const sections: SettingsSection[] = [
  {
    id: "general",
    label: "General",
    description: "Configuration hub and runtime overview",
    icon: <SettingsIcon className="h-5 w-5" />,
  },
  {
    id: "ai",
    label: "AI & Models",
    description: "Remote provider, model routing, and credentials",
    icon: <Bot className="h-5 w-5" />,
  },
  {
    id: "workspace",
    label: "Workspace",
    description: "Shell, tabs, and terminal behavior",
    icon: <FolderOpen className="h-5 w-5" />,
  },
  {
    id: "about",
    label: "About",
    description: "Product details and settings conventions",
    icon: <Info className="h-5 w-5" />,
  },
];

const statusBadgeClassName = (active: boolean) =>
  active
    ? "border-[var(--term-status-info-border)] bg-[var(--term-status-info)] text-[var(--term-status-info-strong)]"
    : "border-[var(--term-status-warning-border)] bg-[var(--term-status-warning)] text-warning";

export const SettingsPage: React.FC<SettingsPageProps> = ({
  status,
  onRefreshStatus,
  onStatusChange,
  onBackToTerminal,
  workspacePreferences,
  onWorkspacePreferencesChange,
}) => {
  const validatedStatus = useMemo(
    () => sanitizeAgentConfigStatus(status),
    [status],
  );

  const [activeSection, setActiveSection] =
    useState<SettingsSectionId>("general");
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [refreshError, setRefreshError] = useState<string | null>(null);
  const [toasts, setToasts] = useState<Toast[]>([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [showKeyboardShortcuts, setShowKeyboardShortcuts] = useState(false);

  // Add toast notification
  const addToast = useCallback(
    (type: ToastType, message: string, duration?: number) => {
      const id = Math.random().toString(36).substring(2, 9);
      const newToast: Toast = { id, type, message, duration };
      setToasts((prev) => [...prev, newToast]);
    },
    [],
  );

  // Dismiss toast
  const dismissToast = useCallback((id: string) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  }, []);

  // Filter sections based on search
  const filteredSections = useMemo(() => {
    if (!searchQuery.trim()) return sections;
    const query = searchQuery.toLowerCase();
    return sections.filter(
      (section) =>
        section.label.toLowerCase().includes(query) ||
        section.description.toLowerCase().includes(query),
    );
  }, [searchQuery]);

  const statusSummary = useMemo(
    () => [
      {
        label: "Settings health",
        value: validatedStatus.configured ? "Ready" : "Needs attention",
        icon: validatedStatus.configured ? (
          <Check className="h-4 w-4" />
        ) : (
          <AlertTriangle className="h-4 w-4" />
        ),
      },
      {
        label: "Remote provider",
        value: validatedStatus.providers.remote.enabled
          ? validatedStatus.providers.remote.configured
            ? "Ready"
            : "Needs setup"
          : "Disabled",
        icon: validatedStatus.providers.remote.enabled ? (
          <Wifi className="h-4 w-4" />
        ) : (
          <WifiOff className="h-4 w-4" />
        ),
      },
      {
        label: "Local provider",
        value: validatedStatus.providers.ollama.enabled
          ? validatedStatus.providers.ollama.configured
            ? "Ready"
            : "Needs setup"
          : "Disabled",
        icon: validatedStatus.providers.ollama.enabled ? (
          <Wifi className="h-4 w-4" />
        ) : (
          <WifiOff className="h-4 w-4" />
        ),
      },
      {
        label: "API key",
        value: validatedStatus.providers.remote.hasApiKey
          ? "Stored"
          : "Missing",
        icon: validatedStatus.providers.remote.hasApiKey ? (
          <KeyRound className="h-4 w-4" />
        ) : (
          <Key className="h-4 w-4" />
        ),
      },
    ],
    [validatedStatus],
  );

  const handleRefresh = async () => {
    setIsRefreshing(true);
    setRefreshError(null);

    try {
      const nextStatus = await onRefreshStatus();
      onStatusChange(nextStatus);
      addToast("success", "Settings status refreshed");
    } catch (error) {
      const errorMessage =
        error instanceof Error
          ? error.message
          : "Failed to refresh settings status";
      setRefreshError(errorMessage);
      addToast("error", errorMessage);
    } finally {
      setIsRefreshing(false);
    }
  };

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      const activeElement = document.activeElement as HTMLElement | null;
      const isEditingField =
        activeElement?.tagName === "INPUT" ||
        activeElement?.tagName === "TEXTAREA" ||
        activeElement?.isContentEditable === true;

      // Cmd/Ctrl + S to save (prevent default)
      if ((e.metaKey || e.ctrlKey) && e.key === "s") {
        e.preventDefault();
        // Trigger save in the active form
        const saveButton = document.querySelector(
          '[aria-describedby="save-hint"]',
        ) as HTMLButtonElement;
        if (saveButton && !saveButton.disabled) {
          saveButton.click();
        }
      }

      // Cmd/Ctrl + K to focus search
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        document.getElementById("settings-search")?.focus();
      }

      if (isEditingField) {
        return;
      }

      // ? to show shortcuts
      if (e.key === "?" && !e.shiftKey && !e.metaKey && !e.ctrlKey) {
        setShowKeyboardShortcuts((prev) => !prev);
      }

      // Escape to close shortcuts modal
      if (e.key === "Escape") {
        setShowKeyboardShortcuts(false);
      }

      // Number keys to navigate sections
      if (["1", "2", "3", "4"].includes(e.key)) {
        const sectionIndex = parseInt(e.key) - 1;
        if (filteredSections[sectionIndex]) {
          setActiveSection(
            filteredSections[sectionIndex].id as SettingsSectionId,
          );
        }
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [filteredSections]);

  const renderContent = () => {
    if (activeSection === "general") {
      return (
        <div className="space-y-8">
          <section>
            <h2 className="mb-3 text-sm font-mono font-semibold text-term-text">
              Settings are centralized here
            </h2>
            <p className="max-w-2xl text-sm font-mono leading-7 text-term-text-muted">
              This page is the dedicated control surface for MosaicIQ
              configuration. New settings categories should be added as submenu
              entries here instead of modal dialogs or one-off controls
              elsewhere in the shell.
            </p>
          </section>

          <section>
            <div className="mb-4 flex items-center gap-3 border-b border-term-border-subtle pb-3">
              <div className="h-px flex-1 bg-term-border-subtle" />
              <span className="text-xs font-mono uppercase tracking-wider text-term-text-tertiary">
                Status Overview
              </span>
              <div className="h-px flex-1 bg-term-border-subtle" />
            </div>
            <div className="grid gap-6 sm:grid-cols-3">
              {statusSummary.map((item) => (
                <div key={item.label} className="space-y-1">
                  <div className="flex items-center gap-2 text-term-text-tertiary">
                    <span className="text-sm">{item.icon}</span>
                    <span className="text-xs font-mono uppercase tracking-wide">
                      {item.label}
                    </span>
                  </div>
                  <div className="text-sm font-mono text-term-text">
                    {item.value}
                  </div>
                </div>
              ))}
            </div>
          </section>

          <section>
            <h2 className="mb-4 text-sm font-mono font-semibold text-term-text">
              Settings roadmap
            </h2>
            <div className="space-y-4">
              <div className="flex gap-4 border-l-2 border-term-border-subtle p-4 transition-colors hover:border-info">
                <span className="mt-0.5 text-term-text-tertiary">
                  <Bot className="h-5 w-5" />
                </span>
                <div className="flex-1">
                  <h3 className="mb-1 text-sm font-mono text-term-text">
                    AI & Models
                  </h3>
                  <p className="text-sm font-mono leading-6 text-term-text-muted">
                    Active now. Provider routing, default models, and credential
                    storage are managed in this section.
                  </p>
                </div>
              </div>
              <div className="flex gap-4 border-l-2 border-term-border-subtle p-4 transition-colors hover:border-info">
                <span className="mt-0.5 text-term-text-tertiary">
                  <FolderOpen className="h-5 w-5" />
                </span>
                <div className="flex-1">
                  <h3 className="mb-1 text-sm font-mono text-term-text">
                    Workspace
                  </h3>
                  <p className="text-sm font-mono leading-6 text-term-text-muted">
                    Reserved for terminal defaults, tab naming conventions, and
                    shell preferences as those controls are added.
                  </p>
                </div>
              </div>
            </div>
          </section>

          <SecEdgarSettingsCard
            status={validatedStatus}
            onStatusChange={onStatusChange}
          />
          <NewsFeedSettingsCard />
          <MappingsSettingsCard />
        </div>
      );
    }

    if (activeSection === "ai") {
      return (
        <AgentSettingsForm status={validatedStatus} onStatusChange={onStatusChange} />
      );
    }

    if (activeSection === "workspace") {
      return (
        <section>
          <h2 className="mb-3 text-sm font-mono font-semibold text-term-text">
            Workspace settings
          </h2>
          <p className="mb-6 max-w-2xl text-sm font-mono leading-7 text-term-text-muted">
            This submenu is in place for shell-wide controls such as sidebar
            defaults, startup behavior, and terminal preferences. Future
            workspace configuration should be added here rather than inside the
            terminal view.
          </p>

          <div className="space-y-4">
            <div className="border border-term-border rounded-lg p-4">
              <h3 className="mb-3 text-sm font-mono font-semibold text-term-text">
                Chat history restore
              </h3>
              <p className="mb-4 text-sm font-mono text-term-text-muted">
                Choose where saved chat transcripts are restored when clicked from the sidebar.
              </p>
              <div className="space-y-3">
                <label className="flex items-start gap-3 cursor-pointer group">
                  <input
                    type="radio"
                    name="chatHistoryRestoreTarget"
                    value="activeTab"
                    checked={workspacePreferences.chatHistoryRestoreTarget === 'activeTab'}
                    onChange={() => onWorkspacePreferencesChange({ chatHistoryRestoreTarget: 'activeTab' })}
                    className="mt-1 accent-info"
                  />
                  <div>
                    <span className="text-sm font-mono text-term-text group-hover:text-info transition-colors">
                      Active tab
                    </span>
                    <p className="text-xs font-mono text-term-text-muted mt-0.5">
                      Replace the active terminal with the saved transcript.
                    </p>
                  </div>
                </label>
                <label className="flex items-start gap-3 cursor-pointer group">
                  <input
                    type="radio"
                    name="chatHistoryRestoreTarget"
                    value="newTab"
                    checked={workspacePreferences.chatHistoryRestoreTarget === 'newTab'}
                    onChange={() => onWorkspacePreferencesChange({ chatHistoryRestoreTarget: 'newTab' })}
                    className="mt-1 accent-info"
                  />
                  <div>
                    <span className="text-sm font-mono text-term-text group-hover:text-info transition-colors">
                      New tab
                    </span>
                    <p className="text-xs font-mono text-term-text-muted mt-0.5">
                      Open the saved transcript in a new terminal tab.
                    </p>
                  </div>
                </label>
              </div>
            </div>
          </div>
        </section>
      );
    }

    return (
      <section>
        <h2 className="mb-3 text-sm font-mono font-semibold text-term-text">
          About this settings page
        </h2>
        <div className="space-y-4 text-sm font-mono leading-7 text-term-text-muted">
          <p>
            The settings page is designed as a durable home for configuration
            instead of scattering controls across the product shell.
          </p>
          <p>
            Each submenu is a stable category. Future settings work should add
            to these categories or introduce a new submenu here when the
            information architecture truly expands.
          </p>
          <p>
            Current shell shortcut: use the bottom-left cog or press{" "}
            <kbd className="mx-1 rounded bg-term-highlight px-1.5 py-0.5 text-xs text-term-text">
              <Command className="inline h-3 w-3" /> + ,
            </kbd>{" "}
            to open settings.
          </p>
        </div>

        {/* Keyboard shortcuts help */}
        <div className="mt-6 border-t border-term-border-subtle pt-6">
          <div className="mb-4 flex items-center justify-between">
            <h3 className="text-sm font-mono font-semibold text-term-text">
              Keyboard shortcuts
            </h3>
            <button
              type="button"
              onClick={() => setShowKeyboardShortcuts(true)}
              className="rounded border border-term-border px-3 py-1.5 text-xs font-mono text-term-text-muted transition-colors hover:border-info hover:text-info"
            >
              View all
            </button>
          </div>
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="flex items-center justify-between text-xs font-mono">
              <span className="text-term-text-muted">Save settings</span>
              <kbd className="flex items-center gap-1 rounded bg-term-highlight px-2 py-0.5 text-term-text">
                <Command className="h-3 w-3" />S
              </kbd>
            </div>
            <div className="flex items-center justify-between text-xs font-mono">
              <span className="text-term-text-muted">Search settings</span>
              <kbd className="flex items-center gap-1 rounded bg-term-highlight px-2 py-0.5 text-term-text">
                <Command className="h-3 w-3" />K
              </kbd>
            </div>
            <div className="flex items-center justify-between text-xs font-mono">
              <span className="text-term-text-muted">Show shortcuts</span>
              <kbd className="rounded bg-term-highlight px-2 py-0.5 text-term-text">
                ?
              </kbd>
            </div>
            <div className="flex items-center justify-between text-xs font-mono">
              <span className="text-term-text-muted">Navigate sections</span>
              <kbd className="rounded bg-term-highlight px-2 py-0.5 text-term-text">
                1-4
              </kbd>
            </div>
          </div>
        </div>
      </section>
    );
  };

  const currentSectionLabel = sections.find(
    (section) => section.id === activeSection,
  )?.label;

  return (
    <div className="flex h-screen w-screen flex-col bg-term-bg">
      {/* Header */}
      <header className="flex items-center justify-between border-b border-term-border-subtle px-6 py-4">
        <div>
          <h1 className="text-lg font-mono font-semibold text-term-text">
            Settings
          </h1>
          <p className="mt-1 text-xs font-mono text-term-text-muted">
            Centralized configuration for MosaicIQ
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => setShowKeyboardShortcuts(true)}
            className="rounded border border-term-border bg-term-surface p-2 text-term-text-muted transition-colors hover:border-info hover:text-info"
            aria-label="View keyboard shortcuts"
          >
            <Keyboard className="h-4 w-4" />
          </button>
          <button
            type="button"
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="flex items-center gap-2 rounded border border-term-border bg-term-surface px-3 py-2 text-xs font-mono text-term-text transition-colors hover:border-info hover:text-info disabled:cursor-not-allowed disabled:opacity-50"
          >
            {isRefreshing ? (
              <>
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
                Refreshing...
              </>
            ) : (
              <>
                <RefreshCw className="h-3.5 w-3.5" />
                Refresh status
              </>
            )}
          </button>
          <button
            type="button"
            onClick={onBackToTerminal}
            className="rounded border border-term-border bg-term-surface px-3 py-2 text-xs font-mono text-term-text transition-colors hover:border-info hover:text-info"
          >
            Back to terminal
          </button>
        </div>
      </header>

      {/* Main content */}
      <div className="flex min-h-0 flex-1 flex-col lg:flex-row">
        {/* Sidebar */}
        <aside className="border-b border-term-border-subtle bg-term-elevated lg:w-[280px] lg:border-b-0 lg:border-r">
          {/* Search */}
          <div className="border-b border-term-border-subtle px-4 py-3">
            <div className="relative group">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-term-text-tertiary transition-colors group-focus-within:text-info" />
              <input
                id="settings-search"
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search settings... (⌘K)"
                className="w-full border-l-2 border-term-border-subtle bg-transparent px-3 py-2 pl-9 text-sm font-mono text-term-text outline-none transition-all focus:border-l-info focus:bg-term-bg"
              />
            </div>
            {searchQuery && filteredSections.length === 0 && (
              <div className="mt-3 flex items-center gap-2 px-1">
                <div className="h-px flex-1 bg-term-border" />
                <span className="text-xs font-mono text-term-text-tertiary">
                  No results
                </span>
                <div className="h-px flex-1 bg-term-border" />
              </div>
            )}
          </div>

          {/* Navigation */}
          <nav
            className="flex gap-1 overflow-x-auto px-4 py-3 lg:flex-col lg:gap-0.5 lg:overflow-visible"
            role="navigation"
            aria-label="Settings sections"
          >
            {filteredSections.map((section, index) => {
              const isActive = activeSection === section.id;
              return (
                <button
                  key={section.id}
                  type="button"
                    onClick={() => setActiveSection(section.id)}
                    className={`min-w-[180px] flex items-center gap-3 px-3 py-2.5 text-left transition-all lg:min-w-0 ${
                      isActive
                      ? "bg-term-highlight text-term-text"
                      : "text-term-text-muted hover:bg-term-surface hover:text-term-text"
                    }`}
                  aria-current={isActive ? "page" : undefined}
                >
                  <span
                    className={`transition-colors ${isActive ? "text-term-text" : "text-term-text-tertiary"}`}
                  >
                    {section.icon}
                  </span>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <span className="text-xs font-mono truncate">
                        {section.label}
                      </span>
                      <kbd className="text-[10px] font-mono text-term-text-tertiary/70">
                        {index + 1}
                      </kbd>
                    </div>
                    <div className="mt-0.5 text-[11px] font-mono leading-tight truncate opacity-70">
                      {section.description}
                    </div>
                  </div>
                </button>
              );
            })}
          </nav>
        </aside>

        {/* Content area */}
        <main
          className="min-h-0 flex-1 overflow-y-auto px-4 py-4 lg:px-8 lg:py-6"
          id="main-content"
        >
          {/* Breadcrumbs */}
          <nav
            className="mb-6 flex items-center gap-2 text-xs font-mono"
            aria-label="Breadcrumb"
          >
            <span className="text-term-text-muted">Settings</span>
            <ChevronRight
              className="h-4 w-4 text-term-text-tertiary"
              aria-hidden="true"
            />
            <span className="text-term-text">{currentSectionLabel}</span>
          </nav>

          {/* Status badges */}
          <div className="mb-6 flex flex-wrap items-center gap-4">
            <div
              className={`flex items-center gap-2 px-3 py-1.5 text-[11px] font-mono border-l-2 ${statusBadgeClassName(
                Boolean(validatedStatus.configured),
              )}`}
            >
              {validatedStatus.configured ? (
                <>
                  <Check className="h-3.5 w-3.5" />
                  Configured
                </>
              ) : (
                <>
                  <AlertTriangle className="h-3.5 w-3.5" />
                  Needs configuration
                </>
              )}
            </div>
            <div className="flex items-center gap-2 border-l-2 border-term-border px-3 py-1.5 text-[11px] font-mono text-term-text-muted">
              <span className="h-1.5 w-1.5 rounded-full bg-term-text-tertiary" />
              <span>Active section: {currentSectionLabel}</span>
            </div>
          </div>

          {/* Refresh error */}
          {refreshError ? (
            <div
              className="mb-6 border-l-2 border-[var(--term-status-error-border)] bg-[color:rgb(var(--term-status-error-rgb)/0.3)] p-4 text-sm font-mono text-negative"
              role="alert"
            >
              <div className="flex items-start gap-3">
                <XCircle className="h-5 w-5 mt-0.5" aria-hidden="true" />
                <div className="flex-1">{refreshError}</div>
                <button
                  type="button"
                  onClick={() => setRefreshError(null)}
                  className="text-negative opacity-60 transition-opacity hover:opacity-100"
                  aria-label="Dismiss error"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            </div>
          ) : null}

          {/* Content */}
          {renderContent()}
        </main>
      </div>

      {/* Toast container */}
      <ToastContainer toasts={toasts} onDismiss={dismissToast} />

      {/* Keyboard shortcuts modal */}
      {showKeyboardShortcuts && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
          onClick={() => setShowKeyboardShortcuts(false)}
          role="dialog"
          aria-modal="true"
          aria-labelledby="shortcuts-title"
        >
          <div
            className="w-full max-w-md rounded-lg border border-term-border bg-term-surface p-6 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="mb-5 flex items-center justify-between">
              <h2
                id="shortcuts-title"
                className="text-base font-mono font-semibold text-term-text"
              >
                Keyboard Shortcuts
              </h2>
              <button
                type="button"
                onClick={() => setShowKeyboardShortcuts(false)}
                className="text-term-text-muted transition-colors hover:text-term-text"
                aria-label="Close keyboard shortcuts"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <div className="space-y-3">
              <div className="flex items-center justify-between border-b border-term-border-subtle pb-3">
                <span className="text-sm font-mono text-term-text">
                  Save settings
                </span>
                <kbd className="flex items-center gap-1 rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                  <Command className="h-3 w-3" /> /{" "}
                  <RotateCcw className="h-3 w-3" /> + S
                </kbd>
              </div>
              <div className="flex items-center justify-between border-b border-term-border-subtle pb-3">
                <span className="text-sm font-mono text-term-text">
                  Search settings
                </span>
                <kbd className="flex items-center gap-1 rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                  <Command className="h-3 w-3" /> /{" "}
                  <RotateCcw className="h-3 w-3" /> + K
                </kbd>
              </div>
              <div className="flex items-center justify-between border-b border-term-border-subtle pb-3">
                <span className="text-sm font-mono text-term-text">
                  Toggle shortcuts help
                </span>
                <kbd className="rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                  ?
                </kbd>
              </div>
              <div className="flex items-center justify-between border-b border-term-border-subtle pb-3">
                <span className="text-sm font-mono text-term-text">
                  Navigate to section
                </span>
                <div className="flex gap-1">
                  <kbd className="rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                    1
                  </kbd>
                  <kbd className="rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                    2
                  </kbd>
                  <kbd className="rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                    3
                  </kbd>
                  <kbd className="rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                    4
                  </kbd>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm font-mono text-term-text">
                  Close modal
                </span>
                <kbd className="rounded border border-term-border bg-term-elevated px-2 py-1 text-xs text-term-text">
                  Esc
                </kbd>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Skip link for accessibility */}
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:absolute focus:left-4 focus:top-4 focus:z-50 focus:rounded focus:border-info focus:bg-term-surface focus:px-3 focus:py-2 focus:text-sm focus:font-mono focus:text-info"
      >
        Skip to main content
      </a>
    </div>
  );
};
