import { useEffect, useState } from 'react'
import { Minus, Square, RestoreDown, X } from '../../lib/icons'

/**
 * Custom titlebar for the Tauri desktop shell. With `decorations: false` on
 * the window, the OS chrome is gone - this bar provides the dragging region
 * (`data-tauri-drag-region`) and the min / max / close affordances.
 *
 * Themed to match the rest of the app: 36px tall, void-tone background with
 * a subtle bottom border, hairline accent on hover for the buttons, classic
 * red on the close hover. Title shown center-left.
 */
export default function Titlebar() {
  const [maximized, setMaximized] = useState(false)
  const [win, setWin] = useState<any>(null)

  useEffect(() => {
    let cancelled = false
    let unlisten: (() => void) | undefined
    import('@tauri-apps/api/window').then(({ getCurrentWindow }) => {
      if (cancelled) return
      const w = getCurrentWindow()
      setWin(w)
      w.isMaximized().then((v: boolean) => {
        if (!cancelled) setMaximized(v)
      })
      w.onResized(async () => {
        const v = await w.isMaximized()
        if (!cancelled) setMaximized(v)
      }).then((u: () => void) => {
        unlisten = u
      })
    })
    return () => {
      cancelled = true
      unlisten?.()
    }
  }, [])

  return (
    <div
      data-tauri-drag-region
      className="app-titlebar shrink-0 h-9 flex items-center justify-between bg-void/95 border-b border-border select-none"
      style={{ WebkitUserSelect: 'none' }}
    >
      <div data-tauri-drag-region className="flex items-center gap-2 pl-3">
        <span
          data-tauri-drag-region
          className="w-4 h-4 rounded-md bg-gradient-to-br from-accent to-accent-press grid place-items-center text-void font-bold text-[9px]"
        >
          j
        </span>
        <span
          data-tauri-drag-region
          className="text-[11.5px] font-medium tracking-tight text-text-2"
        >
          Jellybloom
        </span>
      </div>

      <div className="flex items-stretch h-full">
        <TitlebarButton onClick={() => win?.minimize()} aria-label="Minimize">
          <Minus size={14} stroke={2} />
        </TitlebarButton>
        <TitlebarButton onClick={() => win?.toggleMaximize()} aria-label={maximized ? 'Restore' : 'Maximize'}>
          {maximized ? <RestoreDown size={12} stroke={2} /> : <Square size={12} stroke={2} />}
        </TitlebarButton>
        <TitlebarButton onClick={() => win?.close()} aria-label="Close" variant="close">
          <X size={14} stroke={2.25} />
        </TitlebarButton>
      </div>
    </div>
  )
}

function TitlebarButton({
  children,
  onClick,
  variant,
  ...props
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { variant?: 'close' }) {
  return (
    <button
      {...props}
      onClick={onClick}
      className={`w-11 h-full grid place-items-center text-text-3 transition-colors duration-100 focus-ring ${
        variant === 'close'
          ? 'hover:bg-red-500 hover:text-white'
          : 'hover:bg-elevated hover:text-text-1'
      }`}
    >
      {children}
    </button>
  )
}
