import { Link, useLocation } from "wouter";
import { Library, Mic, Settings, Play, Pause, X } from "lucide-react";
import { useApp } from "@/lib/app-context";
import { formatDurationHHMMSS } from "@/lib/format";
import type { ReactNode } from "react";

export function AppShell({ children }: { children: ReactNode }) {
  const [location] = useLocation();
  const { player, togglePlay, closePlayer, snackbar, dismissSnackbar } = useApp();

  const tabs = [
    { href: "/", label: "Aufnehmen", icon: Mic, match: location === "/" },
    { href: "/bibliothek", label: "Bibliothek", icon: Library, match: location.startsWith("/bibliothek") || location.startsWith("/aufnahme") },
    { href: "/einstellungen", label: "Einstellungen", icon: Settings, match: location.startsWith("/einstellungen") },
  ];

  // Hide tab bar on detail page if we want fullscreen, but spec says player persistent across tab switch, so we keep tab bar always.
  const showMiniPlayer = player.recording && !location.startsWith("/aufnahme");

  return (
    <div className="h-full flex flex-col bg-background text-foreground">
      {/* Status bar safe area */}
      <div className="safe-top shrink-0" />

      {/* Brand strip — hardware faceplate header */}
      <div className="chassis border-b border-black px-4 py-1.5 flex items-center justify-between shrink-0">
        <div className="flex items-center gap-2">
          <LogoMark />
          <div className="flex flex-col leading-none">
            <span className="text-[13px] font-bold tracking-[0.05em] text-zinc-100">TAPECAST</span>
            <span className="text-[8px] font-mono tracking-[0.30em] text-zinc-500 uppercase mt-0.5">Pocket Studio · TC-1</span>
          </div>
        </div>
        <div className="flex items-center gap-1.5 px-2 py-1 rounded-sm panel-metal">
          <span className="led-pill on-green" />
          <span className="text-[9px] font-mono tracking-[0.18em] text-zinc-400 uppercase">PWR</span>
        </div>
      </div>

      {/* Page content */}
      <main className="flex-1 min-h-0 overflow-hidden">{children}</main>

      {/* Mini player */}
      {showMiniPlayer && player.recording && (
        <MiniPlayer
          title={player.recording.title}
          position={player.position}
          duration={player.recording.durationSec}
          playing={player.playing}
          onToggle={togglePlay}
          onClose={closePlayer}
        />
      )}

      {/* Snackbar */}
      {snackbar && (
        <div className={`fixed left-3 right-3 z-50 anim-snack ${showMiniPlayer ? "bottom-[136px]" : "bottom-[84px]"}`} style={{ marginBottom: "env(safe-area-inset-bottom)" }}>
          <div className="bg-foreground text-background rounded-full shadow-lg flex items-center gap-2 pl-4 pr-2 py-2" data-testid="snackbar">
            <span className="flex-1 text-sm font-medium truncate">{snackbar.message}</span>
            {snackbar.actionLabel && snackbar.onAction && (
              <button
                onClick={() => {
                  snackbar.onAction?.();
                  dismissSnackbar();
                }}
                className="text-sm font-semibold accent-red px-3 py-1.5 tap-target rounded-full"
                data-testid="button-snackbar-action"
              >
                {snackbar.actionLabel}
              </button>
            )}
            <button
              onClick={dismissSnackbar}
              className="w-8 h-8 flex items-center justify-center text-background/70"
              aria-label="Schließen"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Bottom tab bar — hardware mode-switch strip */}
      <nav className="shrink-0 chassis border-t border-black pb-safe">
        <ul className="flex px-2 py-2 gap-2">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            return (
              <li key={tab.href} className="flex-1">
                <Link
                  href={tab.href}
                  className={`hw-btn ${tab.match ? "active" : ""} flex flex-col items-center justify-center gap-0.5 py-2 tap-target`}
                  data-testid={`tab-${tab.href.replace("/", "") || "record"}`}
                >
                  <Icon className="w-[18px] h-[18px]" strokeWidth={tab.match ? 2.5 : 2} />
                  <span className="text-[9px] font-mono tracking-[0.16em] uppercase font-semibold">{tab.label}</span>
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>
    </div>
  );
}

function MiniPlayer({
  title,
  position,
  duration,
  playing,
  onToggle,
  onClose,
}: {
  title: string;
  position: number;
  duration: number;
  playing: boolean;
  onToggle: () => void;
  onClose: () => void;
}) {
  const progress = Math.min(1, position / Math.max(1, duration));
  return (
    <div className="relative chassis border-t border-black shrink-0" data-testid="mini-player">
      <div className="absolute left-0 top-0 h-0.5 bg-accent-red transition-all" style={{ width: `${progress * 100}%`, boxShadow: "0 0 6px rgba(255,59,48,0.7)" }} />
      <div className="flex items-center gap-2.5 px-3 py-2">
        <div className="w-10 h-10 rounded-md panel-metal flex items-center justify-center shrink-0">
          <Mic className="w-4 h-4 text-zinc-400" />
        </div>
        <div className="flex-1 min-w-0 px-2.5 py-1.5 rounded-sm lcd-screen">
          <p className="text-[11px] font-mono truncate" data-testid="text-mini-title">{title}</p>
          <p className="text-[10px] opacity-70 tabular-nums font-mono">
            {formatDurationHHMMSS(Math.floor(position))} / {formatDurationHHMMSS(duration)}
          </p>
        </div>
        <button
          onClick={onToggle}
          className="hw-btn orange w-10 h-10 flex items-center justify-center"
          aria-label={playing ? "Pausieren" : "Abspielen"}
          data-testid="button-mini-toggle"
        >
          {playing ? <Pause className="w-4 h-4" fill="currentColor" /> : <Play className="w-4 h-4 ml-0.5" fill="currentColor" />}
        </button>
        <button
          onClick={onClose}
          className="hw-btn w-10 h-10 flex items-center justify-center"
          aria-label="Schließen"
          data-testid="button-mini-close"
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}

function LogoMark() {
  return (
    <svg width="22" height="22" viewBox="0 0 32 32" aria-label="Tapecast Logo">
      <rect width="32" height="32" rx="8" fill="#FF3B30" />
      <circle cx="16" cy="16" r="6" fill="#0d0d0d" />
      <circle cx="16" cy="16" r="2" fill="#FF3B30" />
    </svg>
  );
}
