Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

31.5 KB
Raw Blame
import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router';
import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save, ExternalLink, User, Key, Monitor, Wand2 } from 'lucide-react';
import toast from '../ui/Toast';
import { formatDateTime } from '../../utils/formatters';
import * as api from '../../services/api';
import ProviderModelSelector from '../ProviderModelSelector';
import useProviderModels from '../../hooks/useProviderModels';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { FormField } from '../ui/FormField';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
import { useGoogleAutoConfigProgress } from '../../hooks/useGoogleAutoConfigProgress';

const TYPE_ICONS = { gmail: Mail, outlook: Globe, teams: MessageSquare };
const TYPE_LABELS = { gmail: 'Gmail (API)', outlook: 'Outlook (Playwright)', teams: 'Teams (Playwright)' };

const DEFAULT_REPLY_TEMPLATE = `You are a professional email assistant. Draft a reply to the following email.

From: {{from}}
Subject: {{subject}}
Body:
{{body}}

{{#instructions}}
Additional instructions: {{instructions}}
{{/instructions}}

Write a professional, concise reply. Match the tone of the original message.`;

export default function ConfigTab({ accounts, setAccounts }) {
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ name: '', type: 'gmail', email: '' });
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(null);
  const [clearingCache, setClearingCache] = useState(null);
  const [confirmClear, setConfirmClear] = useState(null);
  const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();

  // Google OAuth status for Gmail accounts
  const [googleAuth, setGoogleAuth] = useState(null);
  const [oauthForm, setOauthForm] = useState({ clientId: '', clientSecret: '' });
  const [savingOAuth, setSavingOAuth] = useState(false);
  const [reauthorizing, setReauthorizing] = useState(false);
  const { progress: autoConfigProgress, run: runAutoConfig, mounted: autoConfigMounted } = useGoogleAutoConfigProgress();
  const [autoConfigStep, setAutoConfigStep] = useState(null);

  // AI config
  const [config, setConfig] = useState(null);
  const [configLoading, setConfigLoading] = useState(true);
  const [configDirty, setConfigDirty] = useState(false);

  // Separate provider/model selectors for triage and reply
  const triage = useProviderModels();
  const reply = useProviderModels();
  const {
    selectedProviderId: triageSelectedProviderId,
    selectedModel: triageSelectedModel,
    setSelectedProviderId: setTriageSelectedProviderId,
    setSelectedModel: setTriageSelectedModel
  } = triage;
  const {
    selectedProviderId: replySelectedProviderId,
    selectedModel: replySelectedModel,
    setSelectedProviderId: setReplySelectedProviderId,
    setSelectedModel: setReplySelectedModel
  } = reply;

  const loadConfig = useCallback(async () => {
    const settings = await api.getSettings().catch(() => ({}));
    const msgConfig = settings?.messages || {};
    const triageConfig = msgConfig.triage || {};
    const replyConfig = msgConfig.reply || {};
    setConfig({
      replyTemplate: msgConfig.replyTemplate || DEFAULT_REPLY_TEMPLATE,
      // Unsupported legacy setting: no runtime consumer, preserved opaquely so saves do not discard it
      ...(Object.hasOwn(msgConfig, "forwardTemplate") ? { legacyForwardTemplate: msgConfig.forwardTemplate } : {}),
      voiceMode: msgConfig.voiceMode ?? false
    });
    // Restore saved provider/model - per-action configs with legacy fallback
    const triageProviderId = triageConfig.providerId || msgConfig.providerId;
    const triageModel = triageConfig.model || msgConfig.model;
    const replyProviderId = replyConfig.providerId || msgConfig.providerId;
    const replyModel = replyConfig.model || msgConfig.model;
    if (triageProviderId) setTriageSelectedProviderId(triageProviderId);
    if (triageModel) setTriageSelectedModel(triageModel);
    if (replyProviderId) setReplySelectedProviderId(replyProviderId);
    if (replyModel) setReplySelectedModel(replyModel);
    setConfigLoading(false);
  }, [setReplySelectedModel, setReplySelectedProviderId, setTriageSelectedModel, setTriageSelectedProviderId]);

  useEffect(() => { loadConfig(); }, [loadConfig]);

  // Check Google OAuth status when Gmail accounts exist
  const hasGmailAccount = accounts.some(a => a.type === 'gmail');
  const gmailAuthorized = Boolean(googleAuth?.hasTokens && !googleAuth?.needsScopeUpgrade);
  const fetchGoogleAuth = useCallback(() => {
    api.getGoogleAuthStatus()
      .then(setGoogleAuth)
      .catch(err => console.warn(`⚠️ Failed to load Google auth status: ${err.message}`));
  }, []);

  useEffect(() => {
    if (hasGmailAccount) fetchGoogleAuth();
  }, [fetchGoogleAuth, hasGmailAccount]);

  // Google redirects back to the surface that started authorization. Surface a
  // callback failure once, then remove it so reloads do not repeat the toast.
  const [searchParams, setSearchParams] = useSearchParams();
  const oauthError = searchParams.get('oauthError');
  useEffect(() => {
    if (!oauthError) return;
    toast.error(`Google OAuth failed: ${oauthError}`);
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      next.delete('oauthError');
      return next;
    }, { replace: true });
  }, [oauthError, setSearchParams]);

  const handleReauthorize = () => {
    setReauthorizing(true);
    api.getGoogleAuthUrl({ returnTo: 'messages', silent: true })
      .then(({ url }) => {
        window.open(url, '_blank');
        toast.success('Complete authorization in the opened browser tab');
      })
      .catch(() => toast.error('Failed to get auth URL'))
      .finally(() => setReauthorizing(false));
  };

  const handleSaveOAuthCredentials = async () => {
    if (!oauthForm.clientId || !oauthForm.clientSecret) {
      return toast.error('Both Client ID and Client Secret are required');
    }
    setSavingOAuth(true);
    const saved = await api.saveGoogleAuthCredentials(oauthForm, { silent: true }).catch(() => null);
    setSavingOAuth(false);
    if (!saved) return toast.error('Failed to save credentials');
    toast.success('OAuth credentials saved');
    fetchGoogleAuth();
    handleReauthorize();
  };

  const handleAutoConfigStart = async () => {
    const result = await api.startGoogleAutoConfig({ silent: true }).catch(() => null);
    if (!result || result.error) return toast.error(result?.error || 'Failed to open browser');
    setAutoConfigStep('login');
    toast.success('Google Cloud Console opened in PortOS browser');
  };

  const handleAutoConfigContinue = async () => {
    setAutoConfigStep('running');
    const email = accounts.find(a => a.type === 'gmail')?.email || '';
    const result = await runAutoConfig(email);
    if (!autoConfigMounted.current) return;
    if (!result || result.error) {
      setAutoConfigStep('login');
      return toast.error(result?.error || 'Automated setup failed. Try manual setup instead.');
    }
    setAutoConfigStep('done');
    fetchGoogleAuth();
    toast.success('Google OAuth setup complete');
    handleReauthorize();
  };

  const handleEnableGmailApi = () => {
    api.enableGmailApi({ silent: true })
      .then(r => toast.success(r.message))
      .catch(() => toast.error('Failed to open Gmail API page'));
  };

  const handleSaveConfig = async () => {
    const patch = {
      messages: {
        triage: {
          providerId: triageSelectedProviderId,
          model: triageSelectedModel
        },
        reply: {
          providerId: replySelectedProviderId,
          model: replySelectedModel
        },
        replyTemplate: config.replyTemplate,
        ...(Object.hasOwn(config, "legacyForwardTemplate") ? { forwardTemplate: config.legacyForwardTemplate } : {}),
        voiceMode: config.voiceMode
      }
    };
    const result = await api.updateSettings(patch, { silent: true }).catch(() => null);
    if (!result) return toast.error('Failed to save config');
    toast.success('Message config saved');
    setConfigDirty(false);
  };

  const updateTemplate = (key, value) => {
    setConfig(prev => ({ ...prev, [key]: value }));
    setConfigDirty(true);
  };

  // Account CRUD
  const handleCreate = async () => {
    if (!form.name) return toast.error('Name is required');
    setSaving(true);
    const result = await api.createMessageAccount(form, { silent: true }).catch(() => null);
    setSaving(false);
    if (!result) return toast.error('Failed to create account');
    setShowForm(false);
    setForm({ name: '', type: 'gmail', email: '' });
    toast.success('Account created');
    setAccounts(prev => [...prev, result]);
  };

  const handleDelete = async (id) => {
    setDeleting(id);
    const ok = await api.deleteMessageAccount(id).then(() => true).catch(() => false);
    setDeleting(null);
    if (!ok) return;
    toast.success('Account deleted');
    setAccounts(prev => prev.filter(a => a.id !== id));
  };

  const handleToggle = async (account) => {
    const result = await api.updateMessageAccount(account.id, { enabled: !account.enabled }, { silent: true }).catch(() => null);
    if (!result) return toast.error('Failed to update account');
    toast.success(account.enabled ? 'Account disabled' : 'Account enabled');
    setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, enabled: !a.enabled } : a));
  };

  // Per-account reply detection: ingest sent mail so Tribe-outreach won't nudge an
  // already-replied thread (#2796). Default-on for Gmail (absent === on).
  const handleToggleIngestSent = async (account) => {
    const next = account.syncConfig?.ingestSent === false; // flipping to enabled
    const result = await api.updateMessageAccount(
      account.id,
      { syncConfig: { ...account.syncConfig, ingestSent: next } },
      { silent: true }
    ).catch(() => null);
    if (!result) return toast.error('Failed to update account');
    toast.success(next ? 'Reply detection enabled' : 'Reply detection disabled');
    setAccounts(prev => prev.map(a => a.id === account.id
      ? { ...a, syncConfig: { ...a.syncConfig, ingestSent: next } }
      : a));
  };

  const handleClearCache = async (accountId) => {
    if (confirmClear !== accountId) {
      setConfirmClear(accountId);
      return;
    }
    setConfirmClear(null);
    setClearingCache(accountId);
    const result = await api.clearMessageCache(accountId).catch(() => null);
    setClearingCache(null);
    if (!result) return;
    toast.success('Cache cleared');
  };

  const renderProviderSection = (label, description, hook) => (
    <div className="p-4 bg-port-card rounded-lg border border-port-border">
      <h3 className="text-sm font-medium text-white mb-1">{label}</h3>
      <p className="text-xs text-gray-500 mb-3">{description}</p>
      {hook.loading ? (
        <RefreshCw size={16} className="text-port-accent animate-spin" />
      ) : hook.providers.length === 0 ? (
        <p className="text-sm text-gray-500">No AI providers configured. Add one in AI Providers.</p>
      ) : (
        <ProviderModelSelector
          providers={hook.providers}
          selectedProviderId={hook.selectedProviderId}
          selectedModel={hook.selectedModel}
          availableModels={hook.availableModels}
          onProviderChange={(id) => { hook.setSelectedProviderId(id); setConfigDirty(true); }}
          onModelChange={(m) => { hook.setSelectedModel(m); setConfigDirty(true); }}
        />
      )}
    </div>
  );

  return (
    <div className="space-y-8">
      {/* Accounts */}
      <section>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-3">
          <h2 className="text-lg font-semibold text-white">Email Accounts</h2>
          <button
            onClick={() => setShowForm(!showForm)}
            className="flex items-center justify-center gap-2 px-3 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors self-start sm:self-auto"
          >
            <Plus size={16} />
            Add Account
          </button>
        </div>

        {hasGmailAccount && (
          <div className="p-4 mb-4 bg-port-card border border-port-border rounded-lg space-y-3">
            <h3 className="text-sm font-medium text-white">Gmail Setup</h3>
            <div className="space-y-2">
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                <div className="flex items-center gap-2 text-sm">
                  <span className={`w-2 h-2 rounded-full ${gmailAuthorized ? 'bg-port-success' : 'bg-port-warning'}`} />
                  <span className="text-gray-300">
                    {gmailAuthorized
                      ? 'Google OAuth authorized'
                      : googleAuth?.hasTokens
                        ? 'Google OAuth needs Gmail permission'
                        : googleAuth?.hasCredentials
                          ? 'Google OAuth authorization pending'
                          : 'Google OAuth setup required'}
                  </span>
                </div>
                {googleAuth?.hasCredentials && (
                  <button
                    onClick={handleReauthorize}
                    disabled={reauthorizing}
                    className={`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg transition-colors disabled:opacity-50 shrink-0 self-start sm:self-auto ${
                      gmailAuthorized
                        ? 'text-gray-400 hover:text-white'
                        : 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
                    }`}
                    title={gmailAuthorized ? 'Re-authorize to update permissions' : 'Authorize Gmail with Google'}
                  >
                    {gmailAuthorized ? <RefreshCw size={12} /> : <ExternalLink size={14} />}
                    {gmailAuthorized ? 'Re-authorize' : 'Authorize'}
                  </button>
                )}
              </div>

              {!googleAuth?.hasCredentials && (
                <div className="space-y-3 rounded-lg border border-port-border bg-port-bg/50 p-3">
                  <p className="text-xs text-gray-500">
                    PortOS needs a Google Cloud OAuth client before it can ask for access to Gmail.
                  </p>

                  {!autoConfigStep ? (
                    <button
                      onClick={handleAutoConfigStart}
                      className="flex w-full items-center justify-center gap-1.5 rounded border border-port-accent/20 bg-port-accent/10 px-3 py-2 text-xs text-port-accent hover:bg-port-accent/20"
                    >
                      <Monitor size={14} />
                      Set up with PortOS Browser
                    </button>
                  ) : autoConfigStep === 'running' ? (
                    <div className="flex items-center gap-2 rounded border border-port-border bg-port-bg/80 p-3">
                      <RefreshCw size={14} className="shrink-0 animate-spin text-port-accent" />
                      <p className="text-xs text-gray-400" role="status" aria-live="polite">
                        {autoConfigProgress?.message || 'Automating Google Cloud setup... This may take up to a minute.'}
                      </p>
                    </div>
                  ) : autoConfigStep === 'login' ? (
                    <div className="space-y-2 rounded border border-port-border bg-port-bg/80 p-3">
                      <div className="flex items-center gap-1.5 text-xs font-medium text-port-accent">
                        <Monitor size={12} />
                        Google Cloud Console is open in the PortOS browser
                      </div>
                      <div className="space-y-1 text-xs text-gray-400">
                        <p>1. Log in to your Google account if needed.</p>
                        <p>2. Select or create a Google Cloud project.</p>
                        <p>3. Click Continue and PortOS will finish the setup.</p>
                      </div>
                      <div className="flex flex-wrap gap-2 pt-1">
                        <button
                          onClick={handleAutoConfigContinue}
                          className="flex items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-xs text-white hover:bg-port-accent/80"
                        >
                          <Wand2 size={12} /> Continue
                        </button>
                        <button
                          onClick={() => setAutoConfigStep(null)}
                          className="rounded bg-port-border px-3 py-1.5 text-xs text-gray-400 hover:text-white"
                        >
                          Cancel
                        </button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center gap-1.5 p-2 text-xs text-port-success">
                      <Key size={12} />
                      Setup complete. Finish authorization in the opened tab.
                    </div>
                  )}

                  <details className="text-xs text-gray-600">
                    <summary className="cursor-pointer font-medium text-gray-400 hover:text-white">
                      Manual setup (paste credentials)
                    </summary>
                    <div className="mt-2 space-y-2">
                      <FormField label="Google OAuth Client ID" labelClassName="block text-xs text-gray-400 mb-1">
                        <input
                          type="text"
                          value={oauthForm.clientId}
                          onChange={e => setOauthForm(f => ({ ...f, clientId: e.target.value }))}
                          placeholder="123456789-abc.apps.googleusercontent.com"
                          className="w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-white placeholder-gray-600"
                        />
                      </FormField>
                      <FormField label="Google OAuth Client Secret" labelClassName="block text-xs text-gray-400 mb-1">
                        <input
                          type="password"
                          value={oauthForm.clientSecret}
                          onChange={e => setOauthForm(f => ({ ...f, clientSecret: e.target.value }))}
                          placeholder="GOCSPX-..."
                          className="w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-white placeholder-gray-600"
                        />
                      </FormField>
                      <button
                        onClick={handleSaveOAuthCredentials}
                        disabled={savingOAuth || !oauthForm.clientId || !oauthForm.clientSecret}
                        className="flex items-center gap-1 rounded bg-port-accent px-2.5 py-1.5 text-xs text-white hover:bg-port-accent/80 disabled:opacity-50"
                      >
                        {savingOAuth ? 'Saving...' : 'Save & Authorize'}
                      </button>
                    </div>
                  </details>
                </div>
              )}

              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                <div className="flex items-center gap-2 text-sm">
                  <span className="w-2 h-2 rounded-full bg-gray-500" />
                  <span className="text-gray-300">Gmail API</span>
                </div>
                <button
                  onClick={handleEnableGmailApi}
                  className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors self-start sm:self-auto"
                  title="Open Google Cloud Console to enable Gmail API"
                >
                  <ExternalLink size={12} />
                  Enable in Console
                </button>
              </div>
            </div>
            <p className="text-xs text-gray-500">
              Gmail requires the Gmail API in Google Cloud and Google OAuth permission. Guided setup handles both;
              manual setup can use "Enable in Console" to verify the API.
            </p>
          </div>
        )}

        {showForm && (
          <div className="p-4 bg-port-card rounded-lg border border-port-border space-y-3 mb-4">
            <FormField label="Name">
              <input
                type="text"
                value={form.name}
                onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))}
                placeholder="e.g. Work Gmail"
                className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
              />
            </FormField>
            <FormField label="Type">
              <select
                value={form.type}
                onChange={(e) => setForm(f => ({ ...f, type: e.target.value }))}
                className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"
              >
                <option value="gmail">Gmail (API)</option>
                <option value="outlook">Outlook (Playwright)</option>
                <option value="teams">Teams (Playwright)</option>
              </select>
            </FormField>
            <FormField label="Email">
              <input
                type="email"
                value={form.email}
                onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))}
                placeholder="[email protected]"
                className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
              />
            </FormField>
            <div className="flex gap-2">
              <button
                onClick={handleCreate}
                disabled={saving}
                className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors disabled:opacity-50"
              >
                {saving ? 'Creating...' : 'Create'}
              </button>
              <button
                onClick={() => setShowForm(false)}
                className="px-4 py-2 bg-port-border text-gray-300 rounded-lg text-sm hover:bg-port-border/80 transition-colors"
              >
                Cancel
              </button>
            </div>
          </div>
        )}

        {accounts.length === 0 && !showForm && (
          <div className="text-center py-12 text-gray-500">
            <Mail size={48} className="mx-auto mb-4 opacity-50" />
            <p>No accounts configured</p>
            <p className="text-sm mt-1">Add a Gmail, Outlook, or Teams account to get started</p>
          </div>
        )}

        <div className="space-y-2">
          {accounts.map((account) => {
            const Icon = TYPE_ICONS[account.type] || Mail;
            const isPendingAuthorization = account.type === 'gmail' && account.enabled && !gmailAuthorized;
            return (
              <div
                key={account.id}
                className="p-4 bg-port-card rounded-lg border border-port-border"
              >
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                  <div className="flex items-center gap-3 min-w-0">
                    <Icon size={20} className={`shrink-0 ${account.enabled ? 'text-port-accent' : 'text-gray-600'}`} />
                    <div className="min-w-0 flex-1">
                      <div className="text-sm font-medium text-white truncate">{account.name}</div>
                      <div className="text-xs text-gray-500 truncate">
                        {TYPE_LABELS[account.type]} · {account.email || 'No email set'}
                      </div>
                      {account.lastSyncAt && (
                        <div className="text-xs text-gray-600 truncate">
                          Last sync: {formatDateTime(account.lastSyncAt)} ({account.lastSyncStatus})
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="flex flex-wrap items-center gap-2 pt-2 sm:pt-0 border-t border-port-border/40 sm:border-0">
                    {account.type === 'gmail' && (
                      <button
                        onClick={() => handleToggleIngestSent(account)}
                        className={`px-2 py-1 rounded text-xs transition-colors ${
                          account.syncConfig?.ingestSent !== false
                            ? 'bg-port-accent/20 text-port-accent'
                            : 'bg-gray-700 text-gray-400'
                        }`}
                        title="Ingest sent mail so Tribe outreach won't nudge threads you've already replied to"
                      >
                        {account.syncConfig?.ingestSent !== false ? 'Reply detection: on' : 'Reply detection: off'}
                      </button>
                    )}
                    <button
                      onClick={() => handleToggle(account)}
                      className={`px-2 py-1 rounded text-xs transition-colors ${
                        isPendingAuthorization
                          ? 'bg-port-warning/20 text-port-warning'
                          : account.enabled
                          ? 'bg-port-success/20 text-port-success'
                          : 'bg-gray-700 text-gray-400'
                      }`}
                      title={isPendingAuthorization ? 'Account is enabled but waiting for Google authorization' : undefined}
                    >
                      {isPendingAuthorization ? 'Pending authorization' : account.enabled ? 'Enabled' : 'Disabled'}
                    </button>
                    <button
                      onClick={() => handleClearCache(account.id)}
                      disabled={clearingCache === account.id}
                      className={`px-2 py-1 rounded text-xs transition-colors ${
                        confirmClear === account.id
                          ? 'bg-port-error/20 text-port-error'
                          : 'bg-port-warning/10 text-port-warning hover:bg-port-warning/20'
                      } disabled:opacity-50`}
                      onBlur={() => setConfirmClear(null)}
                      title="Clear cached messages for this account"
                    >
                      {clearingCache === account.id ? 'Clearing...' : confirmClear === account.id ? 'Are you sure?' : 'Clear Cache'}
                    </button>
                    <button
                      onClick={() => requestDelete(account.id)}
                      disabled={deleting === account.id}
                      className="p-1 text-gray-500 hover:text-port-error transition-colors"
                      title="Delete account"
                    >
                      {deleting === account.id ? (
                        <RefreshCw size={16} className="animate-spin" />
                      ) : (
                        <Trash2 size={16} />
                      )}
                    </button>
                  </div>
                </div>
                {isConfirming(account.id) && (
                  <InlineConfirmRow
                    className="mt-2"
                    question="Remove this account? This cannot be undone."
                    confirmText="Remove"
                    confirmTitle="Remove account"
                    cancelTitle="Cancel"
                    onConfirm={() => confirmDelete(() => handleDelete(account.id))}
                    onCancel={cancelDelete}
                  />
                )}
              </div>
            );
          })}
        </div>
      </section>

      {/* AI Provider & Model */}
      <section>
        <h2 className="text-lg font-semibold text-white mb-3">AI Provider & Model</h2>
        <p className="text-sm text-gray-500 mb-3">
          Email analysis requires a local text API provider. Configure screening and dedicated source overrides in <a href="/models/llms/abuse" className="text-port-accent underline">Abuse Guard</a>; those overrides take priority over the selections below.
        </p>
        <div className="space-y-3">
          {renderProviderSection(
            'Triage',
            'Classifies emails as reply/archive/delete/review with priority. A fast, cheap model works well here.',
            triage
          )}
          {renderProviderSection(
            'Reply Generation',
            'Generates draft email replies. A more capable model produces better responses.',
            reply
          )}
        </div>
      </section>

      <section>
        <h2 className="text-lg font-semibold text-white mb-3">Reply Tone</h2>
        <div className="p-4 bg-port-card rounded-lg border border-port-border">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-3 min-w-0">
              <User size={20} className={`shrink-0 ${config?.voiceMode ? 'text-port-accent-2' : 'text-gray-600'}`} />
              <div>
                <div className="text-sm font-medium text-white">Conversational tone</div>
                <div className="text-xs text-gray-500">
                  Draft replies in a natural, conversational tone without loading private identity documents.
                </div>
              </div>
            </div>
            <button
              onClick={() => { setConfig(prev => ({ ...prev, voiceMode: !prev.voiceMode })); setConfigDirty(true); }}
              className={`px-3 py-1.5 rounded text-xs font-medium transition-colors shrink-0 self-start sm:self-auto ${
                config?.voiceMode
                  ? 'bg-port-accent-2/20 text-port-accent-2'
                  : 'bg-gray-700 text-gray-400'
              }`}
            >
              {config?.voiceMode ? 'Enabled' : 'Disabled'}
            </button>
          </div>
        </div>
      </section>

      {/* Prompt Templates */}
      <section>
        <h2 className="text-lg font-semibold text-white mb-3">Prompt Templates</h2>
        <p className="text-sm text-gray-500 mb-3">
          Templates used when generating AI draft replies. Use {'{{variable}}'} syntax for substitution.
          Available: {'{{from}}'}, {'{{subject}}'}, {'{{body}}'}, {'{{instructions}}'}.
        </p>
        {configLoading ? (
          <RefreshCw size={16} className="text-port-accent animate-spin" />
        ) : (
          <div className="space-y-4">
            <FormField
              label="Reply Template"
              className="p-4 bg-port-card rounded-lg border border-port-border"
              labelClassName="block text-sm font-medium text-gray-300 mb-2"
            >
              <textarea
                value={config.replyTemplate}
                onChange={(e) => updateTemplate('replyTemplate', e.target.value)}
                rows={8}
                className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white font-mono placeholder-gray-500 focus:outline-none focus:border-port-accent resize-y"
              />
            </FormField>
            <div className="flex items-center gap-3">
              <button
                onClick={handleSaveConfig}
                disabled={!configDirty}
                className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg text-sm hover:bg-port-accent/80 transition-colors disabled:opacity-50"
              >
                <Save size={14} /> Save Config
              </button>
              {configDirty && <span className="text-xs text-port-warning">Unsaved changes</span>}
            </div>
          </div>
        )}
      </section>
    </div>
  );
}