'use client';

import { useEffect, useMemo, useState, type RefObject } from 'react';
import { toast } from 'react-toastify';
import { api } from '@/lib/api';
import { fetchEmailTemplates, fillTemplate, type EmailTemplate } from '@/lib/notificationTemplates';

export interface SmsCandidate {
  id: number;
  name: string;
  company: string;
  jobTitle: string;
  email: string;
  phone: string;
  uploadedBy: string;
  uploadedAt: string;
}

interface SendSmsMailModalProps {
  open: boolean;
  onClose: () => void;
  candidates: SmsCandidate[];
  /** Available messaging credits shown in the header. */
  credits?: { sms: number; whatsapp: number };
  /** Called when a CSV is chosen + submitted (reuses the page's import). */
  onImportCsv?: (file: File) => void;
  importing?: boolean;
  /** Ref to the hidden CSV file input, so the parent can reopen the file
   * picker (e.g. after "Cancel / Choose Another File" on the preview popup)
   * without this modal needing to know anything about that flow. */
  csvInputRef?: RefObject<HTMLInputElement | null>;
}

function formatDate(iso: string) {
  const d = new Date(iso);
  if (isNaN(d.getTime())) return '—';
  return d.toLocaleString('en-IN', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true });
}

interface SentRecord {
  id: number;
  action: string;
  candidate: SmsCandidate;
  sentAt: Date;
}

/** "27-03-2026 06:06:25 PM" — matches the legacy system's date format. */
function legacyDate(d: Date | string) {
  const dt = typeof d === 'string' ? new Date(d) : d;
  if (isNaN(dt.getTime())) return '—';
  const pad = (n: number) => String(n).padStart(2, '0');
  let h = dt.getHours();
  const ampm = h >= 12 ? 'PM' : 'AM';
  h = h % 12 || 12;
  return `${pad(dt.getDate())}-${pad(dt.getMonth() + 1)}-${dt.getFullYear()} ${pad(h)}:${pad(dt.getMinutes())}:${pad(dt.getSeconds())} ${ampm}`;
}

