import { useState, useCallback, useEffect, useRef } from 'react';
import type { DashboardData } from './types';
import { SMTP_PRESETS } from './data/smtp-presets';
import { Label } from './components/ui/label';
import { Switch } from './components/ui/switch';
import {
  RefreshCw,
  Send,
  Zap,
  Plus,
  CheckCircle2,
  Settings2,
  Clock as ClockIcon,
  Globe,
  Mail,
  ArrowRight,
  ArrowLeft,
  ShieldCheck,
  Tag,
  Hash,
  User,
  Lock,
  UserCircle,
  X,
  BookOpen,
  Terminal
} from 'lucide-react';
import { SearchableSelect } from './components/ui/searchable-select';
import {
  SettingsLayout,
  SettingsHeader,
  ModernCardHeader,
  SettingCard,
  AdminButton,
  SecondaryButton,
  GhostButton,
  SettingInput,
  MethodButton,
  StatusMessage,
  SaveWithStatus,
  SaveFooter,
  DeleteButton
} from './components/ui/settings-ui';
import { useSettingsSave } from './hooks/useSettingsSave';
import { Sheet, SheetContent } from './components/ui/sheet';






interface SMTPSettings {
  provider: string;
  host?: string;
  port?: number;
  encryption?: string;
  user?: string;
  pass?: string;
  from_email?: string;
  from_name?: string;
  auth?: number;
  api_key?: string;
  domain?: string;
  region?: string;
  access_key?: string;
  secret_key?: string;
}

interface SMTPAccount {
  id: number;
  account_name: string;
  provider: string;
  is_active: boolean;
  validated: boolean;
  config: SMTPSettings;
}

