import React, { useEffect, useState, useRef } from 'react';
import { supabase } from './supabaseClient';
import { Button } from '../components/ui/Button';
import { Input } from '../components/ui/Input';
import { Send, AlertCircle, CheckCircle2, RadioTower, Mail, Eye, Play, Database } from 'lucide-react';
import toast from 'react-hot-toast';

export const Campaign = ({ userId = '' }: { userId?: string }) => {
  const [templates, setTemplates] = useState<any[]>([]);
  const [contacts, setContacts] = useState<any[]>([]);
  const [selectedTable, setSelectedTable] = useState('members_list');
  const [sendingMode, setSendingMode] = useState<'test' | 'batch' | 'auto'>('test');
  const [autoStartRow, setAutoStartRow] = useState(1);
  const [autoBatchSize, setAutoBatchSize] = useState(50);
  const [autoEmailDelay, setAutoEmailDelay] = useState(200);
  const [autoBatchWaitSecs, setAutoBatchWaitSecs] = useState(300);
  const [autoRunning, setAutoRunning] = useState(false);
  const [autoCurrentBatch, setAutoCurrentBatch] = useState(0);
  const [autoTotalBatches, setAutoTotalBatches] = useState(0);
  const [autoTotalSent, setAutoTotalSent] = useState(0);
  const [autoTotalFailed, setAutoTotalFailed] = useState(0);
  const [autoLastSentEmail, setAutoLastSentEmail] = useState('');
  const [autoCountdown, setAutoCountdown] = useState(0);
  const [autoCountingDown, setAutoCountingDown] = useState(false);
  const [autoStopError, setAutoStopError] = useState<string | null>(null);
  const [autoResumeNotice, setAutoResumeNotice] = useState('');
  const [autoDone, setAutoDone] = useState(false);
  const autoAbortRef = useRef(false);
  const [testEmail, setTestEmail] = useState('');
  const [selectedContactIds, setSelectedContactIds] = useState<string[]>([]);
  const [rangeStart, setRangeStart] = useState<string>('1');
  const [rangeCount, setRangeCount] = useState<string>('1');
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [scheduledDate, setScheduledDate] = useState<string>('');
  const [progress, setProgress] = useState({ total: 0, sent: 0, failed: 0 });
  const [sendDetails, setSendDetails] = useState<{ email: string; success: boolean; error?: string }[]>([]);
  const processingRef = useRef(false);
  const [smtpStatus, setSmtpStatus] = useState<'checking' | 'online' | 'offline'>('checking');

  useEffect(() => {
    setSelectedContactIds([]);
    fetchTemplates();
    fetchContacts();
  }, [selectedTable]);

  useEffect(() => {
    checkSmtpStatus();
    const interval = setInterval(checkSmtpStatus, 10000); // Check every 10 seconds
    return () => clearInterval(interval);
  }, []);

  const checkSmtpStatus = async () => {
    try {
      const response = await fetch('/api/smtp-check');
      const data = await response.json();
      if (data.status === 'ready') {
        setSmtpStatus('online');
      } else {
        setSmtpStatus('offline');
      }
    } catch (err) {
      setSmtpStatus('offline');
    }
  };

  const fetchTemplates = async () => {
    const { data } = await supabase.from('templates').select('*');
    if (data) setTemplates(data);
  };

  const fetchContacts = async () => {
    const { data } = await supabase.from(selectedTable).select('*');
    if (data) {
      // Sort alphabetically by last name or name to ensure UI is always ordered
      const sortedData = [...data].sort((a, b) => {
        const nameA = (a.last_name || a.name || a.first_name || '').toLowerCase();
        const nameB = (b.last_name || b.name || b.first_name || '').toLowerCase();
        return nameA.localeCompare(nameB);
      });
      setContacts(sortedData);
    }
  };

  // Range Selection Logic
  useEffect(() => {
    if (rangeStart === '' || rangeCount === '' || contacts.length === 0) return;
    if (parseInt(rangeStart) === 0) {
      setSelectedContactIds([]);
      return;
    }
    const startIdx = parseInt(rangeStart) - 1;
    const num = parseInt(rangeCount);
    if (startIdx >= 0 && num > 0) {
      const selected = contacts.slice(startIdx, startIdx + num).map(c => c.id);
      setSelectedContactIds(selected);

      // Auto-scroll to the first selected row
      setTimeout(() => {
        const rowElement = document.getElementById(`contact-row-${startIdx}`);
        const container = document.getElementById('contact-list-container');
        if (rowElement && container) {
          const containerRect = container.getBoundingClientRect();
          const rowRect = rowElement.getBoundingClientRect();
          const scrollTop = container.scrollTop + (rowRect.top - containerRect.top) - (containerRect.height / 2) + (rowRect.height / 2);
          
          container.scrollTo({
            top: scrollTop,
            behavior: 'smooth'
          });
        }
      }, 50);
    }
  }, [rangeStart, rangeCount, contacts]);

  // Auto-batch: check for previous send to pre-fill resume row
  useEffect(() => {
    if (sendingMode !== 'auto' || !selectedTemplateId || contacts.length === 0) return;
    (async () => {
      try {
        const res = await fetch(`/api/last-send?templateId=${selectedTemplateId}&targetTable=${selectedTable}`);
        const data = await res.json();
        if (data.found && data.lastEmail) {
          const idx = contacts.findIndex((c: any) => c.email === data.lastEmail);
          if (idx !== -1) {
            const resumeRow = idx + 2;
            setAutoStartRow(resumeRow);
            setAutoResumeNotice(
              `Previous send detected (${new Date(data.sentAt).toLocaleString()}). ` +
              `Last email delivered: ${data.lastEmail}. ` +
              `Start row automatically set to ${resumeRow} — the next unsent contact.`
            );
          }
        } else {
          setAutoResumeNotice('');
        }
      } catch { /* ignore — non-critical */ }
    })();
  }, [sendingMode, selectedTemplateId, selectedTable, contacts]);

  const waitWithCountdown = (seconds: number): Promise<void> =>
    new Promise(resolve => {
      setAutoCountingDown(true);
      let rem = seconds;
      setAutoCountdown(rem);
      const tick = () => {
        if (autoAbortRef.current) { setAutoCountingDown(false); resolve(); return; }
        rem--;
        setAutoCountdown(rem);
        if (rem <= 0) { setAutoCountingDown(false); resolve(); }
        else setTimeout(tick, 1000);
      };
      setTimeout(tick, 1000);
    });

  const handleAutoRun = async () => {
    if (!selectedTemplateId) { toast.error('Please select a template.'); return; }
    if (contacts.length === 0) { toast.error('No contacts loaded.'); return; }

    // Duplicate detection
    try {
      const res = await fetch(`/api/last-send?templateId=${selectedTemplateId}&targetTable=${selectedTable}`);
      const data = await res.json();
      if (data.found) {
        const ok = window.confirm(
          `This template was already sent to this list on ${new Date(data.sentAt).toLocaleString()}.\n\nSend again?`
        );
        if (!ok) return;
      }
    } catch { /* proceed */ }

    const slice = contacts.slice(autoStartRow - 1);
    const totalBatches = Math.ceil(slice.length / autoBatchSize);

    setAutoTotalBatches(totalBatches);
    setAutoCurrentBatch(0);
    setAutoTotalSent(0);
    setAutoTotalFailed(0);
    setAutoLastSentEmail('');
    setAutoStopError(null);
    setAutoResumeNotice('');
    setAutoDone(false);
    setAutoRunning(true);
    autoAbortRef.current = false;

    let totalSent = 0;
    let totalFailed = 0;
    let lastEmail = '';

    for (let bi = 0; bi < totalBatches; bi++) {
      if (autoAbortRef.current) break;
      setAutoCurrentBatch(bi + 1);

      const batch = slice.slice(bi * autoBatchSize, (bi + 1) * autoBatchSize);
      try {
        const response = await fetch('/api/send-batch', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            subject: selectedTemplate?.subject_line || selectedTemplate?.title || 'Notification',
            markdown: selectedTemplate?.content_body || '',
            isTest: false,
            targetTable: selectedTable,
            campaignId: selectedTemplateId,
            emailDelayMs: autoEmailDelay,
            userId: userId,          // ← Add this line
            recipients: batch,
          }),
        });

        if (!response.ok) throw new Error(`Server error ${response.status}: ${response.statusText}`);
        const result = await response.json();
        if (!result.success) throw new Error('Backend failed to process batch');

        const details: any[] = result.details || [];
        const successes = details.filter(r => r.success);
        const failures  = details.filter(r => !r.success);

        if (successes.length > 0) { lastEmail = successes[successes.length - 1].email; setAutoLastSentEmail(lastEmail); }
        totalSent   += successes.length;
        totalFailed += failures.length;
        setAutoTotalSent(totalSent);
        setAutoTotalFailed(totalFailed);

        if (failures.length > 0) {
          const f = failures[0];
          const resumeRow = autoStartRow + bi * autoBatchSize + successes.length + 1;
          setAutoStopError(`Batch ${bi + 1}: failed sending to ${f.email} — ${f.error || 'unknown error'}`);
          setAutoResumeNotice(`Last successful delivery: ${lastEmail || 'none'}. Start row set to ${resumeRow} for your next run.`);
          setAutoStartRow(resumeRow);
          setAutoRunning(false);
          return;
        }

        if (bi < totalBatches - 1 && !autoAbortRef.current) {
          await waitWithCountdown(autoBatchWaitSecs);
        }
      } catch (err: any) {
        const resumeRow = autoStartRow + bi * autoBatchSize + 1;
        setAutoStopError(`Connection error at batch ${bi + 1}: ${err.message}`);
        setAutoResumeNotice(`Last successful delivery: ${lastEmail || 'none'}. Start row set to ${resumeRow} for your next run.`);
        setAutoStartRow(resumeRow);
        setAutoRunning(false);
        return;
      }
    }

    setAutoRunning(false);
    if (!autoAbortRef.current) {
      setAutoDone(true);
      toast.success(`Auto-batch complete — ${totalSent} emails delivered!`);
    }
  };

  const handleSelectMember = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedContactIds(prev => [...prev, id]);
    } else {
      setSelectedContactIds(prev => prev.filter(mId => mId !== id));
    }
  };

  const selectedTemplate = templates.find(t => t.id === selectedTemplateId);

  const handleStartCampaign = async (e: React.FormEvent) => {
    e.preventDefault();
    if (sendingMode === 'test' && !testEmail) {
      toast.error('Please enter a test email address.');
      return;
    }
    
    if (scheduledDate) {
      const scheduledTime = new Date(scheduledDate);
      if (scheduledTime <= new Date()) {
        toast.error("Scheduled time must be in the future.");
        return;
      }
      
      setIsProcessing(true);
      const { error } = await supabase.from('scheduled_campaigns').insert({
        template_id: selectedTemplateId,
        target_table: selectedTable,
        start_row: parseInt(rangeStart),
        batch_count: parseInt(rangeCount),
        test_email: sendingMode === 'test' ? testEmail : null,
        sending_mode: sendingMode,
        scheduled_at: scheduledTime.toISOString()
      });
      setIsProcessing(false);
      
      if (error) { 
        toast.error("Failed to schedule campaign: " + error.message); 
      } else { 
        toast.success("Campaign successfully scheduled for " + scheduledTime.toLocaleString()); 
        setScheduledDate(''); 
      }
      return;
    }

    setIsProcessing(true);
    processingRef.current = true;
    
    try {
      let recipients = [];
      if (sendingMode === 'test') {
        recipients = [{ email: testEmail, id: 'test' }];
      } else {
        recipients = contacts.filter(c => selectedContactIds.includes(c.id));
      }

      setProgress({ total: recipients.length, sent: 0, failed: 0 });

      // Send to local backend engine
      const response = await fetch('/api/send-batch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          subject: selectedTemplate?.subject_line || selectedTemplate?.title || 'Notification',
          markdown: selectedTemplate?.content_body || '',
          isTest: sendingMode === 'test',
          targetTable: selectedTable,
          campaignId: selectedTemplateId,
          userId: userId,          // ← Add this line
          recipients: recipients
        })
      });

      const result = await response.json();
      
      if (result.success) {
        const details = result.details || [];
        const successes = details.filter((r: any) => r.success).length;
        const failures = details.filter((r: any) => !r.success).length;
        setProgress({ total: recipients.length, sent: successes, failed: failures });
        setSendDetails(details);
        if (failures > 0) {
          toast.error(`${failures} email(s) failed — see details below.`);
        } else {
          toast.success(sendingMode === 'test' ? `Test sent to ${testEmail}` : `Batch complete! ${successes} sent.`);
        }
      } else {
        throw new Error("Backend failed to process batch");
      }
    } catch (err: any) {
      toast.error("Error sending campaign: " + err.message);
      setProgress({ total: 0, sent: 0, failed: 0 });
      setSendDetails([]);
    } finally {
      setIsProcessing(false);
      processingRef.current = false;
    }
  };

  return (
    <div className="space-y-8 max-w-6xl mx-auto pb-20">
      <div className="px-2">
        <h1 className="text-4xl font-bold text-zinc-900 tracking-tight">Direct Mailer Pro</h1>
        <p className="text-zinc-500 mt-2 text-sm font-medium">Select target list, design, and dispatch mode.</p>
      </div>

      {/* SMTP Status Banner */}
      {smtpStatus === 'checking' && (
        <div className="flex items-center gap-3 px-5 py-4 rounded-2xl bg-amber-50 border border-amber-200 text-amber-800 font-semibold text-sm shadow-sm">
          <div className="w-3 h-3 rounded-full bg-amber-400 animate-pulse flex-shrink-0" />
          Checking for SMTP Connection...
        </div>
      )}
      {smtpStatus === 'online' && (
        <div className="flex items-center gap-3 px-5 py-4 rounded-2xl bg-emerald-50 border border-emerald-200 text-emerald-800 font-semibold text-sm shadow-sm">
          <div className="w-3 h-3 rounded-full bg-emerald-500 animate-pulse shadow-[0_0_8px_rgba(52,211,153,0.6)] flex-shrink-0" />
          SMTP is Connected and ready to send email
        </div>
      )}
      {smtpStatus === 'offline' && (
        <div className="flex items-center gap-3 px-5 py-4 rounded-2xl bg-red-50 border border-red-200 text-red-800 font-semibold text-sm shadow-sm">
          <div className="w-3 h-3 rounded-full bg-red-500 flex-shrink-0" />
          SMTP is not connected
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* LEFT PANE */}
        <div className="bg-white rounded-3xl shadow-xl border border-zinc-100 p-8 space-y-6 flex flex-col h-full">
          
          {/* 1. Recipient Source */}
          <div className="space-y-3">
            <label className="block text-xs font-bold text-zinc-400 uppercase tracking-wider">1. Recipient Source</label>
            <div className="grid grid-cols-3 gap-2">
                <button onClick={() => setSelectedTable('members_list')} className={`p-3 rounded-xl border-2 text-[10px] font-black uppercase transition ${selectedTable === 'members_list' ? 'border-blue-600 bg-blue-50 text-blue-600' : 'border-zinc-100 text-zinc-400'}`}>BNP</button>
                <button onClick={() => setSelectedTable('business_partners')} className={`p-3 rounded-xl border-2 text-[10px] font-black uppercase transition ${selectedTable === 'business_partners' ? 'border-indigo-600 bg-indigo-50 text-indigo-600' : 'border-zinc-100 text-zinc-400'}`}>B2B</button>
                <button onClick={() => setSelectedTable('customer_list')} className={`p-3 rounded-xl border-2 text-[10px] font-black uppercase transition ${selectedTable === 'customer_list' ? 'border-green-600 bg-green-50 text-green-600' : 'border-zinc-100 text-zinc-400'}`}>B2C</button>
            </div>
          </div>

          {/* 2. Select Email Template */}
          <div className="space-y-2">
            <label className="block text-xs font-bold text-zinc-400 uppercase tracking-wider">2. Email Template</label>
            <select className="w-full p-4 bg-zinc-50 border border-zinc-100 rounded-2xl font-medium" value={selectedTemplateId} onChange={(e) => { setSelectedTemplateId(e.target.value); setProgress({ total: 0, sent: 0, failed: 0 }); }}>
              <option value="">-- Choose Template --</option>
              {templates.map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
            </select>
          </div>

          {/* 3. Mode Switcher */}
          <div className="pt-4 border-t border-zinc-100">
            <div className="flex bg-zinc-100 p-1 rounded-2xl">
              <button onClick={() => setSendingMode('test')} className={`flex-1 py-2.5 rounded-xl text-xs font-bold transition ${sendingMode === 'test' ? 'bg-white text-zinc-900 shadow-sm' : 'text-zinc-500'}`}>Test</button>
              <button onClick={() => { setSendingMode('batch'); setRangeStart('0'); }} className={`flex-1 py-2.5 rounded-xl text-xs font-bold transition ${sendingMode === 'batch' ? 'bg-zinc-900 text-white shadow-sm' : 'text-zinc-500'}`}>Batch</button>
              <button onClick={() => { setSendingMode('auto'); setAutoStopError(null); setAutoDone(false); }} className={`flex-1 py-2.5 rounded-xl text-xs font-bold transition ${sendingMode === 'auto' ? 'bg-blue-600 text-white shadow-sm' : 'text-zinc-500'}`}>Auto</button>
            </div>
          </div>

          {/* 4. Test Email Field */}
          {sendingMode === 'test' && (
            <div className="space-y-2 animate-in fade-in slide-in-from-top-2">
              <label className="text-xs font-bold text-zinc-400 uppercase tracking-wider">Test Recipient</label>
              <Input placeholder="Enter your email for a test run..." value={testEmail} onChange={e => setTestEmail(e.target.value)} className="bg-zinc-50 border-zinc-200 h-12" />
            </div>
          )}

          {/* 5. Start Row and Total Counters */}
          {sendingMode === 'batch' && (
            <div className="space-y-4 animate-in fade-in slide-in-from-top-2">
               <div className="flex gap-4">
                  <div className="flex-1">
                    <label className="text-xs font-bold text-zinc-400">Start Row</label>
                    <Input 
                      type="number" 
                      min="0" 
                      max={contacts.length || 1}
                      value={rangeStart} 
                      onChange={e => {
                        let val = e.target.value;
                        if (val !== '' && contacts.length > 0 && parseInt(val) > contacts.length) val = contacts.length.toString();
                        setRangeStart(val);
                      }} 
                      onBlur={() => {
                        if (rangeStart === '' || parseInt(rangeStart) < 0) setRangeStart('0');
                      }}
                      className="bg-zinc-50 border-zinc-200" 
                    />
                  </div>
                  <div className="flex-1">
                    <label className="text-xs font-bold text-zinc-400">Total Contacts</label>
                    <Input 
                      type="number" 
                      min="1" 
                      max="50"
                      value={rangeCount} 
                      onChange={e => {
                        let val = e.target.value;
                        if (val !== '' && parseInt(val) > 50) val = '50';
                        setRangeCount(val);
                      }} 
                      onBlur={() => {
                        if (rangeCount === '' || parseInt(rangeCount) < 1) setRangeCount('1');
                      }}
                      className="bg-zinc-50 border-zinc-200" 
                    />
                  </div>
               </div>
               <div className="text-xs font-bold text-zinc-500 bg-zinc-100 p-2 rounded text-center">
                 Targeting {selectedContactIds.length} recipients from {selectedTable}
               </div>
            </div>
          )}

          {/* 5b. Auto-Batch Settings */}
          {sendingMode === 'auto' && (
            <div className="space-y-4 animate-in fade-in slide-in-from-top-2">
              {autoResumeNotice && (
                <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 text-xs text-amber-800">
                  <span className="font-bold block mb-1">Resume detected</span>
                  {autoResumeNotice}
                </div>
              )}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider block mb-1">Start Row</label>
                  <Input type="number" min="1" max={contacts.length || 1} value={autoStartRow}
                    onChange={e => setAutoStartRow(Math.max(1, parseInt(e.target.value) || 1))}
                    className="bg-zinc-50 border-zinc-200" />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider block mb-1">Batch Size (max 50)</label>
                  <Input type="number" min="1" max="50" value={autoBatchSize}
                    onChange={e => setAutoBatchSize(Math.min(50, Math.max(1, parseInt(e.target.value) || 50)))}
                    className="bg-zinc-50 border-zinc-200" />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider block mb-1">Email Delay (ms)</label>
                  <Input type="number" min="50" max="5000" value={autoEmailDelay}
                    onChange={e => setAutoEmailDelay(Math.max(50, parseInt(e.target.value) || 200))}
                    className="bg-zinc-50 border-zinc-200" />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 uppercase tracking-wider block mb-1">Batch Wait (sec)</label>
                  <Input type="number" min="10" max="3600" value={autoBatchWaitSecs}
                    onChange={e => setAutoBatchWaitSecs(Math.max(10, parseInt(e.target.value) || 300))}
                    className="bg-zinc-50 border-zinc-200" />
                </div>
              </div>
              {contacts.length > 0 && (
                <div className="text-xs font-bold text-zinc-500 bg-zinc-100 p-2 rounded text-center">
                  {Math.ceil(Math.max(0, contacts.length - autoStartRow + 1) / autoBatchSize)} batch(es) of {autoBatchSize} — {Math.max(0, contacts.length - autoStartRow + 1)} contacts from row {autoStartRow}
                </div>
              )}
            </div>
          )}

          {/* 6. Send Email / Schedule Button */}
          <div className="space-y-4 border-t border-zinc-100 pt-4">
             {sendingMode !== 'auto' && (
               <div className="flex flex-col space-y-2">
                  <label className="text-xs font-bold text-zinc-400 uppercase tracking-wider">Schedule Dispatch (Optional)</label>
                  <Input type="datetime-local" value={scheduledDate} onChange={e => setScheduledDate(e.target.value)} className="bg-zinc-50 border-zinc-200 h-12" />
                  <p className="text-[10px] text-zinc-400 font-medium">Leave blank to dispatch immediately. Times are in your local timezone (Central Time).</p>
               </div>
             )}

             {sendingMode === 'auto' ? (
               <div className="space-y-2">
                 <Button
                   onClick={autoRunning ? () => { autoAbortRef.current = true; setAutoRunning(false); } : handleAutoRun}
                   disabled={!selectedTemplateId || contacts.length === 0}
                   className={`w-full h-16 rounded-2xl text-lg font-bold transition-all ${autoRunning ? 'bg-red-600 hover:bg-red-700' : 'bg-blue-600 hover:bg-blue-700'}`}
                 >
                   {autoRunning ? 'Stop Auto-Batch' : 'Start Auto-Batch'}
                 </Button>
               </div>
             ) : (
               <Button onClick={handleStartCampaign} disabled={isProcessing || (!selectedTemplateId) || (sendingMode === 'batch' && selectedContactIds.length === 0)} className="w-full h-16 rounded-2xl bg-zinc-900 hover:bg-black text-lg font-bold">
                 {isProcessing ? 'Processing...' : scheduledDate ? 'Schedule Campaign' : sendingMode === 'test' ? 'Send Test Email' : 'Start Professional Batch'}
               </Button>
             )}
          </div>

          {/* 7. List of names and email addresses */}
          <div className="flex-1 overflow-hidden flex flex-col border border-zinc-200 rounded-xl bg-zinc-50 min-h-[150px]">
            <div id="contact-list-container" className="overflow-y-auto h-full">
              <table className="w-full text-left text-sm">
                 <tbody className="divide-y divide-zinc-200">
                    {contacts.map((c, index) => (
                      <tr key={c.id} id={`contact-row-${index}`}>
                         <td className="p-3 w-8"><input type="checkbox" checked={selectedContactIds.includes(c.id)} onChange={e => handleSelectMember(c.id, e.target.checked)} className="rounded border-zinc-300 text-zinc-900 focus:ring-zinc-900" /></td>
                         <td className="p-3 font-medium text-zinc-900 whitespace-nowrap">{c.last_name && c.first_name ? `${c.last_name}, ${c.first_name}` : c.last_name || c.first_name || c.name || 'Unknown Contact'}</td>
                         <td className="p-3 text-zinc-500 text-right">{c.email}</td>
                      </tr>
                    ))}
                    {contacts.length === 0 && (
                      <tr><td colSpan={3} className="p-4 text-center text-zinc-400 italic">No contacts found in {selectedTable}</td></tr>
                    )}
                 </tbody>
              </table>
            </div>
          </div>

        </div>

        {/* RIGHT PANE: LIVE MONITOR / PREVIEW */}
        <div className="bg-white rounded-3xl shadow-xl border border-zinc-100 overflow-hidden flex flex-col h-full min-h-[500px]">
           <div className="p-6 border-b border-zinc-50 flex justify-between items-center bg-zinc-50/50">
             <h2 className="font-bold text-zinc-900 flex items-center"><RadioTower className="w-5 h-5 mr-2 text-blue-500" /> Live Monitor</h2>
             <div className="flex items-center gap-4">
               {(isProcessing || autoRunning) && <span className="animate-pulse flex items-center text-xs font-bold text-blue-600"><span className="w-2 h-2 bg-blue-600 rounded-full mr-2"></span> TRANSMITTING</span>}
               {autoCountingDown && <span className="flex items-center text-xs font-bold text-amber-600"><span className="w-2 h-2 bg-amber-500 rounded-full mr-2 animate-pulse"></span> COOLING DOWN</span>}
             </div>
           </div>

           <div className="flex-1 p-8 flex flex-col justify-start">
             {/* AUTO-BATCH MONITOR */}
             {sendingMode === 'auto' && (autoRunning || autoTotalSent > 0 || autoStopError || autoDone) ? (
               <div className="space-y-4 animate-in fade-in duration-300">
                 {/* Batch progress header */}
                 {autoTotalBatches > 0 && (
                   <div className="flex items-center justify-between text-xs font-bold text-zinc-500 bg-zinc-50 rounded-xl px-4 py-2 border border-zinc-100">
                     <span>Batch {autoCurrentBatch} of {autoTotalBatches}</span>
                     <span>{Math.max(0, contacts.length - autoStartRow + 1)} total contacts</span>
                   </div>
                 )}

                 {/* Sent / Failed counters */}
                 <div className="grid grid-cols-2 gap-4">
                   <div className="p-6 bg-emerald-50 rounded-2xl text-center border border-emerald-100">
                     <div className="text-4xl font-bold text-emerald-700">{autoTotalSent}</div>
                     <div className="text-[10px] font-bold text-emerald-600 uppercase mt-1">Delivered</div>
                   </div>
                   <div className="p-6 bg-rose-50 rounded-2xl text-center border border-rose-100">
                     <div className="text-4xl font-bold text-rose-700">{autoTotalFailed}</div>
                     <div className="text-[10px] font-bold text-rose-600 uppercase mt-1">Failed</div>
                   </div>
                 </div>

                 {/* Last sent email */}
                 {autoLastSentEmail && (
                   <div className="text-xs text-zinc-500 bg-zinc-50 rounded-xl px-4 py-2 border border-zinc-100 font-mono truncate">
                     Last sent: <span className="text-zinc-800 font-bold">{autoLastSentEmail}</span>
                   </div>
                 )}

                 {/* Countdown timer */}
                 {autoCountingDown && (
                   <div className="p-5 bg-amber-50 border border-amber-200 rounded-2xl text-center animate-in fade-in">
                     <div className="text-3xl font-bold text-amber-700 tabular-nums">{autoCountdown}s</div>
                     <div className="text-[10px] font-bold text-amber-600 uppercase mt-1">Until next batch</div>
                   </div>
                 )}

                 {/* Error / stopped state */}
                 {autoStopError && (
                   <div className="bg-rose-50 border border-rose-200 rounded-xl p-4 space-y-2">
                     <div className="flex items-center gap-2 text-rose-800 font-bold text-sm">
                       <span className="w-2 h-2 bg-rose-500 rounded-full flex-shrink-0"></span>
                       Stopped
                     </div>
                     <p className="text-xs text-rose-700 font-mono">{autoStopError}</p>
                     {autoResumeNotice && <p className="text-xs text-rose-600 mt-1">{autoResumeNotice}</p>}
                   </div>
                 )}

                 {/* Success / done state */}
                 {autoDone && !autoStopError && (
                   <div className="p-4 bg-emerald-100 border border-emerald-200 rounded-xl flex items-center justify-center font-bold text-emerald-800 animate-in zoom-in-95">
                     <CheckCircle2 className="w-5 h-5 mr-2" />
                     All batches complete — {autoTotalSent} emails delivered!
                   </div>
                 )}
               </div>
             ) : isProcessing || progress.sent > 0 ? (
               <div className="space-y-4 animate-in fade-in duration-500">
                  <div className="grid grid-cols-2 gap-4">
                     <div className="p-6 bg-emerald-50 rounded-2xl text-center border border-emerald-100">
                        <div className="text-4xl font-bold text-emerald-700">{progress.sent}</div>
                        <div className="text-[10px] font-bold text-emerald-600 uppercase mt-1">Delivered</div>
                     </div>
                     <div className="p-6 bg-rose-50 rounded-2xl text-center border border-rose-100">
                        <div className="text-4xl font-bold text-rose-700">{progress.failed}</div>
                        <div className="text-[10px] font-bold text-rose-600 uppercase mt-1">Failed</div>
                     </div>
                  </div>

                  {!isProcessing && (progress.sent + progress.failed) === progress.total && progress.total > 0 && (
                    <div className={`p-4 border rounded-xl flex items-center justify-center font-bold animate-in zoom-in-95 ${progress.failed > 0 ? 'bg-rose-100 text-rose-800 border-rose-200' : 'bg-emerald-100 text-emerald-800 border-emerald-200'}`}>
                      <CheckCircle2 className="w-5 h-5 mr-2" />
                      {progress.failed > 0 ? `${progress.sent} sent, ${progress.failed} failed` : 'All emails delivered successfully!'}
                    </div>
                  )}

                  {/* Per-email result details */}
                  {!isProcessing && sendDetails.length > 0 && (
                    <div className="space-y-1 max-h-48 overflow-y-auto rounded-xl border border-zinc-100">
                      {sendDetails.map((d, i) => (
                        <div key={i} className={`flex items-start gap-2 px-3 py-2 text-xs ${d.success ? 'bg-emerald-50 text-emerald-800' : 'bg-rose-50 text-rose-800'}`}>
                          <span className="mt-0.5 flex-shrink-0">{d.success ? '✓' : '✗'}</span>
                          <span className="font-mono break-all">
                            {d.email}
                            {!d.success && d.error && <span className="block text-rose-600 mt-0.5 font-sans">{d.error}</span>}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
               </div>
             ) : selectedTemplate ? (
               <div className="space-y-4 animate-in zoom-in-95 duration-300 h-full flex flex-col">
                  <div className="flex items-center text-blue-600 font-bold text-sm"><Eye className="w-4 h-4 mr-2" /> Template Preview</div>
                  <div className="flex-1 bg-white rounded-2xl border border-zinc-200 overflow-hidden flex flex-col shadow-inner">
                    <div className="bg-zinc-50 px-4 py-3 border-b border-zinc-200">
                       <h3 className="font-bold text-zinc-800 text-sm">{selectedTemplate.title}</h3>
                    </div>
                    <div className="flex-1 p-4 overflow-y-auto max-h-[300px] relative">
                       <div dangerouslySetInnerHTML={{ __html: (() => {
                         if (!selectedTemplate) return "<i>No content</i>";
                         let html = selectedTemplate.content_body || "";
                         if (selectedTable === 'members_list') {
                           html += `
                             <br/><br/>
                             <p>Location: We meet at Community Toyota, 4701 I-10 East, Baytown, TX, in the conference room on the second floor at NOON.</p>
                             <p>=========================================================</p>
                             <p>You are receiving this email because you opted in via our website.</p>
                             <p>If you have any questions or concerns, please do not hesitate to contact me. Thank you for your continued participation in Baytown Networking Professionals. Don't forget your cold, warm and hot leads.</p>
                             <p>If you wish to unsubscribe to the BNP notifications, click the unsubscribe link below.</p>
                             <p>As always, we hope to see you at the meeting!</p>
                             <p>Best regards, Mike Nebgen (<a href="mailto:mikenebgensenior@gmail.com">mikenebgensenior@gmail.com</a>)</p>
                             <p><a href="#">Unsubscribe</a></p>
                           `;
                         }
                         return html;
                       })() }} />
                    </div>
                  </div>
               </div>
             ) : (
               <div className="flex flex-col items-center justify-center h-full text-zinc-300 italic">
                 <Database className="w-16 h-16 mb-6 opacity-20" />
                 <p className="font-medium text-zinc-400">Select a template to view preview</p>
               </div>
             )}
           </div>
        </div>
      </div>
    </div>
  );
};

export default Campaign;
