import { useState } from 'react';
import { apiFetch } from '../lib/api';

export function useMailTitleEdit() {
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function saveTitle(connectionId: string, title: string): Promise<boolean> {
    setSaving(true);
    setError(null);
    try {
      await apiFetch(`/api/mail-connections/${connectionId}`, {
        method: 'PATCH',
        body: { title: title.trim() || null },
      });
      return true;
    } catch (e: any) {
      setError(e?.message ?? 'unknown');
      return false;
    } finally {
      setSaving(false);
    }
  }

  return { saveTitle, saving, error };
}
