"use client";

import { useState, useEffect } from "react";
import {
  Settings, Mail, Server, Globe, Plus, Pencil, Trash2,
  Wifi, RefreshCw, Eye, EyeOff,
  CheckCircle, XCircle, AlertTriangle, X, Activity,
  Power, PowerOff, Info, Clock, Zap, ChevronRight,
  MapPin, Users, Crown, ShieldCheck,
} from "lucide-react";
import { useTranslations, useLocale } from "next-intl";
import {
  getMailImapConfig, saveMailImapConfig, testMailImapConfig, pollMailNow,
  getMailCronStatus,
  listMailSources, createMailSource, updateMailSource, deleteMailSource, toggleMailSource,
  type MailInboxConfig, type MailSource, type MailImapPayload, type CronStatus,
} from "@/src/lib/api/mail-config";
import {
  listTenantCountries, createTenantCountry, updateTenantCountry, deleteTenantCountry,
  setCountryManager, type TenantCountry,
} from "@/src/lib/api/countries";
import { listTenantUsers, type TenantUser } from "@/src/lib/api/tenant-users";
import { COUNTRIES } from "@/src/lib/constants/countries";

const NAVY = "#1e1b4b";
const NAVY2 = "#312e81";
const TEAL = "#4dba96";

function cx(...cls: (string | boolean | undefined | null)[]) {
  return cls.filter(Boolean).join(" ");
}

const inputCls =
  "w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 " +
  "focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition placeholder:text-slate-400";

function Field({
  label, required, error, hint, children, full,
}: {
  label: string; required?: boolean; error?: string; hint?: string;
  children: React.ReactNode; full?: boolean;
}) {
  return (
    <div className={cx("flex flex-col gap-1.5", full && "col-span-2")}>
      <label className="text-xs font-semibold text-slate-500 uppercase tracking-wide">
        {label}{required && <span className="text-red-500 ml-0.5">*</span>}
      </label>
      {children}
      {hint && !error && <p className="text-xs text-slate-400">{hint}</p>}
      {error && <p className="text-xs text-red-500">{error}</p>}
    </div>
  );
}

// ─── Source type badge ────────────────────────────────────────────────────────
function SourceTypeBadge({ isDomain }: { isDomain: boolean }) {
  const t = useTranslations("settings");
  return isDomain ? (
    <span className="inline-flex items-center gap-1 text-xs bg-violet-50 text-violet-600 border border-violet-200 px-2 py-0.5 rounded-full font-medium">
      <Globe size={10} /> {t("badge_domain")}
    </span>
  ) : (
    <span className="inline-flex items-center gap-1 text-xs bg-sky-50 text-sky-600 border border-sky-200 px-2 py-0.5 rounded-full font-medium">
      <Mail size={10} /> {t("badge_email")}
    </span>
  );
}

// ─── Modal Source ─────────────────────────────────────────────────────────────
type SourceForm = { client_name: string; email_or_domain: string; notes: string; is_active: boolean };

