import type { LinksFunction } from "@remix-run/node";
import {
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
  useLocation,
} from "@remix-run/react";
import baseStyles from "./styles/base.css?url";
import themeStyles from "@dangerousthings/web/dist/index.css?url";
import { PowerWidget } from "./components/PowerWidget";
import { HeaderWidgets } from "./components/HeaderWidgets";
import { LoginPrompt } from "./components/LoginPrompt";
import { useWebSocketState } from "./hooks/useWebSocket";
import { ThemeProvider, useTheme } from "./lib/ThemeContext";
import type { ThemeMode } from "./lib/ThemeContext";

export const links: LinksFunction = () => [
  { rel: "stylesheet", href: baseStyles },
  { rel: "stylesheet", href: themeStyles },
  { rel: "preload", href: "/fonts/Tektur-VariableFont_wdth,wght.ttf", as: "font", type: "font/ttf", crossOrigin: "anonymous" },
];

/**
 * FOUC prevention: static inline script reads localStorage and sets
 * data-brand/data-theme before first paint. This is a hardcoded string
 * constant (no user input), so it is safe from XSS.
 */
const FOUC_PREVENTION_SCRIPT = `(function(){try{var b=localStorage.getItem('dpi_theme_brand')||'dt';var m=localStorage.getItem('theme')||'dark';document.documentElement.setAttribute('data-brand',b);document.documentElement.setAttribute('data-theme',m);}catch(e){}})();`;

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" data-brand="dt" data-theme="dark">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
        <meta name="theme-color" content="#000000" />
        <meta name="description" content="Dangerous Pi - Proxmark3 Management Interface" />
        <Meta />
        <Links />
        {/* Prevent FOUC: hardcoded constant string, no user input — safe from XSS */}
        <script dangerouslySetInnerHTML={{ __html: FOUC_PREVENTION_SCRIPT }} />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

export default function App() {
  return (
    <ThemeProvider>
      <AppInner />
    </ThemeProvider>
  );
}

function AppInner() {
  const location = useLocation();
  const wsState = useWebSocketState();
  const { mode, setMode } = useTheme();

  const toggleMode = () => {
    const modes: ThemeMode[] = ["dark", "auto", "light"];
    const currentIndex = modes.indexOf(mode);
    setMode(modes[(currentIndex + 1) % modes.length]);
  };

  const navLinks = [
    { to: "/", label: "Dashboard", icon: "\u25C8" },
    { to: "/commands", label: "Commands", icon: "\u25B6" },
    { to: "/settings", label: "Settings", icon: "\u2699" },
    { to: "/updates", label: "Updates", icon: "\uD83D\uDD04" },
    { to: "/logs", label: "Logs", icon: "\u2261" },
  ];

  return (
    <>
      <header className="header">
        <div className="header-content">
          <a href="/" className="logo">
            <div className="logo-icon"></div>
            <span>Dangerous Pi</span>
          </a>

          <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
            <PowerWidget />
            <button
              onClick={toggleMode}
              className="btn-secondary"
              style={{ minWidth: "44px", padding: "0.5rem" }}
              aria-label="Toggle theme mode"
              title={`Current mode: ${mode}`}
            >
              {mode === "dark" ? "\u25D0" : mode === "light" ? "\u25CB" : "\u25D1"}
            </button>
          </div>
        </div>
      </header>

      {/* Header Widgets - Notifications from system and plugins */}
      <HeaderWidgets />

      {/* Desktop Navigation - Hidden on mobile */}
      <nav className="nav" style={{ display: "none" }}>
        {navLinks.map((link) => (
          <a
            key={link.to}
            href={link.to}
            className={`nav-link ${location.pathname === link.to ? "active" : ""}`}
          >
            <span style={{ fontSize: "1.25rem" }}>{link.icon}</span>
            <span>{link.label}</span>
          </a>
        ))}
      </nav>

      <main className="main">
        <Outlet />
      </main>

      {/* Mobile Bottom Navigation */}
      <nav className="nav">
        {navLinks.map((link) => (
          <a
            key={link.to}
            href={link.to}
            className={`nav-link ${location.pathname === link.to ? "active" : ""}`}
          >
            <span style={{ fontSize: "1.5rem" }}>{link.icon}</span>
            <span>{link.label}</span>
          </a>
        ))}
      </nav>

      <style>{`
        @media (min-width: 768px) {
          .nav:first-of-type {
            display: flex !important;
            position: static;
            border: none;
            background: transparent;
            padding: 1rem 0;
            max-width: 1280px;
            margin: 0 auto;
            justify-content: center;
          }

          .nav:last-of-type {
            display: none;
          }

          body {
            padding-bottom: 0;
          }
        }
      `}</style>

      {wsState === "auth_required" && <LoginPrompt />}
    </>
  );
}
