import { useState } from "react";
import { FolderGit2, PanelLeft, PanelRight, Bell, Settings, ChevronDown, CloudDownload, Download } from "lucide-react";
import { COLORS, FONT } from "./theme";
import type { WorkspaceView } from "./layoutTypes";
import { leafIds } from "./layoutTypes";
import { openExternal } from "./socketBridge";
import type { UpdateInfo } from "./socketBridge";

/** Human-readable descriptor of the active workspace layout (mock until a real preset id is tracked). */
function describeLayout(w: WorkspaceView | null): string {
  if (!w || !w.layout) return "no layout";
  const n = leafIds(w.layout).length;
  return n === 1 ? "1 pane" : `${n} panes`;
}

function IconBtn({ icon, onClick, active, title }: { icon: React.ReactNode; onClick?: () => void; active?: boolean; title?: string }) {
  return (
    <button
      title={title}
      onClick={onClick}
      style={{
        display: "flex", alignItems: "center", justifyContent: "center",
        width: 26, height: 26, borderRadius: 6,
        background: active ? COLORS.bgElevated : "transparent",
        border: active ? `1px solid ${COLORS.borderSubtle}` : "1px solid transparent",
        color: active ? COLORS.textPrimary : COLORS.textSecondary,
      }}
    >
      {icon}
    </button>
  );
}

/** Update-check button (lights up when the server has a newer version) plus its popover. */
function UpdateControl({ update, checking, onCheck }: { update: UpdateInfo | null; checking: boolean; onCheck: () => void }) {
  const [open, setOpen] = useState(false);
  const hasUpdate = !!update?.has_update;

  return (
    <div style={{ position: "relative", display: "flex" }}>
      <button
        title={hasUpdate ? `Доступна версия ${update?.latest}` : "Проверить обновления"}
        onClick={() => setOpen((v) => !v)}
        style={{
          display: "flex", alignItems: "center", justifyContent: "center",
          width: 26, height: 26, borderRadius: 6,
          background: hasUpdate ? "rgba(52,211,194,0.15)" : open ? COLORS.bgElevated : "transparent",
          border: `1px solid ${hasUpdate ? COLORS.accent : open ? COLORS.borderSubtle : "transparent"}`,
          color: hasUpdate ? COLORS.accent : COLORS.textSecondary,
          boxShadow: hasUpdate ? `0 0 10px rgba(52,211,194,0.5)` : "none",
          animation: hasUpdate ? "spaceshPulse 2s ease-in-out infinite" : "none",
        }}
      >
        <CloudDownload size={15} style={{ animation: checking ? "spaceshBlink 1s ease-in-out infinite" : "none" }} />
      </button>

      {open && (
        <>
          {/* click-away backdrop */}
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 200 }} />
          <div style={{
            position: "absolute", top: 32, right: 0, zIndex: 201, width: 240,
            background: COLORS.bgPanel, border: `1px solid ${COLORS.borderSubtle}`, borderRadius: 8,
            padding: 12, boxShadow: "0 8px 24px rgba(0,0,0,0.4)",
            fontFamily: FONT.ui, color: COLORS.textPrimary,
          }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>Обновление</div>
            <div style={{ fontSize: 12, color: COLORS.textSecondary, display: "flex", justifyContent: "space-between" }}>
              <span>Установлено</span><span style={{ fontFamily: FONT.mono }}>{update?.current ?? "—"}</span>
            </div>
            <div style={{ fontSize: 12, color: COLORS.textSecondary, display: "flex", justifyContent: "space-between", marginTop: 2 }}>
              <span>На сервере</span><span style={{ fontFamily: FONT.mono }}>{update?.latest || "—"}</span>
            </div>

            {hasUpdate ? (
              <button
                onClick={() => { void openExternal(update!.url); setOpen(false); }}
                style={{
                  marginTop: 10, width: "100%", height: 30, borderRadius: 6, border: "none", cursor: "pointer",
                  background: COLORS.accent, color: COLORS.bgApp, fontFamily: FONT.ui, fontSize: 13, fontWeight: 600,
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
                }}
              >
                <Download size={14} /> Скачать {update?.latest}
              </button>
            ) : update?.latest ? (
              <div style={{ marginTop: 10, fontSize: 12, color: COLORS.stDone }}>Установлена последняя версия</div>
            ) : (
              <div style={{ marginTop: 10, fontSize: 12, color: COLORS.textMuted }}>Не удалось проверить сервер</div>
            )}

            <button
              onClick={onCheck}
              disabled={checking}
              style={{
                marginTop: 8, width: "100%", height: 28, borderRadius: 6, cursor: checking ? "default" : "pointer",
                background: "transparent", border: `1px solid ${COLORS.borderStrong}`, color: COLORS.textSecondary,
                fontFamily: FONT.ui, fontSize: 12,
              }}
            >
              {checking ? "Проверяю…" : "Проверить снова"}
            </button>
          </div>
        </>
      )}
    </div>
  );
}

