import { useEffect, useState } from 'react'
import { api } from '../lib/api'

export function ClaudeModeToggle() {
  const [mode, setMode] = useState<'api' | 'proxy' | 'unknown'>('unknown')
  const [busy, setBusy] = useState(false)

  useEffect(() => {
    api.system.getClaudeMode().then((r) => setMode(r.mode)).catch(() => {})
  }, [])

  async function flip() {
    if (busy) return
    setBusy(true)
    const target = mode === 'proxy' ? 'api' : 'proxy'
    try {
      const result = await api.system.setClaudeMode(target)
      setMode(result.mode)
    } catch (err) {
      console.error('claude-mode flip failed', err)
    } finally {
      setBusy(false)
    }
  }

  const label = mode === 'proxy' ? 'sub' : mode === 'api' ? 'api' : '?'
  const tooltip =
    mode === 'proxy'
      ? 'Claude routed via Max subscription proxy (free). Click to switch to direct API.'
      : mode === 'api'
      ? 'Claude routed via direct Anthropic API (billed). Click to switch to subscription proxy.'
      : 'Claude provider mode unknown'

  const dotColor = mode === 'proxy' ? 'bg-emerald-500' : mode === 'api' ? 'bg-amber-500' : 'bg-gray-400'

  return (
    <button
      onClick={flip}
      disabled={busy || mode === 'unknown'}
      title={tooltip}
      className="group flex items-center gap-2 px-2.5 py-1 rounded border border-gray-200 dark:border-gray-700 hover:border-gray-400 dark:hover:border-gray-500 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait"
    >
      <span className={`w-1.5 h-1.5 rounded-full ${dotColor} ${busy ? 'pulse-soft' : ''}`} />
      <span className="font-mono text-[10px] uppercase tracking-wider text-gray-500 dark:text-gray-400">claude</span>
      <span className="font-mono text-[10px] tabular text-gray-900 dark:text-gray-100">{label}</span>
    </button>
  )
}
