'use client';
import { useRef, useState } from 'react';
/** Ayarlar: kapanış kartında kullanılacak ofis logosunu yükler / kaldırır. */
export function LogoUpload({ initial }: { initial: string | null }) {
  const [key, setKey] = useState(initial); const [busy, setBusy] = useState(false); const [err, setErr] = useState('');
  const input = useRef<HTMLInputElement>(null);
  const upload = async (f: File) => {
    setErr('');
    if (f.size > 2 * 1024 * 1024) { setErr('Logo en fazla 2 MB olabilir'); return; }
    setBusy(true);
    const fd = new FormData(); fd.set('logo', f);
    const r = await fetch('/api/hesap/logo', { method: 'POST', body: fd }); const j = await r.json().catch(() => ({}));
    if (r.ok) setKey(j.key); else setErr(j.error || 'Yüklenemedi');
    setBusy(false); if (input.current) input.current.value = '';
  };
  const remove = async () => { setBusy(true); const r = await fetch('/api/hesap/logo', { method: 'DELETE' }); if (r.ok) setKey(null); setBusy(false); };
  return (
    <div>
      <div className="flex items-center gap-3">
        <div className="flex h-20 w-36 shrink-0 items-center justify-center border border-ink/20 bg-white p-2">
          {key ? <img src={`/api/hesap/logo?v=${encodeURIComponent(key)}`} alt="Ofis logosu" className="max-h-full max-w-full object-contain" /> : <span className="text-[12px] text-ink-soft">Logo yok</span>}
        </div>
        <div className="flex flex-col gap-2">
          <input ref={input} type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) upload(f); }} />
          <button type="button" disabled={busy} onClick={() => input.current?.click()} className="btn-ink btn-sm">{busy ? 'Yükleniyor…' : key ? 'Logoyu değiştir' : 'Logo yükle'}</button>
          {key && <button type="button" disabled={busy} onClick={remove} className="btn-line btn-sm">Kaldır</button>}
        </div>
      </div>
      <p className="mt-2 text-[12.5px] text-ink-soft">PNG, JPG ya da WEBP, en fazla 2 MB. Şeffaf arka planlı yatay logo en iyi sonucu verir. Yeni siparişlerin kapanış kartında kullanılır.</p>
      {err && <p className="mt-1 text-[13px] font-semibold text-survey-dark">{err}</p>}
    </div>
  );
}
