// ABOUTME: Compact titlebar with workspace switcher, balance, and window actions.
// ABOUTME: Project folder lives in the sidebar header, not duplicated here.

import { type Component, Show } from "solid-js";
import { BalanceDisplay } from "@/components/common/BalanceDisplay";
import { WorkspaceBar } from "@/components/layout/WorkspaceBar";
import { RecordPrompt } from "@/components/meeting/RecordPrompt";
import { authStore } from "@/stores/auth.store";
import { updaterStore } from "@/stores/updater.store";

interface TitlebarProps {
  onSignInClick: () => void;
  onToggleMeetings: () => void;
  onToggleSkills: () => void;
  onToggleSettings: () => void;
  /** A meeting capture is live; show the recording indicator on the button. */
  meetingRecording?: boolean;
  recordPromptVisible?: boolean;
  recordPromptSourceApp?: string | null;
  onRecordConversation?: () => void;
  onDismissRecordPrompt?: () => void;
}

const DOWNLOAD_QUIPS = [
  "Warming up...",
  "Downloading fresh pixels...",
  "Fetching improvements...",
  "Installing awesomeness...",
  "Polishing bits...",
  "Almost there...",
  "Finalizing magic...",
  "99% done...",
];

function quipForPercent(percent: number): string {
  const index = Math.floor((percent / 100) * (DOWNLOAD_QUIPS.length - 1));
  return DOWNLOAD_QUIPS[Math.min(index, DOWNLOAD_QUIPS.length - 1)];
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / k ** i).toFixed(1)} ${sizes[i]}`;
}

function MeetingsIcon() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      stroke-width="1.4"
      stroke-linecap="round"
      stroke-linejoin="round"
      role="img"
      aria-label="Meetings"
    >
      <path d="M8 9.8a2.25 2.25 0 0 0 2.25-2.25V4.25a2.25 2.25 0 0 0-4.5 0v3.3A2.25 2.25 0 0 0 8 9.8Z" />
      <path d="M3.8 7.25a4.2 4.2 0 0 0 8.4 0M8 11.45V14M6.25 14h3.5" />
    </svg>
  );
}

export const Titlebar: Component<TitlebarProps> = (props) => {
  return (
    <div
      class="relative flex items-center justify-between h-[var(--titlebar-height,40px)] px-3 bg-surface-1 border-b border-border shrink-0 select-none"
      style={{ "-webkit-app-region": "drag" }}
    >
      {/* Left: workspace switcher. */}
      <div
        class="flex items-center shrink-0"
        style={{ "-webkit-app-region": "no-drag" }}
      >
        <WorkspaceBar />
      </div>

      {/* Right: balance + window actions. Project folder lives in
          the sidebar header; no need to duplicate it here. */}
      <div
        class="flex items-center gap-2 shrink-0"
        style={{ "-webkit-app-region": "no-drag" }}
      >
        {/* Update available button */}
        <Show when={updaterStore.state.status === "available"}>
          <button
            type="button"
            class="px-3 py-1 rounded-md bg-success/70 hover:bg-success/85 text-white text-xs font-medium flex items-center gap-1.5 transition-colors animate-pulse"
            onClick={() => updaterStore.installAvailableUpdate()}
            title={`Update to ${updaterStore.state.availableVersion}`}
          >
            <span>⬆</span>
            <span>Update {updaterStore.state.availableVersion}</span>
          </button>
        </Show>

        {/* Downloading progress */}
        <Show when={updaterStore.state.status === "downloading"}>
          <div class="flex flex-col gap-0.5 min-w-[140px]">
            <div class="flex justify-between text-[10px] text-foreground/70">
              <span>{quipForPercent(updaterStore.state.progressPercent)}</span>
              <span>{updaterStore.state.progressPercent}%</span>
            </div>
            <div
              class="w-full h-[4px] bg-white/10 rounded-full overflow-hidden"
              title={`${formatBytes(updaterStore.state.downloadedBytes)} / ${formatBytes(updaterStore.state.totalBytes)}`}
            >
              <div
                class="updater-bar-downloading h-full rounded-full transition-all duration-300"
                style={{
                  width: `${updaterStore.state.progressPercent}%`,
                }}
              />
            </div>
          </div>
        </Show>

        {/* Installing state */}
        <Show when={updaterStore.state.status === "installing"}>
          <div class="flex flex-col gap-0.5 min-w-[140px]">
            <div class="text-[10px] text-foreground/70">
              Installing update...
            </div>
            <div class="w-full h-[4px] bg-white/10 rounded-full overflow-hidden">
              <div class="updater-bar-installing w-full h-full rounded-full" />
            </div>
          </div>
        </Show>

        {/* Error state with retry */}
        <Show when={updaterStore.state.status === "error"}>
          <button
            type="button"
            class="px-3 py-1 rounded-md bg-destructive hover:bg-destructive/90 text-white text-xs font-medium flex items-center gap-1.5 transition-colors"
            onClick={() => updaterStore.checkForUpdates()}
            title={updaterStore.state.error || "Update failed"}
          >
            <span>⚠</span>
            <span>Update failed - Retry</span>
          </button>
        </Show>

        <Show when={props.recordPromptVisible}>
          <RecordPrompt
            sourceApp={props.recordPromptSourceApp}
            onRecord={() => props.onRecordConversation?.()}
            onDismiss={() => props.onDismissRecordPrompt?.()}
          />
        </Show>

        <Show when={authStore.isAuthenticated}>
          <BalanceDisplay />
        </Show>

        <button
          type="button"
          data-testid="titlebar-meetings-button"
          class="relative flex items-center justify-center w-7 h-7 border-none rounded-md cursor-pointer transition-all duration-100 active:scale-95"
          classList={{
            "bg-transparent text-muted-foreground hover:bg-surface-2 hover:text-foreground":
              !props.meetingRecording,
            "text-success bg-success/10 meeting-recording-glow":
              props.meetingRecording,
          }}
          onClick={props.onToggleMeetings}
          title={
            props.meetingRecording
              ? "Recording in progress — open Meetings to stop"
              : "Meetings"
          }
          aria-label={
            props.meetingRecording ? "Recording in progress" : "Meetings"
          }
        >
          <MeetingsIcon />
          <Show when={props.meetingRecording}>
            <span class="absolute -top-0.5 -right-0.5 h-2 w-2 rounded-full bg-success ring-2 ring-surface-1 animate-pulse" />
          </Show>
        </button>

        <button
          type="button"
          class="flex items-center justify-center w-7 h-7 border-none rounded-md bg-transparent text-muted-foreground cursor-pointer transition-all duration-100 hover:bg-surface-2 hover:text-foreground active:scale-95"
          onClick={props.onToggleSettings}
          title="Settings"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            role="img"
            aria-label="Settings"
          >
            <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
            <circle cx="12" cy="12" r="3" />
          </svg>
        </button>

        <button
          type="button"
          class="flex items-center justify-center w-7 h-7 border-none rounded-md bg-transparent text-muted-foreground cursor-pointer transition-all duration-100 hover:bg-surface-2 hover:text-foreground active:scale-95"
          onClick={props.onToggleSkills}
          title="Skills"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            role="img"
            aria-label="Skills"
          >
            <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
            <path d="M4 4.5A2.5 2.5 0 0 1 6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15z" />
            <path d="M8 7h8" />
            <path d="M8 11h6" />
          </svg>
        </button>

        <Show when={!authStore.isAuthenticated}>
          <button
            type="button"
            class="flex items-center justify-center h-7 px-3 border border-primary/30 rounded-md bg-primary/10 text-primary text-[13px] font-medium cursor-pointer transition-all duration-100 hover:bg-primary/20 hover:border-primary/50 active:scale-95"
            onClick={props.onSignInClick}
          >
            Sign In
          </button>
        </Show>
      </div>
    </div>
  );
};