function SourceModal({
  initial, onSave, onClose, loading, error,
}: {
  initial?: MailSource | null; onSave: (d: SourceForm) => void;
  onClose: () => void; loading: boolean; error?: string;
}) {
  const t = useTranslations("settings");
  const tc = useTranslations("common");
  const [form, setForm] = useState<SourceForm>({
    client_name: initial?.client_name ?? "",
    email_or_domain: initial?.email_or_domain ?? "",
    notes: initial?.notes ?? "",
    is_active: initial?.is_active ?? true,
  });
  const set = (k: keyof SourceForm) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setForm((f) => ({ ...f, [k]: e.target.value }));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
          <div>
            <h2 className="font-bold text-slate-800">{initial ? t("edit_source") : t("new_source")}</h2>
            <p className="text-xs text-slate-500 mt-0.5">{t("source_modal_subtitle")}</p>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition">
            <X size={16} />
          </button>
        </div>
        <div className="px-6 py-5 space-y-4">
          {error && (
            <div className="flex items-center gap-2 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5">
              <XCircle size={14} className="flex-shrink-0" /> {error}
            </div>
          )}
          <Field label={t("label_client_name")}>
            <input className={inputCls} value={form.client_name} onChange={set("client_name")} placeholder="ex: Acremac SA" />
          </Field>
          <Field label={t("label_address_domain")} required hint={t("hint_address_domain")}>
            <input
              className={cx(inputCls, initial && "opacity-60 cursor-not-allowed")}
              value={form.email_or_domain}
              onChange={set("email_or_domain")}
              placeholder="ex: acremac.com  ou  john@acremac.com"
              disabled={!!initial}
            />
          </Field>
          <Field label={t("label_notes")}>
            <textarea className={cx(inputCls, "resize-none")} rows={2} value={form.notes} onChange={set("notes")} placeholder={t("placeholder_notes")} />
          </Field>
          <label className="flex items-center gap-3 cursor-pointer select-none py-1">
            <div
              onClick={() => setForm((f) => ({ ...f, is_active: !f.is_active }))}
              className={cx(
                "w-10 h-5.5 rounded-full relative transition-colors flex-shrink-0",
                form.is_active ? "bg-indigo-600" : "bg-slate-300"
              )}
              style={{ height: "22px", width: "40px" }}
            >
              <span
                className={cx(
                  "absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-all",
                  form.is_active ? "left-5" : "left-0.5"
                )}
              />
            </div>
            <span className="text-sm text-slate-700 font-medium">{t("source_active")}</span>
          </label>
        </div>
        <div className="flex justify-end gap-3 px-6 py-4 border-t border-slate-100 bg-slate-50 rounded-b-2xl">
          <button onClick={onClose} className="px-4 py-2 rounded-lg border border-slate-200 text-sm text-slate-600 hover:bg-white transition">
            {tc("cancel")}
          </button>
          <button
            onClick={() => onSave(form)}
            disabled={loading || !form.email_or_domain.trim()}
            className="flex items-center gap-1.5 px-5 py-2 rounded-lg text-sm font-semibold text-white transition disabled:opacity-50"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            {loading
              ? <><RefreshCw size={13} className="animate-spin" /> {t("saving_source")}</>
              : initial ? t("update_source_btn") : t("add_source_btn")}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Onglet Sources ───────────────────────────────────────────────────────────
function SourcesTab() {
  const t = useTranslations("settings");
  const tc = useTranslations("common");
  const [sources, setSources] = useState<MailSource[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<{ open: boolean; item: MailSource | null }>({ open: false, item: null });
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState("");
  const [deleteId, setDeleteId] = useState<number | null>(null);

  useEffect(() => { listMailSources().then(setSources).finally(() => setLoading(false)); }, []);

  const openCreate = () => { setSaveError(""); setModal({ open: true, item: null }); };
  const openEdit = (s: MailSource) => { setSaveError(""); setModal({ open: true, item: s }); };
  const closeModal = () => setModal({ open: false, item: null });

  const handleSave = async (data: SourceForm) => {
    setSaving(true); setSaveError("");
    try {
      if (modal.item) {
        const u = await updateMailSource(modal.item.id, data);
        setSources((p) => p.map((s) => (s.id === u.id ? u : s)));
      } else {
        const c = await createMailSource(data);
        setSources((p) => [c, ...p]);
      }
      closeModal();
    } catch (e: any) { setSaveError(e?.detail || "Erreur."); }
    finally { setSaving(false); }
  };

  const handleToggle = async (s: MailSource) => {
    try {
      const u = await toggleMailSource(s.id);
      setSources((p) => p.map((x) => (x.id === u.id ? u : x)));
    } catch { /* ignore */ }
  };

  const handleDelete = async (id: number) => {
    try { await deleteMailSource(id); setSources((p) => p.filter((s) => s.id !== id)); }
    finally { setDeleteId(null); }
  };

  const plural = (n: number) => (n > 1 ? "s" : "");

  return (
    <div className="flex flex-col h-full">
      <div className="flex items-start justify-between mb-6">
        <div>
          <h2 className="text-lg font-bold text-slate-800">{t("sources_title")}</h2>
          <p className="text-sm text-slate-500 mt-1">{t("sources_desc")}</p>
        </div>
        <button
          onClick={openCreate}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold text-white shadow-sm hover:shadow transition-all flex-shrink-0 ml-4"
          style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
        >
          <Plus size={15} /> {t("add_source")}
        </button>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-6">
        <div className="flex items-start gap-3 bg-violet-50 border border-violet-100 rounded-xl p-4">
          <Globe size={18} className="text-violet-500 flex-shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-semibold text-violet-800">{t("domain_type_title")}</p>
            <p className="text-xs text-violet-600 mt-0.5">{t("domain_type_desc")}</p>
          </div>
        </div>
        <div className="flex items-start gap-3 bg-sky-50 border border-sky-100 rounded-xl p-4">
          <Mail size={18} className="text-sky-500 flex-shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-semibold text-sky-800">{t("email_type_title")}</p>
            <p className="text-xs text-sky-600 mt-0.5">{t("email_type_desc")}</p>
          </div>
        </div>
      </div>

      {loading ? (
        <div className="flex-1 flex items-center justify-center text-slate-400">
          <RefreshCw size={20} className="animate-spin mr-2" /> {tc("loading")}
        </div>
      ) : sources.length === 0 ? (
        <div className="flex-1 flex flex-col items-center justify-center text-center py-12 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50/50">
          <div className="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
            <Mail size={28} className="text-slate-300" />
          </div>
          <p className="text-base font-semibold text-slate-600">{t("no_sources")}</p>
          <p className="text-sm text-slate-400 mt-1 max-w-xs">{t("no_sources_desc")}</p>
          <button
            onClick={openCreate}
            className="mt-5 flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-semibold text-white"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            <Plus size={14} /> {t("add_first_source")}
          </button>
        </div>
      ) : (
        <div className="flex-1 rounded-2xl border border-slate-200 overflow-hidden bg-white shadow-sm">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-200">
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_client")}</th>
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_address_domain")}</th>
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_type")}</th>
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_status")}</th>
                <th className="w-32" />
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {sources.map((s) => (
                <tr key={s.id} className="hover:bg-slate-50/70 transition group">
                  <td className="px-5 py-3.5">
                    <span className="font-semibold text-slate-800">
                      {s.client_name || <span className="text-slate-400 italic font-normal">{t("unnamed")}</span>}
                    </span>
                    {s.notes && <p className="text-xs text-slate-400 mt-0.5 truncate max-w-[200px]">{s.notes}</p>}
                  </td>
                  <td className="px-5 py-3.5">
                    <code className="text-xs bg-slate-100 text-slate-700 px-2 py-1 rounded-md font-mono">{s.email_or_domain}</code>
                  </td>
                  <td className="px-5 py-3.5"><SourceTypeBadge isDomain={s.is_domain} /></td>
                  <td className="px-5 py-3.5">
                    <button onClick={() => handleToggle(s)} className="flex items-center gap-2 text-xs transition group/toggle">
                      <div
                        className={cx("w-8 h-4 rounded-full relative transition-colors", s.is_active ? "bg-indigo-500" : "bg-slate-300")}
                        style={{ height: "18px", width: "32px" }}
                      >
                        <span className={cx("absolute top-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-all", s.is_active ? "left-3.5" : "left-0.5")} />
                      </div>
                      <span className={cx("font-medium", s.is_active ? "text-emerald-600" : "text-slate-400")}>
                        {s.is_active ? t("active") : t("inactive")}
                      </span>
                    </button>
                  </td>
                  <td className="px-5 py-3.5">
                    <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition">
                      <button onClick={() => openEdit(s)} className="p-1.5 rounded-lg text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition" title={tc("edit")}>
                        <Pencil size={14} />
                      </button>
                      {deleteId === s.id ? (
                        <span className="flex items-center gap-1">
                          <button onClick={() => handleDelete(s.id)} className="px-2 py-1 text-xs text-red-600 bg-red-50 rounded-lg border border-red-200 hover:bg-red-100 transition font-medium">{tc("delete")}</button>
                          <button onClick={() => setDeleteId(null)} className="px-2 py-1 text-xs text-slate-500 bg-slate-50 rounded-lg border border-slate-200 hover:bg-slate-100 transition">{tc("cancel")}</button>
                        </span>
                      ) : (
                        <button onClick={() => setDeleteId(s.id)} className="p-1.5 rounded-lg text-slate-400 hover:text-red-500 hover:bg-red-50 transition" title={tc("delete")}>
                          <Trash2 size={14} />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="px-5 py-3 border-t border-slate-100 bg-slate-50/50">
            <p className="text-xs text-slate-400">
              {sources.length} {t("tab_sources").toLowerCase()} — {sources.length} {t("active").toLowerCase()}
            </p>
          </div>
        </div>
      )}

      {modal.open && (
        <SourceModal initial={modal.item} onSave={handleSave} onClose={closeModal} loading={saving} error={saveError} />
      )}
    </div>
  );
}

// ─── Cron status card ─────────────────────────────────────────────────────────
const HEALTH_STYLE = {
  healthy:      { bg: "bg-emerald-50", border: "border-emerald-200", dot: "bg-emerald-500", text: "text-emerald-700", pulse: true },
  delayed:      { bg: "bg-amber-50",   border: "border-amber-200",   dot: "bg-amber-400",   text: "text-amber-700",   pulse: false },
  stale:        { bg: "bg-red-50",     border: "border-red-200",     dot: "bg-red-400",     text: "text-red-700",     pulse: false },
  error:        { bg: "bg-orange-50",  border: "border-orange-300",  dot: "bg-orange-500",  text: "text-orange-700",  pulse: false },
  inactive:     { bg: "bg-slate-100",  border: "border-slate-200",   dot: "bg-slate-400",   text: "text-slate-600",   pulse: false },
  unconfigured: { bg: "bg-slate-50",   border: "border-slate-200",   dot: "bg-slate-300",   text: "text-slate-400",   pulse: false },
} as const;

function CronStatusCard({ status, onToggle, onPoll, toggling, polling }: {
  status: CronStatus; onToggle: () => void; onPoll: () => void; toggling: boolean; polling: boolean;
}) {
  const t = useTranslations("settings");
  const h = HEALTH_STYLE[status.health as keyof typeof HEALTH_STYLE] ?? HEALTH_STYLE.stale;
  const healthLabel = t(`cron_health_${status.health}` as any);

  return (
    <div className={cx("rounded-2xl border-2 p-5", h.bg, h.border)}>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="relative w-10 h-10 flex items-center justify-center">
            <span className={cx("w-10 h-10 rounded-full absolute inset-0 opacity-20", h.bg)} />
            <span className={cx("w-4 h-4 rounded-full", h.dot, h.pulse && "animate-pulse")} />
          </div>
          <div>
            <p className={cx("font-bold text-sm", h.text)}>{t("cron_service_label")}</p>
            <p className={cx("text-xs mt-0.5 font-medium", h.text)}>{healthLabel} — {status.health_label}</p>
          </div>
        </div>
        {status.health !== "unconfigured" && (
          <div className="flex items-center gap-2">
            <button
              onClick={onPoll}
              disabled={polling || !status.is_active}
              className={cx("flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border bg-white/80 transition disabled:opacity-40", h.border, h.text)}
            >
              <Zap size={12} className={polling ? "animate-pulse" : ""} />
              {polling ? t("cron_polling") : t("cron_poll_now")}
            </button>
            <button
              onClick={onToggle}
              disabled={toggling}
              className={cx(
                "flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold border bg-white/80 transition disabled:opacity-40",
                status.is_active ? "border-red-300 text-red-600 hover:bg-red-50" : "border-emerald-300 text-emerald-700 hover:bg-emerald-50"
              )}
            >
              {toggling ? <RefreshCw size={12} className="animate-spin" /> : status.is_active ? <PowerOff size={12} /> : <Power size={12} />}
              {toggling ? "…" : status.is_active ? t("cron_stop") : t("cron_start")}
            </button>
          </div>
        )}
      </div>

      <div className="flex flex-wrap gap-5 mt-4 pt-4 border-t border-current/10">
        <div className={cx("flex items-center gap-1.5 text-xs", h.text)}>
          <Clock size={12} />
          {status.last_run ? new Date(status.last_run).toLocaleString() : t("cron_no_run")}
        </div>
        <div className={cx("flex items-center gap-1.5 text-xs", h.text)}>
          <Activity size={12} />
          {t("cron_interval", { n: status.cron_interval_minutes })}
        </div>
        {status.last_error && (
          <div className="flex items-center gap-1.5 text-xs text-red-600">
            <AlertTriangle size={12} /> {status.last_error}
          </div>
        )}
      </div>

    </div>
  );
}

// ─── Onglet IMAP ──────────────────────────────────────────────────────────────
function ImapTab() {
  const t = useTranslations("settings");
  const tc = useTranslations("common");
  const [config, setConfig] = useState<MailInboxConfig>(null);
  const [cronStatus, setCronStatus] = useState<CronStatus | null>(null);
  const [loadingConfig, setLoadingConfig] = useState(true);
  const [form, setForm] = useState<MailImapPayload>({
    imap_host: "", imap_port: 993, imap_user: "", imap_password: "",
    use_ssl: true, mailbox: "INBOX", is_active: true,
  });
  const [showPwd, setShowPwd] = useState(false);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [polling, setPolling] = useState(false);
  const [toggling, setToggling] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [saveError, setSaveError] = useState("");
  const [saveOk, setSaveOk] = useState(false);

  const loadAll = async () => {
    const [cfg, cron] = await Promise.all([getMailImapConfig(), getMailCronStatus()]);
    setConfig(cfg);
    setCronStatus(cron);
    if (cfg) setForm({ imap_host: cfg.imap_host, imap_port: cfg.imap_port, imap_user: cfg.imap_user, imap_password: "", use_ssl: cfg.use_ssl, mailbox: cfg.mailbox, is_active: cfg.is_active });
  };

  useEffect(() => { loadAll().finally(() => setLoadingConfig(false)); }, []);

  const setField = (k: keyof MailImapPayload) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [k]: val }));
    setTestResult(null); setSaveOk(false);
  };

  const handleToggleActive = async () => {
    if (!config) return;
    setToggling(true);
    try {
      const upd = await saveMailImapConfig({ ...form, is_active: !config.is_active });
      setConfig(upd); setForm((f) => ({ ...f, is_active: !config.is_active }));
      setCronStatus(await getMailCronStatus());
    } catch { /* ignore */ } finally { setToggling(false); }
  };

  const handleTest = async () => {
    setTesting(true); setTestResult(null);
    try { setTestResult(await testMailImapConfig({ ...form, imap_password: form.imap_password || "" })); }
    catch (e: any) { setTestResult({ success: false, message: e?.detail || "Erreur de connexion." }); }
    finally { setTesting(false); }
  };

  const handleSave = async () => {
    setSaving(true); setSaveError(""); setSaveOk(false);
    try {
      setConfig(await saveMailImapConfig(form));
      setSaveOk(true);
      setCronStatus(await getMailCronStatus());
    } catch (e: any) { setSaveError(e?.detail || "Erreur."); }
    finally { setSaving(false); }
  };

  const handlePoll = async () => {
    setPolling(true);
    try {
      const res = await pollMailNow();
      setConfig((p) => p ? { ...p, last_polled_at: res.last_polled_at, last_error: res.last_error } : p);
      setCronStatus(await getMailCronStatus());
    } catch { /* ignore */ } finally { setPolling(false); }
  };

  if (loadingConfig) return (
    <div className="flex-1 flex items-center justify-center text-slate-400">
      <RefreshCw size={20} className="animate-spin mr-2" /> {tc("loading")}
    </div>
  );

  const steps = [
    { step: "1", title: t("imap_step1_title"), desc: t("imap_step1_desc") },
    { step: "2", title: t("imap_step2_title"), desc: t("imap_step2_desc") },
    { step: "3", title: t("imap_step3_title"), desc: t("imap_step3_desc") },
    { step: "4", title: t("imap_step4_title"), desc: t("imap_step4_desc") },
  ];

  return (
    <div className="flex gap-8 h-full">
      <div className="flex-1 min-w-0 space-y-6">
        <div>
          <h2 className="text-lg font-bold text-slate-800">{t("imap_title")}</h2>
          <p className="text-sm text-slate-500 mt-1">{t("imap_desc")}</p>
        </div>

        {cronStatus && (
          <CronStatusCard status={cronStatus} onToggle={handleToggleActive} onPoll={handlePoll} toggling={toggling} polling={polling} />
        )}

        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
          <div className="px-6 py-4 border-b border-slate-100 bg-slate-50/50">
            <p className="text-sm font-semibold text-slate-700">{t("imap_credentials")}</p>
          </div>
          <div className="p-6 grid grid-cols-2 gap-5">
            <Field label={t("label_imap_host")} required full>
              <input className={inputCls} value={form.imap_host} onChange={setField("imap_host")} placeholder="imap.gmail.com" />
            </Field>
            <Field label={t("label_port")}>
              <input className={inputCls} type="number" value={form.imap_port} onChange={setField("imap_port")} />
            </Field>
            <Field label={t("label_mailbox")}>
              <input className={inputCls} value={form.mailbox} onChange={setField("mailbox")} placeholder="INBOX" />
            </Field>
            <Field label={t("label_email")} required full>
              <input className={inputCls} type="email" value={form.imap_user} onChange={setField("imap_user")} placeholder="recouvrement@votreentreprise.com" />
            </Field>
            <Field
              label={config?.imap_password_set ? t("label_password_existing") : t("label_password")}
              required={!config?.imap_password_set}
              full
            >
              <div className="relative">
                <input
                  className={cx(inputCls, "pr-10")}
                  type={showPwd ? "text" : "password"}
                  value={form.imap_password}
                  onChange={setField("imap_password")}
                  placeholder={config?.imap_password_set ? "••••••••" : t("label_password")}
                />
                <button type="button" onClick={() => setShowPwd((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                  {showPwd ? <EyeOff size={15} /> : <Eye size={15} />}
                </button>
              </div>
            </Field>
            <div className="col-span-2">
              <label className="flex items-center gap-3 cursor-pointer select-none">
                <input type="checkbox" checked={form.use_ssl} onChange={setField("use_ssl")} className="accent-indigo-600 w-4 h-4" />
                <span className="text-sm text-slate-700">
                  {t("label_ssl")} <span className="text-slate-400">{t("label_ssl_hint")}</span>
                </span>
              </label>
            </div>
          </div>
        </div>

        {testResult && (
          <div className={cx("flex items-center gap-2 text-sm rounded-xl px-4 py-3 border", testResult.success ? "bg-emerald-50 text-emerald-700 border-emerald-200" : "bg-red-50 text-red-600 border-red-200")}>
            {testResult.success ? <CheckCircle size={16} /> : <XCircle size={16} />}
            {testResult.message}
          </div>
        )}
        {saveError && (
          <div className="flex items-center gap-2 text-sm bg-red-50 text-red-600 border border-red-200 rounded-xl px-4 py-3">
            <XCircle size={16} /> {saveError}
          </div>
        )}
        {saveOk && (
          <div className="flex items-center gap-2 text-sm bg-emerald-50 text-emerald-700 border border-emerald-200 rounded-xl px-4 py-3">
            <CheckCircle size={16} /> {t("imap_saved")}
          </div>
        )}

        <div className="flex items-center gap-3">
          <button
            onClick={handleTest}
            disabled={testing || !form.imap_host || !form.imap_user}
            className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl border border-slate-300 text-sm font-medium text-slate-700 hover:bg-slate-50 transition disabled:opacity-50"
          >
            <Wifi size={15} className={testing ? "animate-pulse" : ""} />
            {testing ? t("imap_testing") : t("imap_test")}
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !form.imap_host || !form.imap_user}
            className="flex items-center gap-1.5 px-5 py-2.5 rounded-xl text-sm font-semibold text-white shadow-sm transition disabled:opacity-50"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            {saving ? <><RefreshCw size={13} className="animate-spin" /> {tc("saving")}</> : <><Server size={14} /> {tc("save")}</>}
          </button>
        </div>
      </div>

      <div className="w-72 flex-shrink-0 space-y-4">
        <div className="bg-indigo-50 border border-indigo-100 rounded-2xl p-5 space-y-3 sticky top-0">
          <p className="text-xs font-bold text-indigo-700 uppercase tracking-wide flex items-center gap-1.5">
            <Info size={13} /> {t("imap_guide_title")}
          </p>
          <ol className="space-y-3">
            {steps.map(({ step, title, desc }) => (
              <li key={step} className="flex gap-3">
                <span className="w-5 h-5 rounded-full bg-indigo-600 text-white text-xs flex items-center justify-center flex-shrink-0 font-bold mt-0.5">{step}</span>
                <div>
                  <p className="text-xs font-semibold text-indigo-800">{title}</p>
                  <p className="text-xs text-indigo-600 mt-0.5 leading-relaxed">{desc}</p>
                </div>
              </li>
            ))}
          </ol>
        </div>

        <div className="bg-amber-50 border border-amber-100 rounded-2xl p-4">
          <p className="text-xs font-bold text-amber-700 uppercase tracking-wide mb-2 flex items-center gap-1.5">
            <AlertTriangle size={12} /> {t("imap_security_title")}
          </p>
          <p className="text-xs text-amber-600 leading-relaxed">{t("imap_security_desc")}</p>
        </div>
      </div>
    </div>
  );
}

// ─── Flag emoji helper ────────────────────────────────────────────────────────
function flag(code: string) {
  return code.toUpperCase().replace(/./g, (c) =>
    String.fromCodePoint(c.charCodeAt(0) + 127397)
  );
}

// ─── Onglet Pays ──────────────────────────────────────────────────────────────
function CountriesTab() {
  const t = useTranslations("settings");
  const tc = useTranslations("common");
  const locale = useLocale();
  const [countries, setCountries] = useState<TenantCountry[]>([]);
  const [users, setUsers] = useState<TenantUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleteId, setDeleteId] = useState<number | null>(null);

  const [addOpen, setAddOpen] = useState(false);
  const [addCode, setAddCode] = useState("");
  const [addSearch, setAddSearch] = useState("");
  const [addSaving, setAddSaving] = useState(false);
  const [addError, setAddError] = useState("");
  const [addSuccess, setAddSuccess] = useState<string | null>(null);

  const [managerModal, setManagerModal] = useState<TenantCountry | null>(null);
  const [managerUserId, setManagerUserId] = useState<number | "">("");
  const [managerSaving, setManagerSaving] = useState(false);

  useEffect(() => {
    Promise.all([listTenantCountries(), listTenantUsers()])
      .then(([c, u]) => { setCountries(c); setUsers(u); })
      .finally(() => setLoading(false));
  }, []);

  const alreadyConfigured = new Set(countries.map((c) => c.country_code));
  const available = COUNTRIES.filter(
    (c) => !alreadyConfigured.has(c.code) && (
      addSearch.trim() === "" ||
      c.fr.toLowerCase().includes(addSearch.toLowerCase()) ||
      c.en.toLowerCase().includes(addSearch.toLowerCase()) ||
      c.code.toLowerCase().includes(addSearch.toLowerCase())
    )
  );

  async function handleAdd() {
    if (!addCode) return;
    const found = COUNTRIES.find((c) => c.code === addCode);
    if (!found) return;
    setAddSaving(true); setAddError(""); setAddSuccess(null);
    try {
      const created = await createTenantCountry({
        country_code: found.code,
        country_name: locale === "fr" ? found.fr : found.en,
      });
      setCountries((p) => [...p, created].sort((a, b) => a.country_name.localeCompare(b.country_name)));
      const name = locale === "fr" ? found.fr : found.en;
      setAddSuccess(`${name} ✓`);
      setAddCode("");
      setTimeout(() => setAddSuccess(null), 3000);
    } catch (e: any) {
      setAddError(e?.detail || "Erreur lors de l'ajout.");
    } finally { setAddSaving(false); }
  }

  async function handleToggle(c: TenantCountry) {
    try {
      const updated = await updateTenantCountry(c.id, { is_active: !c.is_active });
      setCountries((p) => p.map((x) => (x.id === updated.id ? updated : x)));
    } catch { /* ignore */ }
  }

  async function handleDelete(id: number) {
    try { await deleteTenantCountry(id); setCountries((p) => p.filter((c) => c.id !== id)); }
    finally { setDeleteId(null); }
  }

  function openManagerModal(c: TenantCountry) {
    setManagerModal(c);
    setManagerUserId(c.manager?.id ?? "");
  }

  async function handleSaveManager() {
    if (!managerModal) return;
    setManagerSaving(true);
    try {
      const updated = await setCountryManager(managerModal.id, managerUserId === "" ? null : Number(managerUserId));
      setCountries((p) => p.map((x) => (x.id === updated.id ? updated : x)));
      setManagerModal(null);
    } catch { /* ignore */ } finally { setManagerSaving(false); }
  }

  if (loading) return (
    <div className="flex-1 flex items-center justify-center text-slate-400">
      <RefreshCw size={20} className="animate-spin mr-2" /> {tc("loading")}
    </div>
  );

  const explainerCards = [
    { icon: MapPin, color: "violet", title: t("geo_perimeter_title"), desc: t("geo_perimeter_desc") },
    { icon: Crown, color: "amber", title: t("country_manager_title"), desc: t("country_manager_desc") },
    { icon: ShieldCheck, color: "emerald", title: t("auto_track_title"), desc: t("auto_track_desc") },
  ];

  return (
    <div className="flex flex-col h-full">
      <div className="flex items-start justify-between mb-6">
        <div>
          <h2 className="text-lg font-bold text-slate-800">{t("countries_title")}</h2>
          <p className="text-sm text-slate-500 mt-1">{t("countries_desc")}</p>
        </div>
        <button
          onClick={() => { setAddOpen(true); setAddCode(""); setAddSearch(""); setAddError(""); }}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold text-white shadow-sm hover:shadow transition-all flex-shrink-0 ml-4"
          style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
        >
          <Plus size={15} /> {t("add_country")}
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4 mb-6">
        {explainerCards.map(({ icon: Icon, color, title, desc }) => (
          <div key={title} className={cx(
            "flex items-start gap-3 rounded-xl p-4 border",
            color === "violet" ? "bg-violet-50 border-violet-100" :
            color === "amber" ? "bg-amber-50 border-amber-100" :
            "bg-emerald-50 border-emerald-100"
          )}>
            <Icon size={18} className={cx(
              "flex-shrink-0 mt-0.5",
              color === "violet" ? "text-violet-500" :
              color === "amber" ? "text-amber-500" : "text-emerald-500"
            )} />
            <div>
              <p className={cx("text-sm font-semibold",
                color === "violet" ? "text-violet-800" :
                color === "amber" ? "text-amber-800" : "text-emerald-800"
              )}>{title}</p>
              <p className={cx("text-xs mt-0.5",
                color === "violet" ? "text-violet-600" :
                color === "amber" ? "text-amber-600" : "text-emerald-600"
              )}>{desc}</p>
            </div>
          </div>
        ))}
      </div>

      {countries.length === 0 ? (
        <div className="flex-1 flex flex-col items-center justify-center text-center py-12 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50/50">
          <div className="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
            <Globe size={28} className="text-slate-300" />
          </div>
          <p className="text-base font-semibold text-slate-600">{t("no_countries")}</p>
          <p className="text-sm text-slate-400 mt-1 max-w-xs">{t("no_countries_desc")}</p>
          <button
            onClick={() => { setAddOpen(true); setAddCode(""); setAddSearch(""); setAddError(""); }}
            className="mt-5 flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-semibold text-white"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            <Plus size={14} /> {t("add_first_country")}
          </button>
        </div>
      ) : (
        <div className="flex-1 rounded-2xl border border-slate-200 overflow-hidden bg-white shadow-sm">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-200">
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_country")}</th>
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_manager")}</th>
                <th className="text-left px-5 py-3.5 text-xs font-semibold text-slate-500 uppercase tracking-wide">{t("col_status")}</th>
                <th className="w-40" />
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {countries.map((c) => (
                <tr key={c.id} className="hover:bg-slate-50/70 transition group">
                  <td className="px-5 py-3.5">
                    <div className="flex items-center gap-3">
                      <span className="text-2xl leading-none">{flag(c.country_code)}</span>
                      <div>
                        <p className="font-semibold text-slate-800">{c.country_name}</p>
                        <p className="text-xs text-slate-400 font-mono">{c.country_code}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-5 py-3.5">
                    {c.manager ? (
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-indigo-100 flex items-center justify-center text-[10px] font-bold text-indigo-600">
                          {(c.manager.full_name || c.manager.username).slice(0, 1).toUpperCase()}
                        </div>
                        <span className="text-sm text-slate-700 font-medium">{c.manager.full_name || c.manager.username}</span>
                        <span className="text-[10px] bg-amber-50 text-amber-600 border border-amber-200 px-1.5 py-0.5 rounded-full font-medium flex items-center gap-0.5">
                          <Crown size={8} /> {t("manager_badge")}
                        </span>
                      </div>
                    ) : (
                      <span className="text-sm text-slate-400 italic">{t("not_assigned")}</span>
                    )}
                  </td>
                  <td className="px-5 py-3.5">
                    <button onClick={() => handleToggle(c)} className="flex items-center gap-2 text-xs transition">
                      <div
                        className={cx("rounded-full relative transition-colors", c.is_active ? "bg-indigo-500" : "bg-slate-300")}
                        style={{ height: "18px", width: "32px" }}
                      >
                        <span className={cx("absolute top-0.5 w-3.5 h-3.5 rounded-full bg-white shadow transition-all", c.is_active ? "left-3.5" : "left-0.5")} />
                      </div>
                      <span className={cx("font-medium", c.is_active ? "text-emerald-600" : "text-slate-400")}>
                        {c.is_active ? t("active") : t("inactive")}
                      </span>
                    </button>
                  </td>
                  <td className="px-5 py-3.5">
                    <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition">
                      <button
                        onClick={() => openManagerModal(c)}
                        className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium text-indigo-600 bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 transition"
                      >
                        <Users size={12} /> {t("col_manager")}
                      </button>
                      {deleteId === c.id ? (
                        <span className="flex items-center gap-1">
                          <button onClick={() => handleDelete(c.id)} className="px-2 py-1 text-xs text-red-600 bg-red-50 rounded-lg border border-red-200 hover:bg-red-100 transition font-medium">{tc("delete")}</button>
                          <button onClick={() => setDeleteId(null)} className="px-2 py-1 text-xs text-slate-500 bg-slate-50 rounded-lg border border-slate-200 hover:bg-slate-100 transition">{tc("cancel")}</button>
                        </span>
                      ) : (
                        <button onClick={() => setDeleteId(c.id)} className="p-1.5 rounded-lg text-slate-400 hover:text-red-500 hover:bg-red-50 transition" title={tc("delete")}>
                          <Trash2 size={14} />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="px-5 py-3 border-t border-slate-100 bg-slate-50/50">
            <p className="text-xs text-slate-400">
              {countries.length} {t("col_country").toLowerCase()} — {countries.filter((c) => c.manager).length} {t("col_manager").toLowerCase()}
            </p>
          </div>
        </div>
      )}

      {/* Modal — Ajouter pays */}
      {addOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
            <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
              <div>
                <h2 className="font-bold text-slate-800">{t("modal_add_country_title")}</h2>
                <p className="text-xs text-slate-500 mt-0.5">{t("modal_add_country_subtitle")}</p>
              </div>
              <button onClick={() => setAddOpen(false)} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition"><X size={16} /></button>
            </div>
            <div className="px-6 py-5 space-y-4">
              {addSuccess && (
                <div className="flex items-center gap-2 text-sm text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-lg px-3 py-2.5">
                  <CheckCircle size={14} /> {addSuccess}
                </div>
              )}
              {addError && (
                <div className="flex items-center gap-2 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5">
                  <XCircle size={14} /> {addError}
                </div>
              )}
              <div className="relative">
                <input
                  className={inputCls + " pl-9"}
                  placeholder={t("search_country")}
                  value={addSearch}
                  onChange={(e) => setAddSearch(e.target.value)}
                  autoFocus
                />
                <Globe size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
              </div>
              <div className="max-h-64 overflow-y-auto rounded-xl border border-slate-200 divide-y divide-slate-100">
                {available.length === 0 ? (
                  <p className="text-sm text-slate-400 text-center py-6">{t("no_countries_available")}</p>
                ) : available.slice(0, 50).map((c) => (
                  <button
                    key={c.code}
                    onClick={() => setAddCode(c.code)}
                    className={cx(
                      "w-full flex items-center gap-3 px-4 py-2.5 text-left text-sm transition",
                      addCode === c.code ? "bg-indigo-50 text-indigo-700" : "hover:bg-slate-50 text-slate-700"
                    )}
                  >
                    <span className="text-lg">{flag(c.code)}</span>
                    <span className="font-medium">{locale === "fr" ? c.fr : c.en}</span>
                    <span className="ml-auto text-xs text-slate-400 font-mono">{c.code}</span>
                    {addCode === c.code && <CheckCircle size={14} className="text-indigo-600" />}
                  </button>
                ))}
              </div>
            </div>
            <div className="flex justify-end gap-3 px-6 py-4 border-t border-slate-100 bg-slate-50 rounded-b-2xl">
              <button onClick={() => setAddOpen(false)} className="px-4 py-2 rounded-lg border border-slate-200 text-sm text-slate-600 hover:bg-white transition">
                {tc("cancel")}
              </button>
              <button
                onClick={handleAdd}
                disabled={!addCode || addSaving}
                className="flex items-center gap-1.5 px-5 py-2 rounded-lg text-sm font-semibold text-white transition disabled:opacity-50"
                style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
              >
                {addSaving ? <><RefreshCw size={13} className="animate-spin" /> {t("adding")}</> : <><Plus size={13} /> {tc("create")}</>}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal — Responsable pays */}
      {managerModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm">
            <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
              <div>
                <h2 className="font-bold text-slate-800 flex items-center gap-2">
                  <span className="text-xl">{flag(managerModal.country_code)}</span>
                  {managerModal.country_name}
                </h2>
                <p className="text-xs text-slate-500 mt-0.5">{t("modal_manager_subtitle")}</p>
              </div>
              <button onClick={() => setManagerModal(null)} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition"><X size={16} /></button>
            </div>
            <div className="px-6 py-5">
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-3">{t("label_country_manager")}</p>
              <select
                className={inputCls}
                value={managerUserId}
                onChange={(e) => setManagerUserId(e.target.value === "" ? "" : Number(e.target.value))}
              >
                <option value="">{t("no_manager_option")}</option>
                {users.filter((u) => u.is_active).map((u) => (
                  <option key={u.id} value={u.id}>
                    {u.first_name || u.last_name ? `${u.first_name || ""} ${u.last_name || ""}`.trim() : u.username}
                    {u.membership?.is_owner ? ` ${t("owner_label")}` : ""}
                  </option>
                ))}
              </select>
              <p className="text-xs text-slate-400 mt-2">{t("manager_hint")}</p>
            </div>
            <div className="flex justify-end gap-3 px-6 py-4 border-t border-slate-100 bg-slate-50 rounded-b-2xl">
              <button onClick={() => setManagerModal(null)} className="px-4 py-2 rounded-lg border border-slate-200 text-sm text-slate-600 hover:bg-white transition">
                {tc("cancel")}
              </button>
              <button
                onClick={handleSaveManager}
                disabled={managerSaving}
                className="flex items-center gap-1.5 px-5 py-2 rounded-lg text-sm font-semibold text-white transition disabled:opacity-50"
                style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
              >
                {managerSaving ? <><RefreshCw size={13} className="animate-spin" /> {tc("saving")}</> : tc("save")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────
type TabId = "countries" | "sources" | "imap";

export default function SettingsPage() {
  const t = useTranslations("settings");
  const [tab, setTab] = useState<TabId>("countries");

  const NAV_ITEMS: { id: TabId; labelKey: string; descKey: string; icon: React.ElementType; group: string }[] = [
    { id: "countries", labelKey: "tab_countries", descKey: "tab_countries_desc", icon: Globe,   group: "geography" },
    { id: "sources",   labelKey: "tab_sources",   descKey: "tab_sources_desc",   icon: Mail,    group: "mail" },
    { id: "imap",      labelKey: "tab_imap",       descKey: "tab_imap_desc",       icon: Server,  group: "mail" },
  ];

  const groups: { key: string; labelKey: "nav_group_geography" | "nav_group_mail" }[] = [
    { key: "geography", labelKey: "nav_group_geography" },
    { key: "mail",      labelKey: "nav_group_mail" },
  ];

  return (
    <div className="flex flex-col h-full overflow-hidden">
      <div
        className="flex-shrink-0 px-8 py-5 border-b border-slate-200 bg-white"
        style={{ borderTop: `3px solid ${NAVY}` }}
      >
        <div className="flex items-center gap-2 text-xs text-slate-400 mb-2">
          <span>{t("breadcrumb_workspace")}</span>
          <ChevronRight size={11} />
          <span className="text-slate-600 font-medium">{t("title")}</span>
        </div>
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-xl flex items-center justify-center shadow-sm" style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
            <Settings size={18} color="white" />
          </div>
          <div>
            <h1 className="text-lg font-bold text-slate-800">{t("title")}</h1>
            <p className="text-xs text-slate-500">{t("subtitle")}</p>
          </div>
        </div>
      </div>

      <div className="flex-1 flex overflow-hidden">
        <aside className="w-60 flex-shrink-0 bg-slate-50 border-r border-slate-200 py-4 overflow-y-auto">
          {groups.map(({ key, labelKey }) => (
            <div key={key} className="mb-2">
              <p className="px-4 mb-1 text-xs font-bold text-slate-400 uppercase tracking-wider">{t(labelKey)}</p>
              {NAV_ITEMS.filter((n) => n.group === key).map(({ id, labelKey: lk, descKey, icon: Icon }) => (
                <button
                  key={id}
                  onClick={() => setTab(id)}
                  className={cx(
                    "w-full flex items-center gap-3 px-4 py-3 text-left transition group",
                    tab === id ? "bg-white border-r-2 shadow-sm" : "hover:bg-white/60"
                  )}
                  style={tab === id ? { borderRightColor: NAVY2 } : {}}
                >
                  <div className={cx(
                    "w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 transition",
                    tab === id ? "text-white shadow-sm" : "bg-slate-200 text-slate-500 group-hover:bg-slate-300"
                  )}
                    style={tab === id ? { background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` } : {}}
                  >
                    <Icon size={15} />
                  </div>
                  <div className="min-w-0">
                    <p className={cx("text-sm font-semibold truncate", tab === id ? "text-slate-800" : "text-slate-600")}>{t(lk as any)}</p>
                    <p className="text-xs text-slate-400 truncate mt-0.5">{t(descKey as any)}</p>
                  </div>
                </button>
              ))}
            </div>
          ))}
        </aside>

        <main className="flex-1 overflow-y-auto p-8 bg-slate-50/30">
          {tab === "countries" && <CountriesTab />}
          {tab === "sources" && <SourcesTab />}
          {tab === "imap" && <ImapTab />}
        </main>
      </div>
    </div>
  );
}