export function TopBar({
  active, eventsOpen, onToggleEvents, onShowEvents, sidebarOpen, onToggleSidebar, unread, onOpenSettings,
  update, updateChecking, onCheckUpdate,
}: {
  active: WorkspaceView | null;
  eventsOpen: boolean;
  onToggleEvents: () => void;
  onShowEvents: () => void;
  sidebarOpen: boolean;
  onToggleSidebar: () => void;
  unread: number;
  onOpenSettings: () => void;
  update: UpdateInfo | null;
  updateChecking: boolean;
  onCheckUpdate: () => void;
}) {
  return (
    <div
      // Native titlebar is a transparent Overlay (see tauri.conf.json), so the
      // theme fill flows up to the very top and this bar IS the titlebar. Make it
      // the OS drag region; child buttons keep their own clicks (Tauri only starts
      // a drag on mousedown landing on the drag-region element itself).
      data-tauri-drag-region
      style={{
        display: "flex", alignItems: "center", height: 40, flex: "0 0 40px",
        // Left pad clears the macOS traffic lights overlaid in this strip.
        padding: "0 14px 0 78px", gap: 12, background: COLORS.elevatedGlass,
        backdropFilter: COLORS.panelBlur, WebkitBackdropFilter: COLORS.panelBlur,
        borderBottom: `1px solid ${COLORS.borderSubtle}`,
        // The glass panels below use backdrop-filter, which creates stacking
        // contexts that otherwise paint over this bar's popovers (update/bell).
        // Lift the whole bar into its own context above the panel grid.
        position: "relative", zIndex: 30,
      }}
    >
      {/* Left: sidebar toggle, flush to the left edge. */}
      <IconBtn icon={<PanelLeft size={15} />} onClick={onToggleSidebar} active={sidebarOpen} title="Toggle Sidebar" />

      {/* Workspace breadcrumb */}
      <div data-tauri-drag-region style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
        <FolderGit2 size={15} color={COLORS.textSecondary} />
        <span style={{ fontFamily: FONT.ui, fontSize: 13, fontWeight: 600, color: COLORS.textPrimary, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {active?.name ?? "spaceshell"}
        </span>
        {active && (
          <>
            <span style={{ fontFamily: FONT.ui, fontSize: 13, color: COLORS.textMuted }}>/</span>
            <span style={{ fontFamily: FONT.ui, fontSize: 13, color: COLORS.textSecondary, whiteSpace: "nowrap" }}>
              {describeLayout(active)}
            </span>
          </>
        )}
      </div>

      <div data-tauri-drag-region style={{ flex: 1, alignSelf: "stretch" }} />

      <style>{`
        @keyframes spaceshBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
        @keyframes spaceshPulse { 0%,100% { box-shadow: 0 0 6px rgba(52,211,194,0.35); } 50% { box-shadow: 0 0 14px rgba(52,211,194,0.7); } }
      `}</style>

      {/* Right cluster */}
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        <UpdateControl update={update} checking={updateChecking} onCheck={onCheckUpdate} />
        <div style={{ position: "relative", display: "flex" }}>
          <IconBtn icon={<Bell size={16} />} onClick={onShowEvents} active={eventsOpen} title="Open activity log" />
          {unread > 0 && (
            <span style={{
              position: "absolute", top: -2, right: -2, minWidth: 14, height: 14, padding: "0 3px",
              borderRadius: 7, background: COLORS.stError, color: "#fff",
              fontFamily: FONT.ui, fontSize: 9, fontWeight: 700,
              display: "flex", alignItems: "center", justifyContent: "center", boxSizing: "border-box",
              pointerEvents: "none", // let clicks/hover pass through to the bell button beneath
            }}>
              {unread > 99 ? "99+" : unread}
            </span>
          )}
        </div>
        <IconBtn icon={<PanelRight size={15} />} onClick={onToggleEvents} active={eventsOpen} title="Toggle Event Center" />
        <IconBtn icon={<Settings size={16} />} onClick={onOpenSettings} title="Settings" />
        <span style={{ width: 1, height: 18, background: COLORS.borderStrong, margin: "0 2px" }} />
        <button
          title="Account (mock)"
          style={{
            display: "flex", alignItems: "center", gap: 6, height: 26, padding: "0 4px 0 4px",
            background: "transparent", border: "1px solid transparent", borderRadius: 6, color: COLORS.textSecondary,
          }}
        >
          <span style={{ width: 20, height: 20, borderRadius: "50%", background: COLORS.accent, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: FONT.ui, fontSize: 11, fontWeight: 700, color: "#fff" }}>
            V
          </span>
          <ChevronDown size={13} />
        </button>
      </div>
    </div>
  );
}
