import { useEffect, useState } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
import { useStore } from "../store";

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handler = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handler);
    return () => window.removeEventListener("resize", handler);
  }, []);
  return width;
}

interface Props {
  onOpenSettings: () => void;
}

export default function TitleBar({ onOpenSettings }: Props) {
  const { view, closeGuide, activeGuideData } = useStore();
  const windowWidth = useWindowWidth();

  function handleDragMouseDown(e: React.MouseEvent) {
    if (e.button === 0) {
      getCurrentWindow().startDragging();
    }
  }

  async function handleClose() {
    const viewer = await WebviewWindow.getByLabel("image-viewer");
    if (viewer) {
      try { await viewer.close(); } catch (_) {}
    }
    await getCurrentWindow().close();
  }

  async function handleMinimize() {
    await getCurrentWindow().minimize();
  }

  return (
    <div
      style={{
        display: "flex", alignItems: "center", height: "40px",
        background: "#0d1117", borderBottom: "1px solid #2d3748",
        padding: "0 12px", gap: "8px", flexShrink: 0,
        userSelect: "none",
      }}
    >
      {/* Zone draggable — appel direct à startDragging() */}
      <div
        onMouseDown={handleDragMouseDown}
        style={{
          display: "flex", alignItems: "center", gap: "8px", flex: 1,
          cursor: "grab", userSelect: "none",
        }}
      >
        <img src="/logo_tougli.png" style={{ pointerEvents: "none", width: "24px", height: "24px", objectFit: "contain" }} />
        <span style={{ pointerEvents: "none", fontSize: "13px", fontWeight: 700, color: "#f0c040", letterSpacing: "0.05em" }}>
          TougliGui
        </span>
        {view === "guide" && activeGuideData && windowWidth >= 400 && (
          <>
            <span style={{ pointerEvents: "none", color: "#4a5568", fontSize: "12px" }}>›</span>
            <span style={{ pointerEvents: "none", fontSize: "12px", color: "#94a3b8" }}>{activeGuideData.name}</span>
          </>
        )}
      </div>

      {/* Boutons — pas de drag, interactions normales */}
      <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
        {view === "guide" && (
          <TitleButton onClick={closeGuide} title="Retour à l'accueil">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
              <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
            </svg>
          </TitleButton>
        )}

        <TitleButton onClick={onOpenSettings} title="Paramètres">
          ⚙
        </TitleButton>

        <div style={{ width: "1px", height: "16px", background: "#2d3748", margin: "0 4px" }} />

        <TitleButton onClick={handleMinimize} title="Réduire">—</TitleButton>
        <TitleButton onClick={handleClose} title="Fermer" danger>✕</TitleButton>
      </div>
    </div>
  );
}

function TitleButton({
  children, onClick, title, active, danger, disabled
}: {
  children: React.ReactNode;
  onClick?: () => void;
  title?: string;
  active?: boolean;
  danger?: boolean;
  disabled?: boolean;
}) {
  return (
    <button
      onClick={onClick}
      title={title}
      disabled={disabled}
      style={{
        background: active ? "rgba(240,192,64,0.15)" : "transparent",
        border: active ? "1px solid rgba(240,192,64,0.4)" : "1px solid transparent",
        color: active ? "#f0c040" : danger ? "#f87171" : "#94a3b8",
        padding: "3px 8px",
        borderRadius: "5px",
        cursor: disabled ? "default" : "pointer",
        fontSize: "12px",
        fontWeight: 500,
        transition: "all 0.15s",
        display: "flex", alignItems: "center", gap: "4px",
        opacity: disabled ? 0.5 : 1,
      }}
      onMouseEnter={e => {
        if (!disabled) {
          const el = e.currentTarget;
          el.style.background = active ? "rgba(240,192,64,0.25)" : danger ? "rgba(248,113,113,0.1)" : "rgba(255,255,255,0.05)";
          el.style.color = active ? "#f0c040" : danger ? "#f87171" : "#e2e8f0";
        }
      }}
      onMouseLeave={e => {
        const el = e.currentTarget;
        el.style.background = active ? "rgba(240,192,64,0.15)" : "transparent";
        el.style.color = active ? "#f0c040" : danger ? "#f87171" : "#94a3b8";
      }}
    >
      {children}
    </button>
  );
}