export default function SendSmsMailModal({
  open,
  onClose,
  candidates,
  credits = { sms: 17765, whatsapp: 175 },
  onImportCsv,
  importing = false,
  csvInputRef,
}: SendSmsMailModalProps) {
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [csvFile, setCsvFile] = useState<File | null>(null);
  const [sending, setSending] = useState<string | null>(null);
  const [tab, setTab] = useState<'send' | 'history'>('send');
  const [sentHistory, setSentHistory] = useState<any[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [subject, setSubject] = useState('Regarding your application for {job}');
  const [message, setMessage] = useState('Hi {name},\n\nWe would like to update you about your application for {job} at {company}.\n\nRegards,\nTA-ATS Team');

  // --- Notification templates (dynamic — from Master Data → Notification Templates) ---
  const [templates, setTemplates] = useState<EmailTemplate[]>([]);
  const [templateId, setTemplateId] = useState<number | ''>('');

  // Load templates when the modal opens; default to the first and apply it.
  useEffect(() => {
    if (!open) return;
    fetchEmailTemplates().then((rows) => {
      setTemplates(rows);
      if (rows.length && templateId === '') applyTemplate(rows[0]);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  const applyTemplate = (t: EmailTemplate) => {
    setTemplateId(t.id);
    if (t.subject) setSubject(t.subject);
    if (t.body) setMessage(t.body);
  };

  // --- Job Order: enter an ID, preview the JD, auto-fill the mail from it ---
  const [jobId, setJobId] = useState('');
  const [jobPreview, setJobPreview] = useState<any | null>(null);
  const [jobLoading, setJobLoading] = useState(false);
  const [showJobDetails, setShowJobDetails] = useState(false);

  const stripHtml = (s: string) => (s || '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();

  const loadJobPreview = async () => {
    const id = jobId.trim();
    if (!id || !/^\d+$/.test(id)) { toast.warning('Enter a numeric Job Order ID (Ref. #).'); return; }
    setJobLoading(true);
    try {
      const r = (await api.get(`/jobs/${id}/`)) as any;
      const j = r?.data ?? r;
      if (!j?.title) throw new Error('Job Order not found.');
      setJobPreview(j);
      setShowJobDetails(true);
      // Auto-fill the mail from the JD — user can still edit before sending.
      setSubject(`Job Opportunity: ${j.title} (Ref #${j.id})${j.client_name ? ` — ${j.client_name}` : ''}`);
      const details = stripHtml(j.work_details).slice(0, 900);
      setMessage(
        `Hi {name},\n\n` +
        `We have a job opportunity that matches your profile:\n\n` +
        `Position: ${j.title} (Ref #${j.id})\n` +
        (j.client_name ? `Company: ${j.client_name}\n` : '') +
        (j.location ? `Location: ${j.location}\n` : '') +
        (j.experience_band ? `Experience: ${j.experience_band}\n` : '') +
        (j.ctc_band ? `CTC: ${j.ctc_band}\n` : '') +
        (j.must_have_skills ? `Key Skills: ${j.must_have_skills}\n` : '') +
        (details ? `\nAbout the role:\n${details}\n` : '') +
        `\nIf you are interested, please reply to this email.\n\nRegards,\nTA-ATS Team`
      );
      toast.success(`JD #${j.id} loaded — mail auto-filled. Review and send.`);
    } catch (err: any) {
      setJobPreview(null);
      toast.error(err?.message || `Job Order #${id} not found.`);
    } finally {
      setJobLoading(false);
    }
  };

  const loadHistory = async () => {
    setHistoryLoading(true);
    try {
      const r = (await api.get('/candidates/notifications/')) as any;
      setSentHistory(r?.data ?? []);
    } catch { setSentHistory([]); }
    finally { setHistoryLoading(false); }
  };

  // Fill placeholders with the candidate's actual values. Handles both {name}
  // and {{candidate_name}}/{{job_title}}/{{company}}/{{location}} styles.
  const personalise = (tpl: string, c: SmsCandidate) =>
    fillTemplate(tpl, {
      name: c.name || 'Candidate',
      job_title: c.jobTitle || 'the open position',
      company: c.company || 'our client',
      location: (c as any).location || '',
      mail_link: (c as any).mail_link || '',
    });

  const allChecked = candidates.length > 0 && selected.size === candidates.length;

  const checkAll = () => setSelected(new Set(candidates.map((c) => c.id)));
  const deselectAll = () => setSelected(new Set());
  const toggle = (id: number) =>
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });

  const selectedCount = selected.size;

  // Map a button label to the API channels it sends on.
  const CHANNELS_FOR: Record<string, string[]> = {
    'Send WhatsApp, SMS & Mail': ['EMAIL', 'WHATSAPP', 'SMS'],
    'Send WhatsApp': ['WHATSAPP'],
    'Send Mail': ['EMAIL'],
    'Send SMS': ['SMS'],
  };

  const act = async (action: string) => {
    if (selectedCount === 0) {
      toast.warning('Select at least one candidate first.');
      return;
    }
    if (action === 'Rejected') {
      toast.info(`${selectedCount} candidate(s) marked as Rejected`);
      deselectAll();
      return;
    }
    if (!message.trim()) { toast.warning('Write a message first.'); return; }

    setSending(action);
    try {
      const recipients = candidates.filter((c) => selected.has(c.id));
      const r = (await api.post('/candidates/notify-bulk/', {
        channels: CHANNELS_FOR[action] || ['EMAIL'],
        items: recipients.map((c) => ({
          id: c.id,
          subject: personalise(subject, c),
          message: personalise(message, c),
        })),
      })) as any;
      const d = r?.data || {};
      if ((d.failed ?? 0) > 0) toast.warn(r?.message || 'Some notifications failed — see View Sent.');
      else toast.success(r?.message || 'Notifications sent ✓');
      deselectAll();
      setTab('history');
      loadHistory();
    } catch (err: any) {
      toast.error(err?.message || 'Send failed.');
    } finally {
      setSending(null);
    }
  };

  const ACTION_BUTTONS: Array<{ label: string; cls: string }> = useMemo(() => [
    { label: 'Rejected',                cls: 'bg-rose-600 hover:bg-rose-500' },
    { label: 'Send WhatsApp, SMS & Mail', cls: 'bg-indigo-600 hover:bg-indigo-500' },
    { label: 'Send WhatsApp',           cls: 'bg-emerald-600 hover:bg-emerald-500' },
    { label: 'Send Mail',               cls: 'bg-blue-600 hover:bg-blue-500' },
    { label: 'Send SMS',                cls: 'bg-[#405189] hover:bg-[#364574]' },
  ], []);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="fixed inset-0 bg-slate-950/40 dark:bg-slate-950/80 backdrop-blur-sm" onClick={onClose}></div>
      <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 w-full max-w-5xl rounded-none relative z-10 shadow-2xl animate-in fade-in zoom-in duration-200 text-slate-800 dark:text-slate-100 flex flex-col max-h-[90vh]">

        {/* Header — title + credits */}
        <div className="flex flex-wrap items-center justify-between gap-3 px-6 pt-5 pb-4 border-b border-slate-100 dark:border-slate-800 shrink-0">
          <div className="flex items-center gap-3 min-w-0">
            <div className="w-10 h-10 rounded-none bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 flex items-center justify-center shrink-0">
              <i className="fa-solid fa-paper-plane"></i>
            </div>
            <div className="min-w-0">
              <h3 className="text-base font-bold text-slate-900 dark:text-white leading-tight">
                Upload Candidates&apos; Excel for sending mail/sms
              </h3>
              <p className="text-xs text-slate-400">Select candidates below and choose a send action.</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs font-bold bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-900/40 rounded-full px-3 py-1">
              SMS: {credits.sms.toLocaleString()}
            </span>
            <span className="text-xs font-bold bg-teal-50 dark:bg-teal-950/40 text-teal-700 dark:text-teal-300 border border-teal-200 dark:border-teal-900/40 rounded-full px-3 py-1">
              WhatsApp: {credits.whatsapp.toLocaleString()}
            </span>
            <button onClick={onClose} className="ml-2 w-8 h-8 rounded-none flex items-center justify-center text-slate-400 hover:text-slate-700 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer">
              <i className="fa-solid fa-xmark"></i>
            </button>
          </div>
        </div>

        {/* Tabs — Send Mail / View Sent */}
        <div className="flex items-center gap-1 px-6 pt-3 shrink-0 border-b border-slate-100 dark:border-slate-800">
          {([
            { key: 'send', label: 'Send Mail', icon: 'fa-solid fa-paper-plane' },
            { key: 'history', label: `View Sent${sentHistory.length ? ` (${sentHistory.length})` : ''}`, icon: 'fa-solid fa-envelope-circle-check' },
          ] as const).map((t) => (
            <button
              key={t.key}
              onClick={() => { setTab(t.key); if (t.key === 'history') loadHistory(); }}
              className={`flex items-center gap-1.5 text-xs font-bold px-4 py-2.5 rounded-none border-b-2 transition cursor-pointer ${
                tab === t.key
                  ? 'border-indigo-600 text-indigo-600 dark:text-indigo-400 bg-indigo-50/50 dark:bg-indigo-950/20'
                  : 'border-transparent text-slate-400 hover:text-slate-600 dark:hover:text-slate-300'
              }`}
            >
              <i className={`${t.icon} text-[11px]`} /> {t.label}
            </button>
          ))}
        </div>

        {tab === 'send' ? (
        <div className="px-6 py-4 overflow-y-auto custom-scrollbar flex-1 min-h-0 space-y-4">
          {/* CSV import row */}
          <div className="bg-slate-50 dark:bg-slate-950/50 border border-slate-200 dark:border-slate-800 rounded-none px-4 py-3 flex flex-wrap items-center gap-3">
            <span className="text-xs font-bold text-slate-600 dark:text-slate-300">Import candidates&apos; CSV file:</span>
            <label className="text-xs font-semibold bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-none px-3 py-1.5 cursor-pointer hover:border-indigo-400 transition">
              <i className="fa-solid fa-folder-open mr-1.5 text-slate-400"></i>
              {csvFile ? csvFile.name : 'Choose file'}
              <input type="file" accept=".csv" className="hidden" ref={csvInputRef}
                onChange={(e) => {
                  setCsvFile(e.target.files?.[0] ?? null);
                  // Reset the native input value after reading it — otherwise
                  // the browser won't fire another change event if the user
                  // picks the exact same file again (e.g. after Cancel /
                  // Choose Another File on the preview popup), so "Choose
                  // file" silently does nothing and Submit re-warns "Choose a
                  // CSV file first." Matches the working Bulk Candidate
                  // upload input, which already resets its value the same way.
                  e.currentTarget.value = '';
                }} />
            </label>
            <button
              onClick={() => {
                if (!csvFile) { toast.warning('Choose a CSV file first.'); return; }
                onImportCsv?.(csvFile);
                setCsvFile(null);
              }}
              disabled={importing}
              className="text-xs font-bold bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-none px-4 py-1.5 transition cursor-pointer"
            >
              {importing ? 'Importing…' : 'Submit'}
            </button>
            <a href="/templates/candidate-bulk-template.xlsx" download
              className="text-xs font-bold bg-[#299cdb] hover:bg-[#2385ba] text-white rounded-none px-3 py-1.5 transition">
              Download Sample File
            </a>
          </div>

          {/* Job Order: enter Ref # → preview JD → mail auto-fills from it */}
          <div className="bg-[#0ab39c]/5 border border-[#0ab39c]/25 rounded-none px-4 py-3">
            <div className="flex flex-wrap items-center gap-2">
              <span className="text-xs font-bold text-[#0ab39c]">Job Order ID (Ref. #):</span>
              <input
                value={jobId}
                onChange={(e) => setJobId(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') loadJobPreview(); }}
                placeholder="e.g. 22"
                className="w-28 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-1.5 text-xs focus:outline-none text-slate-800 dark:text-white"
              />
              <button
                onClick={loadJobPreview}
                disabled={jobLoading}
                className="text-xs font-bold bg-[#0ab39c] hover:bg-[#099885] disabled:opacity-50 text-white rounded-none px-4 py-1.5 transition cursor-pointer"
              >
                {jobLoading ? (<><i className="fa-solid fa-spinner fa-spin mr-1"></i>Loading…</>) : (<><i className="fa-solid fa-eye mr-1"></i>Preview & Use JD</>)}
              </button>
              {jobPreview && (
                <button onClick={() => setShowJobDetails(true)}
                  className="text-[11px] font-bold text-[#0ab39c] hover:underline cursor-pointer">
                  <i className="fa-solid fa-eye mr-1"></i>Preview mail
                </button>
              )}
              <span className="text-[10px] text-slate-400 ml-auto">The JD is auto-filled into the mail and sent to all selected candidates.</span>
            </div>
          </div>

          {/* Pending list */}
          <div>
            <div className="flex flex-wrap items-center justify-between gap-2 mb-2">
              <p className="text-xs font-bold text-slate-700 dark:text-slate-300">Pending for sending mail/sms:</p>
              <div className="flex items-center gap-2">
                <button onClick={checkAll}
                  className="text-[11px] font-bold border border-slate-200 dark:border-slate-700 rounded-none px-2.5 py-1 hover:bg-slate-50 dark:hover:bg-slate-800 transition cursor-pointer text-slate-600 dark:text-slate-300">
                  Check All
                </button>
                <button onClick={deselectAll}
                  className="text-[11px] font-bold border border-slate-200 dark:border-slate-700 rounded-none px-2.5 py-1 hover:bg-slate-50 dark:hover:bg-slate-800 transition cursor-pointer text-slate-600 dark:text-slate-300">
                  Deselect All
                </button>
                <span className="text-[11px] font-bold text-indigo-600 dark:text-indigo-400">{selectedCount} selected</span>
              </div>
            </div>

            <div className="border border-slate-200 dark:border-slate-800 rounded-none overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-xs min-w-[820px]">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-slate-950/40 border-b border-slate-200 dark:border-slate-800">
                      <th className="py-2.5 px-3 text-left w-8">
                        <input type="checkbox" checked={allChecked}
                          onChange={() => (allChecked ? deselectAll() : checkAll())}
                          className="w-4 h-4 rounded-none accent-indigo-600 cursor-pointer" />
                      </th>
                      {['S.No.', 'Candidate Name', 'Company Name', 'Job Title', 'Email-Id', 'Contact No.', 'Uploaded By', 'Uploaded Date'].map((h) => (
                        <th key={h} className="py-2.5 px-3 text-left text-[10px] font-extrabold uppercase tracking-wider text-slate-400 whitespace-nowrap">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                    {candidates.length === 0 ? (
                      <tr>
                        <td colSpan={9} className="py-10 text-center text-slate-400 text-xs">
                          No uploaded candidates yet. Import an Excel/CSV file above — only candidates from that file appear here (not the whole database).
                        </td>
                      </tr>
                    ) : (
                      candidates.map((c, i) => {
                        const checked = selected.has(c.id);
                        return (
                          <tr key={c.id}
                            onClick={() => toggle(c.id)}
                            className={`cursor-pointer transition ${checked ? 'bg-indigo-50/60 dark:bg-indigo-950/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/40'}`}>
                            <td className="py-2.5 px-3">
                              <input type="checkbox" checked={checked} onChange={() => toggle(c.id)}
                                onClick={(e) => e.stopPropagation()}
                                className="w-4 h-4 rounded-none accent-indigo-600 cursor-pointer" />
                            </td>
                            <td className="py-2.5 px-3 font-bold text-slate-500 dark:text-slate-400">{String(i + 1).padStart(2, '0')}</td>
                            <td className="py-2.5 px-3 font-semibold text-slate-800 dark:text-slate-200 whitespace-nowrap">{c.name}</td>
                            <td className="py-2.5 px-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{c.company || '—'}</td>
                            <td className="py-2.5 px-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{c.jobTitle || '—'}</td>
                            <td className="py-2.5 px-3 text-slate-500 dark:text-slate-400">{c.email}</td>
                            <td className="py-2.5 px-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{c.phone || '—'}</td>
                            <td className="py-2.5 px-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{c.uploadedBy}</td>
                            <td className="py-2.5 px-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{formatDate(c.uploadedAt)}</td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        ) : (
        /* ---- View Sent: real notification log (all candidates) ---- */
        <div className="px-6 py-4 overflow-y-auto custom-scrollbar flex-1 min-h-0">
          {historyLoading ? (
            <p className="text-xs text-slate-400 py-10 text-center"><i className="fa-solid fa-spinner fa-spin mr-2"></i>Loading sent history…</p>
          ) : sentHistory.length === 0 ? (
            <div className="py-14 text-center">
              <div className="w-12 h-12 mx-auto bg-slate-50 dark:bg-slate-950/40 rounded-none border border-slate-100 dark:border-slate-800 flex items-center justify-center text-slate-400 mb-3">
                <i className="fa-solid fa-envelope-open text-xl" />
              </div>
              <h4 className="font-bold text-slate-800 dark:text-white text-sm">Nothing sent yet</h4>
              <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">Mails/SMS you send will appear here.</p>
            </div>
          ) : (
            <div className="border border-slate-200 dark:border-slate-800 rounded-none overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-xs min-w-[900px]">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-slate-950/40 border-b border-slate-200 dark:border-slate-800">
                      {['S.No.', 'Candidate Name', 'Channel', 'Status', 'Subject / Message', 'Email-Id', 'Contact No.', 'Sent By', 'Sent Date'].map((h) => (
                        <th key={h} className="py-2.5 px-3 text-left text-[10px] font-extrabold uppercase tracking-wider text-slate-400 whitespace-nowrap">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                    {sentHistory.map((h, i) => (
                      <tr key={h.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition align-top">
                        <td className="py-3 px-3 font-bold text-slate-500 dark:text-slate-400">{String(i + 1).padStart(2, '0')}</td>
                        <td className="py-3 px-3 font-bold text-slate-800 dark:text-slate-200 whitespace-nowrap">{h.candidate_name}</td>
                        <td className="py-3 px-3 whitespace-nowrap font-semibold text-slate-700 dark:text-slate-300">
                          <i className={`mr-1.5 ${h.channel === 'WHATSAPP' ? 'fa-brands fa-whatsapp text-[#0ab39c]' : h.channel === 'SMS' ? 'fa-solid fa-comment-sms text-[#299cdb]' : 'fa-solid fa-envelope text-[#405189]'}`}></i>
                          {h.channel === 'WHATSAPP' ? 'WhatsApp' : h.channel === 'SMS' ? 'SMS' : 'Mail'}
                        </td>
                        <td className="py-3 px-3 whitespace-nowrap">
                          <span className={`text-[10px] font-extrabold px-2 py-0.5 rounded-full ${h.status === 'SENT' ? 'bg-emerald-600 text-white' : 'bg-rose-600 text-white'}`}>
                            {h.status === 'SENT' ? 'Sent ✓' : 'Failed ✕'}
                          </span>
                        </td>
                        <td className="py-3 px-3 max-w-[260px]">
                          {h.subject && <p className="font-bold text-slate-700 dark:text-slate-300 truncate">{h.subject}</p>}
                          <p className="text-slate-500 dark:text-slate-400 line-clamp-2">{h.message}</p>
                          {h.error && <p className="text-rose-500 mt-0.5 text-[11px]"><i className="fa-solid fa-circle-exclamation mr-1"></i>{h.error}</p>}
                        </td>
                        <td className="py-3 px-3 text-indigo-600 dark:text-indigo-400 font-semibold break-all max-w-[200px]">{h.email || '—'}</td>
                        <td className="py-3 px-3 font-semibold text-slate-700 dark:text-slate-300 whitespace-nowrap">{h.phone || '—'}</td>
                        <td className="py-3 px-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">{h.sent_by || '—'}</td>
                        <td className="py-3 px-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{legacyDate(h.created_at)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
        )}

        {/* Action buttons (send tab only) */}
        {tab === 'send' && (
        <div className="flex flex-wrap items-center gap-2 px-6 py-4 border-t border-slate-100 dark:border-slate-800 shrink-0">
          {ACTION_BUTTONS.map((b) => (
            <button
              key={b.label}
              onClick={() => act(b.label)}
              disabled={sending !== null || selectedCount === 0}
              className={`text-xs font-bold text-white rounded-none px-3.5 py-2 transition cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1.5 ${b.cls}`}
            >
              {sending === b.label && <i className="fa-solid fa-spinner fa-spin text-[10px]" />}
              {b.label}
            </button>
          ))}
          <span className="ml-auto text-[11px] text-slate-400">
            Actions apply to {selectedCount} selected candidate{selectedCount === 1 ? '' : 's'}.
          </span>
        </div>
        )}

        {/* JD + mail preview modal */}
        {jobPreview && showJobDetails && (
          <div className="fixed inset-0 z-[70] flex items-center justify-center p-4">
            <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm" onClick={() => setShowJobDetails(false)} />
            <div className="relative z-10 w-full max-w-2xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none shadow-2xl p-6 max-h-[85vh] flex flex-col">
              <div className="flex items-center justify-between mb-4 shrink-0">
                <h4 className="text-base font-bold text-slate-900 dark:text-white">
                  <i className="fa-solid fa-briefcase text-[#0ab39c] mr-2"></i>JD Preview — Ref #{jobPreview.id}
                </h4>
                <button onClick={() => setShowJobDetails(false)}
                  className="w-8 h-8 rounded-none flex items-center justify-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer">
                  <i className="fa-solid fa-xmark"></i>
                </button>
              </div>

              <div className="overflow-y-auto flex-1 min-h-0 space-y-4">
                {/* JD summary */}
                <div className="bg-slate-50 dark:bg-slate-950/50 border border-slate-200 dark:border-slate-800 rounded-none p-4 text-xs">
                  <div className="flex flex-wrap items-center gap-2 mb-2">
                    <span className="inline-flex items-center px-2 py-0.5 rounded-none bg-[#405189]/10 text-[#405189] font-extrabold">#{jobPreview.id}</span>
                    <span className="font-extrabold text-slate-800 dark:text-white text-sm">{jobPreview.title}</span>
                    <span className={`px-2 py-0.5 rounded-none text-[10px] font-bold ${jobPreview.status === 'Published' ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'}`}>{jobPreview.status}</span>
                  </div>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-x-4 gap-y-1 text-slate-500 dark:text-slate-400">
                    <span><b>Company:</b> {jobPreview.client_name || 'Internal'}</span>
                    <span><b>Location:</b> {jobPreview.location || '—'}</span>
                    <span><b>Experience:</b> {jobPreview.experience_band || '—'}</span>
                    <span><b>CTC:</b> {jobPreview.ctc_band || '—'}</span>
                  </div>
                  {jobPreview.must_have_skills && <p className="mt-1.5 text-slate-500 dark:text-slate-400"><b>Skills:</b> {jobPreview.must_have_skills}</p>}
                </div>

                {/* The mail that will be sent (editable) */}
                <div>
                  <div className="flex items-center justify-between mb-1.5">
                    <label className="text-[10px] uppercase font-bold text-slate-400">Email that will be sent</label>
                    <span className="text-[10px] text-slate-400">Tokens: <code>{'{{name}}'}</code> <code>{'{{job_title}}'}</code> <code>{'{{company}}'}</code> <code>{'{{location}}'}</code></span>
                  </div>
                  {/* Template picker — pulls from Master Data → Notification Templates */}
                  <div className="flex items-center gap-2 mb-2">
                    <label className="text-[10px] uppercase font-bold text-slate-400 shrink-0">Template</label>
                    <select
                      value={templateId}
                      onChange={(e) => {
                        const id = Number(e.target.value);
                        const t = templates.find((x) => x.id === id);
                        if (t) applyTemplate(t);
                      }}
                      className="flex-1 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2 text-xs focus:outline-none text-slate-800 dark:text-white"
                    >
                      {templates.length === 0 && <option value="">No templates — add under Master Data → Notification Templates</option>}
                      {templates.map((t) => (
                        <option key={t.id} value={t.id}>{t.name}</option>
                      ))}
                    </select>
                  </div>
                  <input
                    value={subject}
                    onChange={(e) => setSubject(e.target.value)}
                    className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2 text-xs font-bold focus:outline-none text-slate-800 dark:text-white mb-2"
                  />
                  <textarea
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    rows={12}
                    className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2 text-xs focus:outline-none text-slate-800 dark:text-white font-sans"
                  />
                </div>
              </div>

              <div className="flex justify-end gap-3 pt-4 shrink-0">
                <button onClick={() => setShowJobDetails(false)}
                  className="bg-[#405189] hover:bg-[#364574] text-white rounded-none px-6 py-2.5 text-xs font-extrabold shadow-md transition cursor-pointer">
                  <i className="fa-solid fa-check mr-1.5"></i>Looks good — use this mail
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
