"use client";
import { useState } from 'react';

export function useTrustMode() {
  const [trustMode, setTrustMode] = useState('approval_required');
  const [trustModeBusy, setTrustModeBusy] = useState(false);
  const [trustModePromptOpen, setTrustModePromptOpen] = useState(false);

  async function applyTrustMode(next) {
    setTrustModeBusy(true);
    try {
      const res = await fetch('/api/settings/trust-mode', {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ mode: next, confirm: next === 'auto' }),
      });
      if (!res.ok) throw new Error(await res.text());
      const data = await res.json();
      setTrustMode(data.mode || next);
    } catch {
      // leave previous mode in place
    } finally {
      setTrustModeBusy(false);
    }
  }

  function toggleTrustMode() {
    const next = trustMode === 'auto' ? 'approval_required' : 'auto';
    if (next === 'auto') {
      setTrustModePromptOpen(true);
      return;
    }
    applyTrustMode(next);
  }

  async function confirmEnableTrustMode() {
    await applyTrustMode('auto');
    setTrustModePromptOpen(false);
  }

  function cancelEnableTrustMode() {
    setTrustModePromptOpen(false);
  }

  return {
    trustMode,
    setTrustMode,
    trustModeBusy,
    trustModePromptOpen,
    applyTrustMode,
    toggleTrustMode,
    confirmEnableTrustMode,
    cancelEnableTrustMode,
  };
}