export default function SMTPSender({ data: dashboardData }: { data: DashboardData }) {
  const t = useCallback((key: string, fallback: string = ''): string => {
    const val = (dashboardData.smtpSenderData?.i18n as Record<string, unknown>)?.[key] || (dashboardData.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  }, [dashboardData.smtpSenderData?.i18n, dashboardData.i18n]);

  const PROVIDERS = [
    { id: 'wp', name: 'WordPress', iconPath: `${dashboardData?.global?.pluginUrl}assets/icons/wordpress.svg`, desc: t('wpProviderDesc', 'Default PHPMailer') },
    { id: 'smtp', name: 'Custom SMTP', iconPath: `${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`, desc: t('smtpProviderDesc', 'Any Mail Server') },
  ];

  const [accounts, setAccounts] = useState<SMTPAccount[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const editingIdRef = useRef<number | null>(null);
  const [currentStep, setCurrentStep] = useState(1);

  const [accountName, setAccountName] = useState('');
  const [isUserEditedName, setIsUserEditedName] = useState(false);

  const [settings, setSettings] = useState<SMTPSettings>({
    provider: 'smtp',
    host: '',
    port: 587,
    encryption: 'tls',
    user: '',
    pass: '',
    from_email: '',
    from_name: '',
    auth: 1,
    api_key: '',
    domain: '',
    region: 'us',
    access_key: '',
    secret_key: ''
  });

  const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
  const [testLog, setTestLog] = useState<string | null>(null);
  const [isTestingConnect, setIsTestingConnect] = useState(false);
  const [isTestingSend, setIsTestingSend] = useState(false);
  const [testEmail, setTestEmail] = useState('');
  const [presetSearch, setPresetSearch] = useState('');

  // Keep the mutable ref in sync with the state so the async save handler always reads the latest ID.
  useEffect(() => {
    editingIdRef.current = editingId;
  }, [editingId]);

  const { saveStatus, hasUnsavedChanges, isSaving, handleSave, markDirty } = useSettingsSave({
    onSave: async (silent = true) => {
      try {
        const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': dashboardData.global.wpRestNonce
          },
          body: JSON.stringify({
            account_name: accountName,
            provider: settings.provider,
            config: settings,
            id: editingIdRef.current
          })
        });

        const result = await response.json();
        if (result.success) {
          // If creating new, update the ref immediately so any queued auto-save targets the new row.
          if (!editingIdRef.current && (result.id || result.data?.id)) {
            const newId = result.id || result.data.id;
            editingIdRef.current = newId;
            setEditingId(newId);
          }
          fetchAccounts();
          // Only close dialog on explicit (manual) save, not on auto-save
          if (!silent) {
            setIsDialogOpen(false);
          }
          window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'smtp-sender' } }));
          return true;
        }
        setStatusMessage({ type: 'error', text: result.message || t('saveFailed', 'Save failed. Please check your settings and try again.') });
        return false;
      } catch {
        setStatusMessage({ type: 'error', text: t('errorOccurred', 'An error occurred.') });
        return false;
      }
    }
  });

  // Before unload warning
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges && isDialogOpen) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges, isDialogOpen]);

  const fetchAccounts = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp?_=${Date.now()}`, {
        headers: {
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      });
      const result = await response.json();
      if (result.success) {
        setAccounts(result.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch SMTP accounts:', error);
    }
    setIsLoading(false);
  }, [dashboardData.global.apiRestUrl, dashboardData.global.wpRestNonce]);

  const [prevData, setPrevData] = useState(dashboardData);
  if (dashboardData !== prevData) {
    setPrevData(dashboardData);
    fetchAccounts();
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      fetchAccounts();
    }, 0);
    return () => clearTimeout(timer);
  }, [fetchAccounts]);


  const handleInputChange = <K extends keyof SMTPSettings>(field: K, value: SMTPSettings[K]) => {
    setSettings(prev => {
      const next = { ...prev, [field]: value };
      // Auto-fill account name if user hasn't edited it manually
      if (field === 'provider' && !isUserEditedName) {
        const providerName = PROVIDERS.find(p => p.id === value)?.name || '';
        setAccountName(`${providerName} Sender`);
      }
      return next;
    });
    markDirty();
  };

  const openAddDialog = () => {
    setEditingId(null);
    editingIdRef.current = null;
    setAccountName('Custom SMTP Sender');
    setIsUserEditedName(false);
    setCurrentStep(1);
    setSettings({
      provider: 'smtp',
      host: '',
      port: 587,
      encryption: 'tls',
      user: '',
      pass: '',
      from_email: '',
      from_name: '',
      auth: 1,
      api_key: '',
      domain: '',
      region: 'us',
      access_key: '',
      secret_key: ''
    });
    setStatusMessage(null);
    setTestLog(null);
    setIsDialogOpen(true);
  };

  const openEditDialog = (account: SMTPAccount) => {
    setEditingId(account.id);
    editingIdRef.current = account.id;
    setAccountName(account.account_name);
    setIsUserEditedName(true);
    setCurrentStep(1);
    setSettings({
      ...account.config,
      provider: account.provider || 'smtp',
      pass: ''
    });
    setStatusMessage(null);
    setTestLog(null);
    setIsDialogOpen(true);
  };


  const deleteAccount = async (id: number) => {
    if (!confirm(t('deleteConfirm', 'Are you sure you want to delete this account?'))) return;
    try {
      const resp = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/${id}`, {
        method: 'DELETE',
        headers: {
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      });
      const result = await resp.json();
      if (result.success) {
        fetchAccounts();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'smtp-sender' } }));
      }
    } catch (error) {
      console.error('Failed to delete account:', error);
    }
  };

  const toggleAccount = async (id: number, active: boolean) => {
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/${id}/toggle`, {
        method: 'POST',
        headers: {
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({ active })
      });
      const result = await response.json();
      if (result.success) {
        fetchAccounts();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'smtp-sender' } }));
      }
    } catch (error) {
      console.error('Failed to toggle account:', error);
    }
  };

  const testConnection = async () => {
    setIsTestingConnect(true);
    setStatusMessage(null);
    setTestLog(null);
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/validate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          provider: settings.provider,
          config: { ...settings, id: editingIdRef.current }
        })
      });

      const result = await response.json();
      if (result.success) {
        setStatusMessage({ type: 'success', text: result.message || result.data?.message || t('connectionSuccessful', 'Connection successful!') });
        setTestLog(result.log || null);
        if (editingIdRef.current) fetchAccounts();
      } else {
        const errorText = result.message || (typeof result.data === 'string' ? result.data : result.data?.message) || t('connectionFailed', 'Connection failed.');
        setStatusMessage({ type: 'error', text: errorText });
        setTestLog(result.log || null);
      }
    } catch {
      setStatusMessage({ type: 'error', text: t('errorDuringTest', 'An error occurred during test.') });
    }
    setIsTestingConnect(false);
  };

  const sendTestEmail = async () => {
    if (!testEmail) {
      setStatusMessage({ type: 'error', text: t('enterTestEmail', 'Please enter a test email address.') });
      return;
    }
    setIsTestingSend(true);
    setStatusMessage(null);
    setTestLog(null);
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          to: testEmail,
          id: editingIdRef.current,
          config: settings
        })
      });

      const result = await response.json();
      if (result.success) {
        setStatusMessage({ type: 'success', text: result.message || result.data || t('testEmailSent', 'Test email sent successfully.') });
      } else {
        const errorText = typeof result.data === 'string' ? result.data : (result.data?.message || result.message || t('failedSendTestEmail', 'Failed to send test email.'));
        setStatusMessage({ type: 'error', text: errorText });
      }
    } catch {
      setStatusMessage({ type: 'error', text: t('errorOccurred', 'An error occurred.') });
    }
    setIsTestingSend(false);
  };

  const nextStep = () => setCurrentStep(prev => prev + 1);
  const prevStep = () => setCurrentStep(prev => prev - 1);

  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-6 animate-in fade-in duration-500 pb-12">

        {/* Header */}
        <SettingsHeader
          title={t('title', 'SMTP Mail Server')}
          description={t('subtitle', 'Route system emails through your own private mail server. Support multiple accounts.')}
          backUrl="admin.php?page=wawp&wawp_section=senders"
          className="mb-8"
        >
          <div className="flex items-center gap-2.5">
            <AdminButton onClick={openAddDialog} icon={Plus}>
              {t('addAccount', 'Add Account')}
            </AdminButton>
            <SecondaryButton
              size="icon"
              className="bg-white border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/dbtn shrink-0"
              onClick={() => window.open(`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-setup-smtp-email`, '_blank')}
              title={dashboardData?.rtl ? 'دليل إعداد بريد SMTP' : 'SMTP Setup Guide'}
            >
              <BookOpen className="w-4 h-4 text-slate-500 group-hover/dbtn:text-[#004449] transition-colors" strokeWidth={2} />
            </SecondaryButton>
          </div>
        </SettingsHeader>

        {/* Accounts Table */}
        <SettingCard className="p-0 overflow-hidden border-slate-100 bg-white">
          <ModernCardHeader
            iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`}
            title={t('smtpAccounts', 'SMTP Accounts')}
            description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">{t('smtpAccountsDesc', 'Manage configurations and validation status')}</span>}
          />
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-y border-slate-100 bg-slate-50/50">
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">{t('defaultSender', 'Default Sender')}</th>
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">{t('accountName', 'Account Name')}</th>
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">{t('provider', 'Provider')}</th>
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">{t('serverStatus', 'Server Status')}</th>
                  <th className="px-6 py-4 text-center text-[10px] font-bold uppercase tracking-widest text-slate-400">{t('actions', 'Actions')}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {isLoading ? (
                  null
                ) : accounts.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-6 py-12 text-center text-slate-400 text-sm italic">{t('noAccountsConfigured', 'No accounts configured yet.')}</td>
                  </tr>
                ) : accounts.map((account) => (
                  <tr key={account.id} className="hover:bg-slate-50/50 transition-colors group">
                    <td className="px-6 py-4">
                      {account.is_active ? (
                        <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-600 text-white text-[10px] font-bold uppercase tracking-widest">
                          <ShieldCheck className="w-3 h-3" /> {t('selected', 'Selected')}
                        </span>
                      ) : (
                        <GhostButton
                          onClick={() => toggleAccount(account.id, true)}
                          className="h-7 px-3 text-[10px] font-bold uppercase tracking-widest text-slate-400 hover:text-[#004449] hover:bg-slate-100"
                        >
                          {t('setDefault', 'Set Default')}
                        </GhostButton>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex flex-col">
                        <span className="text-sm font-bold text-slate-700">{account.account_name}</span>
                        {account.provider === 'smtp' && (
                          <span className="text-[10px] font-medium text-slate-400 font-mono mt-0.5">{account.config?.host}:{account.config?.port}</span>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        {(() => {
                          let name = '';
                          let iconSrc = '';

                          if (account.provider === 'wp') {
                            const p = PROVIDERS.find(pr => pr.id === 'wp');
                            name = p?.name || 'WordPress';
                            iconSrc = p?.iconPath || '';
                          } else {
                            const matchedPreset = SMTP_PRESETS.find(
                              preset => preset.host === account.config?.host && Number(preset.port) === Number(account.config?.port)
                            );
                            if (matchedPreset) {
                              name = matchedPreset.name;
                              iconSrc = `${dashboardData?.global?.pluginUrl}${matchedPreset.iconFile}`;
                            } else {
                              const p = PROVIDERS.find(pr => pr.id === 'smtp');
                              name = p?.name || 'Custom SMTP';
                              iconSrc = p?.iconPath || '';
                            }
                          }

                          return (
                            <>
                              <div className="w-6 h-6 rounded bg-slate-50 border border-slate-100 flex items-center justify-center shrink-0">
                                {iconSrc ? (
                                  <img
                                    src={iconSrc}
                                    className="w-3.5 h-3.5 object-contain"
                                    alt={name}
                                    onError={(e) => {
                                      (e.target as HTMLImageElement).style.display = 'none';
                                    }}
                                  />
                                ) : (
                                  <Globe className="w-3.5 h-3.5 text-slate-400" />
                                )}
                              </div>
                              <span className="text-xs font-bold text-slate-600 uppercase tracking-wide">
                                {name}
                              </span>
                            </>
                          );
                        })()}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      {account.validated ? (
                        <span className="inline-flex items-center gap-1.5 text-emerald-600 text-[10px] font-bold uppercase tracking-widest">
                          <CheckCircle2 className="w-3.5 h-3.5" /> {t('active', 'Active')}
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 text-amber-500 text-[10px] font-bold uppercase tracking-widest">
                          <ClockIcon className="w-3.5 h-3.5" /> {t('pendingSetup', 'Pending Setup')}
                        </span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-center">
                      <div className="flex items-center justify-center gap-2 opacity-100">
                        <SecondaryButton onClick={() => openEditDialog(account)} className="h-8 px-3 text-[10px] font-bold uppercase tracking-widest text-blue-600 border-blue-100 hover:bg-blue-50 rounded-[4px]" icon={Settings2}>
                          {t('editAndTest', 'Edit & Test')}
                        </SecondaryButton>
                        <DeleteButton
                          onClick={() => deleteAccount(account.id)}
                          size="sm"
                        />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </SettingCard>

        {/* Dialog: 3-Step Wizard */}
        <Sheet open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <SheetContent side="right" className="w-full lg:max-w-[calc(100%-280px)] xl:max-w-[1200px] p-0 overflow-hidden border-none flex flex-col h-full">

            <div className="bg-slate-50 border-b border-slate-100 sticky top-0 z-10">
              <ModernCardHeader
                title={editingId ? t('editAccount', 'Edit Account') : t('connectNewMailServer', 'Connect New Mail Server')}
                description={
                  <div className="text-[10px] font-bold uppercase tracking-widest">
                    <span className="text-[#004449]">Step {currentStep} of 3</span> — {currentStep === 1 ? t('chooseDeliveryMethod', 'Choose Delivery Method') : currentStep === 2 ? t('configureCredentials', 'Configure Credentials') : t('diagnosticCheck', 'Diagnostic Check')}
                  </div>
                }
                iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`}
                rightAction={
                  <GhostButton
                    onClick={() => setIsDialogOpen(false)}
                    size="icon-sm"
                    className="text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full"
                    icon={X}
                  >
                    {null}
                  </GhostButton>
                }
              />
              {/* Progress Bar Container */}
              <div className="h-1 bg-slate-200 w-full overflow-hidden">
                <div
                  className="h-full bg-[#004449] transition-all duration-700 ease-in-out"
                  style={{ width: `${(currentStep / 3) * 100}%` }}
                />
              </div>
            </div>

            <div className="flex-1 overflow-y-auto bg-white">
              <div className="p-8 max-w-6xl mx-auto space-y-12">
                {statusMessage && (
                  <div className={`p-4 rounded-xl border flex items-start gap-3 text-sm font-bold animate-in zoom-in duration-300 ${statusMessage.type === 'success' ? 'bg-emerald-50 border-emerald-100 text-emerald-700' : 'bg-rose-50 border-rose-100 text-rose-700'}`}>
                    {statusMessage.type === 'success' ? <CheckCircle2 className="w-5 h-5 mt-0.5 shrink-0" /> : <ShieldCheck className="w-5 h-5 mt-0.5 shrink-0" />}
                    <span className="whitespace-pre-wrap leading-relaxed flex-1">
                      {typeof statusMessage.text === 'string' ? statusMessage.text : JSON.stringify(statusMessage.text)}
                    </span>
                    <button onClick={() => setStatusMessage(null)}><X className="w-4 h-4 opacity-50" /></button>
                  </div>
                )}

                {testLog && (
                  <div className="rounded-xl border border-slate-800 bg-slate-950 text-slate-100 p-4 font-mono text-[11px] overflow-hidden animate-in zoom-in duration-300">
                    <div className="flex items-center justify-between mb-2 text-slate-400 uppercase text-[10px] font-bold tracking-widest">
                      <span className="flex items-center gap-1.5"><Terminal className="w-3.5 h-3.5" /> {t('serverLog', 'Server Log')}</span>
                      <button onClick={() => setTestLog(null)} className="hover:text-white transition-colors"><X className="w-3.5 h-3.5" /></button>
                    </div>
                    <pre className="whitespace-pre-wrap break-all leading-relaxed max-h-80 overflow-y-auto">{testLog}</pre>
                  </div>
                )}

                {/* STEP 1: CHOOSE SENDER */}
                {currentStep === 1 && (
                  <div className="space-y-10 animate-in fade-in slide-in-from-right-8 duration-500 ease-out">
                    <div className="space-y-4">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                        <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">{t('providerSelection', 'Provider Selection')}</span>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {PROVIDERS.map((p) => (
                          <MethodButton
                            key={p.id}
                            active={settings.provider === p.id}
                            onClick={() => handleInputChange('provider', p.id)}
                            label={p.name}
                            description={p.desc}
                            iconPath={p.iconPath}
                            activeStyles="bg-white border-[#004449] ring-4 ring-[#004449]/5"
                          />
                        ))}
                      </div>
                      <div className="mt-4">
                        <StatusMessage
                          type={settings.provider === 'wp' ? 'active' : 'inactive'}
                          message={settings.provider === 'wp'
                            ? t('wpMailerDesc', 'Using the default WordPress mailer. Simple and reliable, but subject to hosting limitations.')
                            : t('customMailerDesc', 'Using a custom mail server. This allows for higher delivery rates and professional branding.')}
                        />
                      </div>
                    </div>

                    <div className="space-y-4 pt-4">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                        <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">{t('management', 'Management')}</span>
                      </div>
                      <div className="space-y-2">
                        <SettingInput
                          label={t('accountFriendlyName', 'Account Friendly Name')}
                          value={accountName}
                          onChange={(val) => {
                            setAccountName(val);
                            setIsUserEditedName(true);
                          }}
                          placeholder={t('accountFriendlyNamePlaceholder', 'e.g. Sales Team SMTP')}
                          icon={Tag}
                        />
                        <p className="text-[10px] text-slate-400 font-medium italic">{t('accountFriendlyNameDesc', 'This name is only for your reference in the dashboard.')}</p>
                      </div>
                    </div>
                  </div>
                )}

                {/* STEP 2: CONFIGURATION */}
                {currentStep === 2 && (
                  <div className="space-y-6 animate-in fade-in slide-in-from-right-8 duration-500 ease-out">

                    {/* ─── Provider Preset Picker (Custom SMTP only) ─── */}
                    {settings.provider === 'smtp' && (() => {
                      const CATS: Record<string, string> = {
                        popular: t('catPopular', 'Popular'),
                        transactional: t('catTransactional', 'Transactional'),
                        hosting: t('catHosting', 'Hosting'),
                        enterprise: t('catEnterprise', 'Enterprise'),
                        regional: t('catRegional', 'Regional / ISP')
                      };
                      const q = presetSearch;
                      const filtered = SMTP_PRESETS.filter(p => !q || p.name.toLowerCase().includes(q.toLowerCase()) || p.host.toLowerCase().includes(q.toLowerCase()));
                      const activePreset = SMTP_PRESETS.find(p => settings.host === p.host && Number(settings.port) === p.port);
                      return (
                        <SettingCard className="p-0 overflow-hidden border-slate-100 bg-white">
                          <ModernCardHeader
                            icon={Zap}
                            title={t('quickFillFromPreset', 'Quick-fill from a known provider')}
                            description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">{SMTP_PRESETS.length} {t('providersCountLabel', 'Providers')}</span>}
                          />
                          <div className="p-5 space-y-3">
                            <input
                              type="text"
                              placeholder={t('searchProvidersPlaceholder', 'Search providers... (e.g. Gmail, Hostinger, SendGrid)')}
                              value={q}
                              onChange={(e) => setPresetSearch(e.target.value)}
                              className="w-full !h-8 px-3.5 rounded-[5px] border border-slate-200 bg-white text-xs font-medium text-slate-700 placeholder:text-slate-300 focus:ring-1 focus:ring-[#004449]/30 focus:border-[#004449]/30 outline-none transition-all"
                            />
                            <div className="max-h-[220px] overflow-y-auto rounded-[5px] border border-slate-100 bg-slate-50/30 p-3 space-y-4">
                              {Object.entries(CATS).map(([catKey, catLabel]) => {
                                const items = filtered.filter(p => p.category === catKey);
                                if (items.length === 0) return null;
                                return (
                                  <div key={catKey}>
                                    <div className="text-[9px] font-black uppercase tracking-[0.2em] text-slate-300 mb-2 pl-1">{catLabel}</div>
                                    <div className="grid gap-1.5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))' }}>
                                      {items.map((preset) => {
                                        const isActive = settings.host === preset.host && Number(settings.port) === preset.port;
                                        return (
                                          <button
                                            key={preset.id}
                                            type="button"
                                            onClick={() => {
                                              handleInputChange('host', preset.host);
                                              handleInputChange('port', preset.port);
                                              handleInputChange('encryption', preset.encryption);
                                              handleInputChange('auth', preset.auth);
                                            }}
                                            title={preset.hint || preset.name}
                                            className={`flex items-center gap-2 px-2.5 py-2 rounded-[5px] border text-left transition-all text-[11px] font-bold ${isActive
                                              ? 'bg-[#004449]/5 border-[#004449]/30 text-[#004449] ring-1 ring-[#004449]/20'
                                              : 'bg-white border-slate-200/80 text-slate-600 hover:border-slate-300 hover:bg-white'
                                              }`}
                                          >
                                            <img
                                              src={`${dashboardData?.global?.pluginUrl}${preset.iconFile}`}
                                              className="w-3.5 h-3.5 object-contain shrink-0"
                                              alt=""
                                              onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                                            />
                                            <span className="truncate">{preset.name}</span>
                                          </button>
                                        );
                                      })}
                                    </div>
                                  </div>
                                );
                              })}
                              {filtered.length === 0 && (
                                <p className="text-center text-xs text-slate-400 py-6">{t('noProvidersMatch', 'No providers match your search.')}</p>
                              )}
                            </div>
                            {activePreset?.hint && (
                              <p className="text-[10px] text-amber-700 bg-amber-50 border border-amber-100 rounded-[5px] px-3 py-2 font-medium">
                                💡 {activePreset.hint}
                              </p>
                            )}
                          </div>
                        </SettingCard>
                      );
                    })()}

                    {/* ─── Connection Credentials ─── */}
                    <SettingCard className="p-0 overflow-hidden border-slate-100 bg-white">
                      <ModernCardHeader
                        iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`}
                        title={`${t('connectionCredentialsFor', 'Connection Credentials for')} ${PROVIDERS.find(p => p.id === settings.provider)?.name}`}
                        description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">{t('configureCredentials', 'Configure Credentials')}</span>}
                      />
                      <div className="p-6">
                        {settings.provider === 'wp' ? (
                          <div className="rounded-lg bg-blue-50 border border-blue-200/60 flex items-center gap-4 px-5 py-4">
                            <div className="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center shrink-0">
                              <img src={`${dashboardData?.global?.pluginUrl}assets/icons/wordpress.svg`} className="w-5 h-5 object-contain" alt="" />
                            </div>
                            <div>
                              <h4 className="font-bold text-blue-950 text-sm">{t('systemIntegrationReady', 'System Integration Ready')}</h4>
                              <p className="text-xs text-blue-700/80 font-medium mt-0.5">
                                {t('systemIntegrationReadyDesc', "Wawp will use your server's default mailer. Ensure your hosting provider supports PHPMailer or has sendmail configured.")}
                              </p>
                            </div>
                          </div>
                        ) : (
                          <div className="space-y-5">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5">
                              <SettingInput
                                label={t('smtpHost', 'SMTP Host')}
                                value={settings.host || ''}
                                onChange={(val) => handleInputChange('host', val)}
                                placeholder="smtp.gmail.com"
                                icon={Globe}
                              />
                              <SettingInput
                                label={t('port', 'Port')}
                                type="number"
                                value={String(settings.port || '')}
                                onChange={(val) => handleInputChange('port', Number(val))}
                                placeholder="587"
                                icon={Hash}
                              />
                              <div className="space-y-2">
                                <Label className="text-xs font-bold text-slate-700 uppercase tracking-widest">{t('encryption', 'Encryption')}</Label>
                                <SearchableSelect
                                  options={[
                                    { value: "none", label: "None" },
                                    { value: "ssl", label: "SSL" },
                                    { value: "tls", label: "TLS" }
                                  ]}
                                  value={settings.encryption || "tls"}
                                  onChange={(v) => handleInputChange('encryption', v)}
                                  className="h-8 bg-white border-slate-200 text-slate-700 font-bold text-[12px] hover:border-[#004449]/30 transition-all rounded-[5px]"
                                />
                              </div>
                              <div className="space-y-2">
                                <Label className="text-xs font-bold text-slate-700 uppercase tracking-widest">{t('authentication', 'Authentication')}</Label>
                                <div className="flex items-center justify-between px-4 bg-white border border-slate-200 rounded-lg h-8">
                                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">{t('loginRequired', 'Login Required')}</span>
                                  <Switch checked={!!settings.auth} onCheckedChange={(c) => handleInputChange('auth', c ? 1 : 0)} />
                                </div>
                              </div>
                            </div>

                            {!!settings.auth && (
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 pt-4 border-t border-slate-100">
                                <SettingInput
                                  label={t('username', 'Username')}
                                  value={settings.user || ''}
                                  onChange={(val) => handleInputChange('user', val)}
                                  placeholder="user@example.com"
                                  icon={User}
                                />
                                <SettingInput
                                  label={t('password', 'Password')}
                                  type="password"
                                  value={settings.pass || ''}
                                  onChange={(val) => handleInputChange('pass', val)}
                                  placeholder="••••••••"
                                  icon={Lock}
                                />
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                      {/* Status bar inside card footer */}
                      <div className="px-6 pb-4">
                        <StatusMessage
                          type={(settings.provider === 'wp' || (settings.host && settings.port)) ? 'active' : 'error'}
                          message={(settings.provider === 'wp' || (settings.host && settings.port))
                            ? t('serverConfigured', 'Server connection details are configured. You can proceed to test the delivery.')
                            : t('serverMissing', 'Connection details missing. Please enter your SMTP host and port to continue.')}
                        />
                      </div>
                    </SettingCard>

                    {/* ─── Public Identity (From) ─── */}
                    <SettingCard className="p-0 overflow-hidden border-slate-100 bg-white">
                      <ModernCardHeader
                        icon={UserCircle}
                        title={t('publicIdentity', 'Public Identity')}
                        description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">{t('fromEmail', 'From Email')} &amp; {t('fromName', 'From Name')}</span>}
                      />
                      <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5">
                        <SettingInput
                          label={t('fromEmail', 'From Email')}
                          type="email"
                          value={settings.from_email || ''}
                          onChange={(val) => handleInputChange('from_email', val)}
                          placeholder="site@wawp.net"
                          icon={Mail}
                        />
                        <SettingInput
                          label={t('fromName', 'From Name')}
                          value={settings.from_name || ''}
                          onChange={(val) => handleInputChange('from_name', val)}
                          placeholder="Wawp Support"
                          icon={UserCircle}
                        />
                      </div>
                    </SettingCard>

                  </div>
                )}

                {/* STEP 3: TEST */}
                {currentStep === 3 && (
                  <div className="space-y-5 animate-in fade-in slide-in-from-right-8 duration-500 ease-out">

                    {/* Two action cards side by side */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">

                      {/* Connection Check Card */}
                      <SettingCard className="p-0 overflow-hidden border-slate-100 bg-white flex flex-col">
                        <ModernCardHeader
                          icon={Globe}
                          title={t('serverIntegration', 'Server Integration')}
                          description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">{t('verificationAndTestingDesc', 'Validate Endpoint Sync')}</span>}
                        />
                        <div className="p-6 flex flex-col flex-1 gap-4">
                          <p className="text-[12px] font-medium text-slate-500 leading-relaxed flex-1">
                            {t('serverIntegrationDesc', 'Verify that the plugin can successfully connect to your SMTP server using the provided credentials.')}
                          </p>
                          <AdminButton
                            onClick={testConnection}
                            disabled={isTestingConnect}
                            className="w-full bg-slate-900 hover:bg-black uppercase tracking-widest"
                            icon={isTestingConnect ? RefreshCw : ShieldCheck}
                            loading={isTestingConnect}
                          >
                            {t('runServerCheck', 'Run Server Check')}
                          </AdminButton>
                        </div>
                      </SettingCard>

                      {/* Direct Mail Test Card */}
                      <SettingCard className="p-0 overflow-hidden border-slate-100 bg-white flex flex-col">
                        <ModernCardHeader
                          icon={Send}
                          title={t('directMailTest', 'Direct Mail Test')}
                          description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">{t('testEmailAddress', 'Test Email Address')}</span>}
                        />
                        <div className="p-6 flex flex-col flex-1 gap-4">
                          <p className="text-[12px] font-medium text-slate-500 leading-relaxed flex-1">
                            {t('directMailTestDesc', 'Send a physical test email to ensure messages are routed and delivered correctly without ending up in spam.')}
                          </p>
                          <div className="flex gap-2 items-end">
                            <SettingInput
                              label={t('testEmailAddress', 'Test Email Address')}
                              value={testEmail}
                              onChange={(val) => setTestEmail(val)}
                              placeholder="to@example.com"
                              icon={Mail}
                              className="flex-1"
                            />
                            <AdminButton
                              onClick={sendTestEmail}
                              disabled={isTestingSend}
                              size="icon"
                              className="shrink-0 mb-0.5"
                              icon={isTestingSend ? RefreshCw : Send}
                              loading={isTestingSend}
                            />
                          </div>
                        </div>
                      </SettingCard>

                    </div>

                    {/* Note bar */}
                    <div className="flex items-start gap-3 px-5 py-4 rounded-xl bg-amber-50 border border-amber-100">
                      <div className="w-8 h-8 rounded-lg bg-amber-100 flex items-center justify-center shrink-0">
                        <Zap className="w-4 h-4 text-amber-600" />
                      </div>
                      <div>
                        <p className="text-[11px] font-black text-amber-800 uppercase tracking-widest !m-0">{t('configurationNote', 'Configuration Note')}</p>
                        <p className="text-[11px] text-amber-700/80 leading-relaxed font-medium">
                          {t('configurationNoteDesc', 'It is highly recommended to perform a successful test before finalizing. Accounts with a failed test will remain in "Pending" status and might not route emails correctly.')}
                        </p>
                      </div>
                    </div>

                  </div>
                )}
              </div>
            </div>
            <div className="p-6 bg-slate-50 border-t border-slate-100 sticky bottom-0 z-10 flex flex-row gap-3">

              {currentStep > 1 && (
                <GhostButton onClick={prevStep} className="flex-1 rounded-lg font-bold text-slate-500 hover:bg-white active:scale-95 transition-all text-xs uppercase tracking-widest border border-transparent hover:border-slate-200" icon={ArrowLeft}>
                  {t('back', 'Back')}
                </GhostButton>
              )}

              {currentStep < 3 && (
                <AdminButton onClick={nextStep} className="flex-[2] text-xs uppercase tracking-[0.15em]">
                  {t('continueSetup', 'Continue Setup')}
                  <ArrowRight className="w-3.5 h-3.5 ml-2" />
                </AdminButton>
              )}

              <SaveWithStatus
                saveStatus={saveStatus}
                hasUnsavedChanges={hasUnsavedChanges}
                isSaving={isSaving}
                onSave={() => handleSave(false)}
              />
            </div>
          </SheetContent>
        </Sheet>
      </div>

      <SaveFooter
        saveStatus={saveStatus}
        hasUnsavedChanges={hasUnsavedChanges}
        isSaving={isSaving}
        onSave={() => handleSave(false)}
        docsUrl={`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-setup-smtp-email`}
        docsTitle={dashboardData?.rtl ? "كيفية إعداد بريد SMTP" : "How to Setup SMTP Email"}
      />
    </SettingsLayout>
  );
}
