'use client'

import { useState } from 'react'
import { RefreshCw } from 'lucide-react'

export function SyncButton() {
  const [busy, setBusy] = useState(false)

  const sync = async () => {
    setBusy(true)
    try {
      await fetch('/api/sync', { method: 'POST' })
      // Give the Mac a few seconds to dump + post, then refresh the overview.
      setTimeout(() => { window.dispatchEvent(new Event('capture-uploaded')); setBusy(false) }, 6000)
    } catch {
      setBusy(false)
    }
  }

  return (
    <button
      onClick={sync}
      disabled={busy}
      className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50"
      aria-label="Sync from Apple"
    >
      <RefreshCw className={`h-4 w-4 ${busy ? 'animate-spin' : ''}`} />
      {busy ? 'Syncing…' : 'Sync'}
    </button>
  )
}
