import React, { useState, useEffect } from 'react';
import {
  Users,
  UserCheck,
  UserX,
  Mail,
  Send,
  Plus,
  Search,
  Filter,
  Trash2,
  Edit,
  Eye,
  CheckCircle,
  XCircle,
  Clock,
  Loader2,
  FileText,
  AlertCircle,
  RefreshCw,
  Sparkles,
  ChevronLeft,
  ChevronRight,
  BarChart,
  Check,
  Code,
} from 'lucide-react';
import {
  NewsletterSubscriber,
  NewsletterEmailHistory,
  subscribeToSubscribers,
  subscribeToEmailHistory,
  subscribeNewsletter,
  updateSubscriberStatus,
  updateSubscriberNotes,
  deleteSubscriber,
  sendBulkNewsletter,
} from '../../services/newsletterService';
import {
  EmailConfig,
  generateNewsletterHTML,
  subscribeToEmailConfig,
  saveEmailConfig,
  resetEmailCounter,
  getStoredEmailConfig,
} from '../../services/emailService';

export const NewsletterManager: React.FC = () => {
  const [activeSubTab, setActiveSubTab] = useState<'subscribers' | 'compose' | 'history' | 'credentials'>('subscribers');

  // Newsletter EmailJS Config State
  const [emailConfig, setEmailConfig] = useState<EmailConfig>(() => getStoredEmailConfig());
  const [isSavingConfig, setIsSavingConfig] = useState(false);
  const [configNotice, setConfigNotice] = useState<string | null>(null);

  // Subscribers State
  const [subscribers, setSubscribers] = useState<NewsletterSubscriber[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'unsubscribed'>('all');
  const [sourceFilter, setSourceFilter] = useState<'all' | 'footer' | 'checkout' | 'admin'>('all');
  const [selectedSubscriberIds, setSelectedSubscriberIds] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  // History State
  const [history, setHistory] = useState<NewsletterEmailHistory[]>([]);

  // Add Subscriber Modal State
  const [showAddModal, setShowAddModal] = useState(false);
  const [newEmail, setNewEmail] = useState('');
  const [newNotes, setNewNotes] = useState('');
  const [addNotice, setAddNotice] = useState<{ type: 'success' | 'error'; msg: string } | null>(null);
  const [isAdding, setIsAdding] = useState(false);

  // Edit Notes Modal State
  const [editingSubscriber, setEditingSubscriber] = useState<NewsletterSubscriber | null>(null);
  const [editNotesText, setEditNotesText] = useState('');

  // View Subscriber Details Modal
  const [viewingSubscriber, setViewingSubscriber] = useState<NewsletterSubscriber | null>(null);

  // Campaign Composer State
  const [campaignSubject, setCampaignSubject] = useState('');
  const [campaignPreviewText, setCampaignPreviewText] = useState('');
  const [campaignContent, setCampaignContent] = useState('');
  const [campaignFeaturedImage, setCampaignFeaturedImage] = useState('');
  const [campaignButtonLabel, setCampaignButtonLabel] = useState('SHOP ORGANIC NOW');
  const [campaignButtonUrl, setCampaignButtonUrl] = useState('https://timenlife.com');
  const [targetRecipientType, setTargetRecipientType] = useState<'all' | 'selected' | 'single'>('all');
  const [singleTargetEmail, setSingleTargetEmail] = useState('');
  const [showHtmlPreview, setShowHtmlPreview] = useState(false);
  const [useRawHtmlMode, setUseRawHtmlMode] = useState<boolean>(true);

  // Sending Progress State
  const [isSending, setIsSending] = useState(false);
  const [sendProgress, setSendProgress] = useState<{ sent: number; total: number; failed: number } | null>(null);
  const [sendResultNotice, setSendResultNotice] = useState<{ type: 'success' | 'error'; msg: string } | null>(null);

  useEffect(() => {
    setIsLoading(true);
    const unsubSubscribers = subscribeToSubscribers((data) => {
      setSubscribers(data);
      setIsLoading(false);
    });

    const unsubHistory = subscribeToEmailHistory((data) => {
      setHistory(data);
    });

    const unsubEmail = subscribeToEmailConfig((cfg) => {
      setEmailConfig(cfg);
    });

    return () => {
      unsubSubscribers();
      unsubHistory();
      unsubEmail();
    };
  }, []);

  const handleSaveNewsletterEmailConfig = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSavingConfig(true);
    setConfigNotice(null);
    try {
      await saveEmailConfig(emailConfig);
      setConfigNotice('Newsletter EmailJS credentials successfully saved to Firebase & Local Storage!');
      setTimeout(() => setConfigNotice(null), 4000);
    } catch (err) {
      alert('Failed to save Newsletter EmailJS config. Please check connection.');
    } finally {
      setIsSavingConfig(false);
    }
  };

  // Filtered subscribers
  const filteredSubscribers = subscribers.filter((sub) => {
    const matchesSearch =
      sub.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (sub.notes && sub.notes.toLowerCase().includes(searchQuery.toLowerCase()));
    const matchesStatus = statusFilter === 'all' || sub.status === statusFilter;
    const matchesSource = sourceFilter === 'all' || sub.source === sourceFilter;
    return matchesSearch && matchesStatus && matchesSource;
  });

  // Pagination
  const totalPages = Math.ceil(filteredSubscribers.length / pageSize) || 1;
  const paginatedSubscribers = filteredSubscribers.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  // Stats
  const totalSubscribersCount = subscribers.length;
  const activeSubscribersCount = subscribers.filter((s) => s.status === 'active').length;
  const unsubscribedCount = subscribers.filter((s) => s.status === 'unsubscribed').length;
  const totalEmailsSentCount = subscribers.reduce((acc, s) => acc + (s.totalEmailsSent || 0), 0);

  // Checkbox Selection
  const handleSelectAllOnPage = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      const pageIds = paginatedSubscribers.map((s) => s.id);
      setSelectedSubscriberIds(Array.from(new Set([...selectedSubscriberIds, ...pageIds])));
    } else {
      const pageIds = new Set(paginatedSubscribers.map((s) => s.id));
      setSelectedSubscriberIds(selectedSubscriberIds.filter((id) => !pageIds.has(id)));
    }
  };

  const handleToggleSelectOne = (id: string) => {
    if (selectedSubscriberIds.includes(id)) {
      setSelectedSubscriberIds(selectedSubscriberIds.filter((i) => i !== id));
    } else {
      setSelectedSubscriberIds([...selectedSubscriberIds, id]);
    }
  };

  // Add Subscriber
  const handleAddSubscriberSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddNotice(null);
    if (!newEmail.trim() || !newEmail.includes('@')) {
      setAddNotice({ type: 'error', msg: 'Please enter a valid email address.' });
      return;
    }
    setIsAdding(true);
    try {
      const res = await subscribeNewsletter(newEmail, 'admin', newNotes);
      if (res.success) {
        setAddNotice({ type: 'success', msg: res.message });
        setNewEmail('');
        setNewNotes('');
        setTimeout(() => setShowAddModal(false), 1500);
      } else {
        setAddNotice({ type: 'error', msg: res.message });
      }
    } catch (err) {
      setAddNotice({ type: 'error', msg: 'Failed to add subscriber.' });
    } finally {
      setIsAdding(false);
    }
  };

  // Toggle Status
  const handleToggleStatus = async (sub: NewsletterSubscriber) => {
    const newStatus = sub.status === 'active' ? 'unsubscribed' : 'active';
    await updateSubscriberStatus(sub.id, newStatus);
  };

  // Save Notes
  const handleSaveNotes = async () => {
    if (!editingSubscriber) return;
    await updateSubscriberNotes(editingSubscriber.id, editNotesText);
    setEditingSubscriber(null);
  };

  // Delete
  const handleDeleteSubscriber = async (id: string, email: string) => {
    if (confirm(`Are you sure you want to permanently delete "${email}" from subscribers?`)) {
      await deleteSubscriber(id);
      setSelectedSubscriberIds(selectedSubscriberIds.filter((i) => i !== id));
    }
  };

  // Send Newsletter Campaign
  const handleSendCampaign = async () => {
    setSendResultNotice(null);

    if (!campaignSubject.trim()) {
      alert('Please enter a campaign subject.');
      return;
    }
    if (!campaignContent.trim()) {
      alert('Please enter email body content.');
      return;
    }

    let targetRecipients: NewsletterSubscriber[] = [];

    if (targetRecipientType === 'all') {
      targetRecipients = subscribers.filter((s) => s.status === 'active');
    } else if (targetRecipientType === 'selected') {
      targetRecipients = subscribers.filter((s) => selectedSubscriberIds.includes(s.id) && s.status === 'active');
    } else if (targetRecipientType === 'single') {
      const cleanSingle = singleTargetEmail.trim().toLowerCase();
      if (!cleanSingle || !cleanSingle.includes('@')) {
        alert('Please enter a valid single target recipient email.');
        return;
      }
      const existing = subscribers.find((s) => s.email === cleanSingle);
      if (existing) {
        targetRecipients = [existing];
      } else {
        targetRecipients = [
          {
            id: cleanSingle,
            email: cleanSingle,
            status: 'active',
            source: 'admin',
            subscribedAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            totalEmailsSent: 0,
            lastEmailSent: null,
          },
        ];
      }
    }

    if (targetRecipients.length === 0) {
      alert('No active recipients selected to receive this email broadcast.');
      return;
    }

    if (!confirm(`Are you sure you want to send this newsletter to ${targetRecipients.length} subscriber(s)?`)) {
      return;
    }

    // Generate responsive HTML template
    let formattedHtml = generateNewsletterHTML({
      title: campaignSubject,
      content: campaignContent,
      buttonLabel: campaignButtonLabel,
      buttonUrl: campaignButtonUrl,
      featuredImage: campaignFeaturedImage,
      useRawHtml: useRawHtmlMode,
    });

    // Support existing template placeholders {{TITLE}}, {{CONTENT}}, {{BUTTON}}
    formattedHtml = formattedHtml
      .replace(/{{TITLE}}/g, campaignSubject)
      .replace(/{{CONTENT}}/g, campaignContent)
      .replace(/{{BUTTON}}/g, campaignButtonLabel);

    setIsSending(true);
    setSendProgress({ sent: 0, total: targetRecipients.length, failed: 0 });

    try {
      const res = await sendBulkNewsletter(
        targetRecipients,
        campaignSubject,
        formattedHtml,
        (sent, total, failed) => {
          setSendProgress({ sent, total, failed });
        }
      );

      setSendResultNotice({
        type: 'success',
        msg: `Newsletter campaign completed! Successfully sent to ${res.successCount} recipient(s). Failed: ${res.failedCount}`,
      });
    } catch (err) {
      console.error('Error during bulk send:', err);
      setSendResultNotice({
        type: 'error',
        msg: 'Campaign execution encountered an error. Please check EmailJS settings.',
      });
    } finally {
      setIsSending(false);
    }
  };

  return (
    <div className="space-y-6 font-sans text-stone-800">
      
      {/* Module Header & Sub-Tabs Navigation */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 bg-[#1C1814] text-white p-5 rounded-2xl border border-amber-900/40 shadow-lg">
        <div className="space-y-1">
          <div className="flex items-center gap-2 text-[#F8D0BD]">
            <Mail className="w-5 h-5 text-[#C81E3D]" />
            <h2 className="text-xl font-serif font-bold">Newsletter & Bulk Email Marketing</h2>
          </div>
          <p className="text-xs text-stone-300">
            Manage newsletter subscribers, build responsive HTML emails, and send bulk campaigns using existing EmailJS.
          </p>
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <button
            onClick={() => setActiveSubTab('subscribers')}
            className={`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
              activeSubTab === 'subscribers'
                ? 'bg-[#C81E3D] text-white shadow-md'
                : 'bg-[#2A231D] text-stone-300 hover:text-white'
            }`}
          >
            <Users className="w-4 h-4" />
            <span>Subscribers ({subscribers.length})</span>
          </button>

          <button
            onClick={() => setActiveSubTab('compose')}
            className={`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
              activeSubTab === 'compose'
                ? 'bg-[#C81E3D] text-white shadow-md'
                : 'bg-[#2A231D] text-stone-300 hover:text-white'
            }`}
          >
            <Send className="w-4 h-4" />
            <span>Compose Email</span>
          </button>

          <button
            onClick={() => setActiveSubTab('history')}
            className={`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
              activeSubTab === 'history'
                ? 'bg-[#C81E3D] text-white shadow-md'
                : 'bg-[#2A231D] text-stone-300 hover:text-white'
            }`}
          >
            <Clock className="w-4 h-4" />
            <span>Send History ({history.length})</span>
          </button>

          <button
            onClick={() => setActiveSubTab('credentials')}
            className={`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
              activeSubTab === 'credentials'
                ? 'bg-purple-700 text-white shadow-md'
                : 'bg-[#2A231D] text-stone-300 hover:text-white'
            }`}
          >
            <Mail className="w-4 h-4 text-purple-300" />
            <span>EmailJS Credentials</span>
          </button>
        </div>
      </div>

      {/* Dashboard Metrics Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-2xl border border-stone-200 shadow-xs flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center shrink-0">
            <Users className="w-5 h-5" />
          </div>
          <div>
            <span className="text-[11px] font-bold text-stone-500 uppercase tracking-wider block">Total Subscribers</span>
            <span className="text-xl font-extrabold text-stone-900">{totalSubscribersCount}</span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-2xl border border-stone-200 shadow-xs flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
            <UserCheck className="w-5 h-5" />
          </div>
          <div>
            <span className="text-[11px] font-bold text-stone-500 uppercase tracking-wider block">Active Subscribers</span>
            <span className="text-xl font-extrabold text-emerald-700">{activeSubscribersCount}</span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-2xl border border-stone-200 shadow-xs flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center shrink-0">
            <UserX className="w-5 h-5" />
          </div>
          <div>
            <span className="text-[11px] font-bold text-stone-500 uppercase tracking-wider block">Unsubscribed</span>
            <span className="text-xl font-extrabold text-rose-600">{unsubscribedCount}</span>
          </div>
        </div>

        <div className="bg-white p-4 rounded-2xl border border-stone-200 shadow-xs flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-700 flex items-center justify-center shrink-0">
            <Send className="w-5 h-5" />
          </div>
          <div>
            <span className="text-[11px] font-bold text-stone-500 uppercase tracking-wider block">Total Emails Delivered</span>
            <span className="text-xl font-extrabold text-amber-900">{totalEmailsSentCount}</span>
          </div>
        </div>
      </div>

      {/* SUB-TAB 1: SUBSCRIBERS MANAGEMENT LIST */}
      {activeSubTab === 'subscribers' && (
        <div className="bg-white rounded-2xl border border-stone-200 shadow-sm p-6 space-y-5">
          
          {/* Controls Bar */}
          <div className="flex flex-col md:flex-row items-stretch md:items-center justify-between gap-4">
            
            {/* Search & Filters */}
            <div className="flex flex-wrap items-center gap-3 flex-1">
              <div className="relative flex-1 min-w-[200px]">
                <Search className="w-4 h-4 text-stone-400 absolute left-3 top-3" />
                <input
                  type="text"
                  placeholder="Search by email or notes..."
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="w-full pl-9 pr-3 py-2 bg-stone-50 border border-stone-200 rounded-xl text-xs focus:outline-none focus:ring-2 focus:ring-[#C81E3D]"
                />
              </div>

              <select
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value as any);
                  setCurrentPage(1);
                }}
                className="px-3 py-2 bg-stone-50 border border-stone-200 rounded-xl text-xs font-medium focus:outline-none focus:ring-2 focus:ring-[#C81E3D]"
              >
                <option value="all">All Statuses</option>
                <option value="active">Active Only</option>
                <option value="unsubscribed">Unsubscribed</option>
              </select>

              <select
                value={sourceFilter}
                onChange={(e) => {
                  setSourceFilter(e.target.value as any);
                  setCurrentPage(1);
                }}
                className="px-3 py-2 bg-stone-50 border border-stone-200 rounded-xl text-xs font-medium focus:outline-none focus:ring-2 focus:ring-[#C81E3D]"
              >
                <option value="all">All Sources</option>
                <option value="footer">Footer Form</option>
                <option value="checkout">Order Checkout</option>
                <option value="admin">Admin Added</option>
              </select>
            </div>

            {/* Actions */}
            <div className="flex items-center gap-2 shrink-0">
              {selectedSubscriberIds.length > 0 && (
                <button
                  onClick={() => {
                    setActiveSubTab('compose');
                    setTargetRecipientType('selected');
                  }}
                  className="px-3.5 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm cursor-pointer"
                >
                  <Send className="w-3.5 h-3.5" />
                  <span>Send Email to Selected ({selectedSubscriberIds.length})</span>
                </button>
              )}

              <button
                onClick={() => {
                  setShowAddModal(true);
                  setAddNotice(null);
                }}
                className="px-4 py-2 bg-[#C81E3D] hover:bg-[#a81631] text-white rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm cursor-pointer"
              >
                <Plus className="w-4 h-4" />
                <span>Add Subscriber</span>
              </button>
            </div>
          </div>

          {/* Table */}
          <div className="overflow-x-auto border border-stone-200 rounded-2xl">
            <table className="w-full text-left text-xs border-collapse">
              <thead>
                <tr className="bg-stone-100/80 text-stone-700 uppercase text-[10px] tracking-wider font-extrabold border-b border-stone-200">
                  <th className="p-3.5 w-10 text-center">
                    <input
                      type="checkbox"
                      onChange={handleSelectAllOnPage}
                      checked={
                        paginatedSubscribers.length > 0 &&
                        paginatedSubscribers.every((s) => selectedSubscriberIds.includes(s.id))
                      }
                      className="accent-[#C81E3D] cursor-pointer"
                    />
                  </th>
                  <th className="p-3.5">Email Address</th>
                  <th className="p-3.5">Source</th>
                  <th className="p-3.5">Subscribed Date</th>
                  <th className="p-3.5">Status</th>
                  <th className="p-3.5 text-center">Emails Sent</th>
                  <th className="p-3.5">Last Email Sent</th>
                  <th className="p-3.5 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-stone-100">
                {isLoading ? (
                  <tr>
                    <td colSpan={8} className="p-8 text-center text-stone-500">
                      <div className="flex items-center justify-center gap-2">
                        <Loader2 className="w-5 h-5 animate-spin text-[#C81E3D]" />
                        <span>Loading subscribers list...</span>
                      </div>
                    </td>
                  </tr>
                ) : paginatedSubscribers.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="p-8 text-center text-stone-500">
                      No subscribers found matching criteria.
                    </td>
                  </tr>
                ) : (
                  paginatedSubscribers.map((sub) => {
                    const isSelected = selectedSubscriberIds.includes(sub.id);
                    return (
                      <tr
                        key={sub.id}
                        className={`hover:bg-amber-50/40 transition-colors ${
                          isSelected ? 'bg-amber-50/70' : ''
                        }`}
                      >
                        <td className="p-3.5 text-center">
                          <input
                            type="checkbox"
                            checked={isSelected}
                            onChange={() => handleToggleSelectOne(sub.id)}
                            className="accent-[#C81E3D] cursor-pointer"
                          />
                        </td>
                        <td className="p-3.5 font-medium text-stone-900">
                          <div>{sub.email}</div>
                          {sub.notes && (
                            <div className="text-[10px] text-stone-500 italic mt-0.5 truncate max-w-[200px]">
                              Note: {sub.notes}
                            </div>
                          )}
                        </td>
                        <td className="p-3.5">
                          <span className="capitalize px-2 py-0.5 rounded-md text-[10px] font-bold bg-stone-100 text-stone-700">
                            {sub.source}
                          </span>
                        </td>
                        <td className="p-3.5 text-stone-600">
                          {new Date(sub.subscribedAt).toLocaleDateString('en-PK', {
                            day: 'numeric',
                            month: 'short',
                            year: 'numeric',
                          })}
                        </td>
                        <td className="p-3.5">
                          <span
                            className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase ${
                              sub.status === 'active'
                                ? 'bg-emerald-100 text-emerald-800'
                                : 'bg-rose-100 text-rose-800'
                            }`}
                          >
                            {sub.status === 'active' ? (
                              <CheckCircle className="w-3 h-3 text-emerald-600" />
                            ) : (
                              <XCircle className="w-3 h-3 text-rose-600" />
                            )}
                            <span>{sub.status}</span>
                          </span>
                        </td>
                        <td className="p-3.5 text-center font-bold text-stone-800">
                          {sub.totalEmailsSent || 0}
                        </td>
                        <td className="p-3.5 text-stone-500 text-[11px]">
                          {sub.lastEmailSent
                            ? new Date(sub.lastEmailSent).toLocaleDateString('en-PK', {
                                day: 'numeric',
                                month: 'short',
                              })
                            : 'Never'}
                        </td>
                        <td className="p-3.5 text-right">
                          <div className="flex items-center justify-end gap-1">
                            <button
                              onClick={() => setViewingSubscriber(sub)}
                              title="View Details"
                              className="p-1.5 text-stone-600 hover:text-stone-900 hover:bg-stone-100 rounded-lg transition-colors cursor-pointer"
                            >
                              <Eye className="w-4 h-4" />
                            </button>

                            <button
                              onClick={() => {
                                setEditingSubscriber(sub);
                                setEditNotesText(sub.notes || '');
                              }}
                              title="Edit Notes"
                              className="p-1.5 text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-lg transition-colors cursor-pointer"
                            >
                              <Edit className="w-4 h-4" />
                            </button>

                            <button
                              onClick={() => handleToggleStatus(sub)}
                              title={sub.status === 'active' ? 'Unsubscribe' : 'Re-activate'}
                              className={`p-1.5 rounded-lg transition-colors cursor-pointer ${
                                sub.status === 'active'
                                  ? 'text-amber-600 hover:text-amber-800 hover:bg-amber-50'
                                  : 'text-emerald-600 hover:text-emerald-800 hover:bg-emerald-50'
                              }`}
                            >
                              {sub.status === 'active' ? <UserX className="w-4 h-4" /> : <UserCheck className="w-4 h-4" />}
                            </button>

                            <button
                              onClick={() => handleDeleteSubscriber(sub.id, sub.email)}
                              title="Delete Subscriber"
                              className="p-1.5 text-rose-600 hover:text-rose-800 hover:bg-rose-50 rounded-lg transition-colors cursor-pointer"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination Footer */}
          <div className="flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-stone-600 pt-2">
            <div>
              Showing {filteredSubscribers.length > 0 ? (currentPage - 1) * pageSize + 1 : 0} to{' '}
              {Math.min(currentPage * pageSize, filteredSubscribers.length)} of {filteredSubscribers.length} subscribers
            </div>

            <div className="flex items-center gap-2">
              <button
                disabled={currentPage === 1}
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                className="px-3 py-1.5 border border-stone-200 rounded-lg bg-stone-50 hover:bg-stone-100 disabled:opacity-40 transition-colors cursor-pointer"
              >
                Previous
              </button>
              <span className="font-bold px-2">
                Page {currentPage} of {totalPages}
              </span>
              <button
                disabled={currentPage >= totalPages}
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                className="px-3 py-1.5 border border-stone-200 rounded-lg bg-stone-50 hover:bg-stone-100 disabled:opacity-40 transition-colors cursor-pointer"
              >
                Next
              </button>
            </div>
          </div>
        </div>
      )}

      {/* SUB-TAB 2: CAMPAIGN BUILDER & SENDER */}
      {activeSubTab === 'compose' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
          
          {/* Form Side */}
          <div className="lg:col-span-7 bg-white p-6 rounded-2xl border border-stone-200 shadow-sm space-y-5">
            <div className="flex items-center justify-between border-b border-stone-200 pb-3">
              <h3 className="text-base font-bold text-stone-900 flex items-center gap-2">
                <Send className="w-5 h-5 text-[#C81E3D]" />
                <span>Create & Broadcast Campaign</span>
              </h3>
              <button
                onClick={() => setShowHtmlPreview(!showHtmlPreview)}
                className="px-3 py-1.5 bg-stone-100 hover:bg-stone-200 text-stone-800 rounded-lg text-xs font-bold transition-colors cursor-pointer"
              >
                {showHtmlPreview ? 'Hide HTML Preview' : 'Live Preview'}
              </button>
            </div>

            {/* Target Recipients Selection */}
            <div className="space-y-2 bg-amber-50/60 p-4 rounded-xl border border-amber-200/80">
              <label className="block text-xs font-bold text-amber-950 uppercase tracking-wider">
                1. Select Target Recipients
              </label>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                <label className="flex items-center gap-2 p-2.5 bg-white border border-stone-200 rounded-xl cursor-pointer text-xs font-medium">
                  <input
                    type="radio"
                    name="recipientType"
                    checked={targetRecipientType === 'all'}
                    onChange={() => setTargetRecipientType('all')}
                    className="accent-[#C81E3D]"
                  />
                  <span>All Active ({activeSubscribersCount})</span>
                </label>

                <label className="flex items-center gap-2 p-2.5 bg-white border border-stone-200 rounded-xl cursor-pointer text-xs font-medium">
                  <input
                    type="radio"
                    name="recipientType"
                    checked={targetRecipientType === 'selected'}
                    onChange={() => setTargetRecipientType('selected')}
                    className="accent-[#C81E3D]"
                  />
                  <span>Selected ({selectedSubscriberIds.length})</span>
                </label>

                <label className="flex items-center gap-2 p-2.5 bg-white border border-stone-200 rounded-xl cursor-pointer text-xs font-medium">
                  <input
                    type="radio"
                    name="recipientType"
                    checked={targetRecipientType === 'single'}
                    onChange={() => setTargetRecipientType('single')}
                    className="accent-[#C81E3D]"
                  />
                  <span>Single Test Email</span>
                </label>
              </div>

              {targetRecipientType === 'single' && (
                <div className="pt-2">
                  <input
                    type="email"
                    placeholder="Enter test email address..."
                    value={singleTargetEmail}
                    onChange={(e) => setSingleTargetEmail(e.target.value)}
                    className="w-full px-3 py-2 bg-white border border-stone-300 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
                  />
                </div>
              )}
            </div>

            {/* Template Mode Selection Bar */}
            <div className="bg-stone-50 p-3.5 rounded-xl border border-stone-200 space-y-2">
              <label className="block text-xs font-bold text-stone-800 flex items-center justify-between">
                <span>2. Email Template Mode</span>
                <span className="text-[10px] text-stone-500 font-normal">No Auto Header/Footer vs Branded Frame</span>
              </label>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                <button
                  type="button"
                  onClick={() => setUseRawHtmlMode(true)}
                  className={`px-3 py-2.5 rounded-xl text-xs font-bold flex items-center justify-center gap-2 border transition-all cursor-pointer ${
                    useRawHtmlMode
                      ? 'bg-[#C81E3D] text-white border-[#C81E3D] shadow-sm'
                      : 'bg-white text-stone-700 border-stone-300 hover:bg-stone-100'
                  }`}
                >
                  <Code className="w-4 h-4" />
                  <span>Raw Custom HTML (No Header & No Footer)</span>
                </button>

                <button
                  type="button"
                  onClick={() => setUseRawHtmlMode(false)}
                  className={`px-3 py-2.5 rounded-xl text-xs font-bold flex items-center justify-center gap-2 border transition-all cursor-pointer ${
                    !useRawHtmlMode
                      ? 'bg-[#C81E3D] text-white border-[#C81E3D] shadow-sm'
                      : 'bg-white text-stone-700 border-stone-300 hover:bg-stone-100'
                  }`}
                >
                  <Sparkles className="w-4 h-4 text-amber-500" />
                  <span>Time N Life Branded Frame</span>
                </button>
              </div>
              <p className="text-[11px] text-stone-600 font-medium leading-relaxed">
                {useRawHtmlMode
                  ? '⚡ Raw HTML Code Mode: Type or paste your own complete HTML code. Zero automatic headers, logos, or footers will be attached.'
                  : '🎨 Branded Frame Mode: Automatically encloses your written text inside the official Time N Life header, logo, and footer.'}
              </p>
            </div>

            {/* Campaign Quick Presets */}
            <div className="bg-amber-50/70 p-3.5 rounded-xl border border-amber-200/80 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-[11px] font-bold text-amber-950 uppercase tracking-wider flex items-center gap-1.5">
                  <Sparkles className="w-3.5 h-3.5 text-amber-700" />
                  <span>Quick Template Presets</span>
                </span>
                <span className="text-[10px] text-amber-800 font-medium">Click to load sample</span>
              </div>
              <div className="flex flex-wrap gap-2 text-xs">
                <button
                  type="button"
                  onClick={() => {
                    setUseRawHtmlMode(true);
                    setCampaignSubject('🌿 Special Organic Sidr Honey Offer | Time N Life');
                    setCampaignContent(`<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Special Honey Offer</title>
</head>
<body style="margin: 0; padding: 20px; font-family: Arial, sans-serif; background-color: #f8fafc; color: #1e293b;">
  <div style="max-width: 600px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 12px; border: 1px solid #e2e8f0; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
    <h1 style="color: #c81e3d; margin-top: 0; font-size: 22px;">Pure Organic Sidr Honey Special Offer</h1>
    <p style="font-size: 15px; line-height: 1.6; color: #334155;">
      Dear Customer,<br/><br/>
      Enjoy 15% OFF on our 100% Pure Certified Organic Sidr Honey and Premium Dry Fruits collection!
    </p>
    <p style="font-size: 14px; background-color: #fef2f2; border: 1px dashed #f87171; padding: 12px; border-radius: 8px; color: #991b1b; text-align: center; font-weight: bold;">
      Use Coupon Code: NATURAL15 at checkout
    </p>
    <div style="text-align: center; margin: 25px 0 10px 0;">
      <a href="https://timenlife.com" style="background: #c81e3d; color: #ffffff; padding: 12px 28px; text-decoration: none; font-weight: bold; border-radius: 8px; display: inline-block;">
        ORDER ONLINE NOW
      </a>
    </div>
  </div>
</body>
</html>`);
                  }}
                  className="px-2.5 py-1 bg-white hover:bg-amber-100 border border-amber-300 rounded-lg text-amber-900 font-semibold transition-colors cursor-pointer flex items-center gap-1"
                >
                  <Code className="w-3.5 h-3.5 text-amber-700" />
                  <span>Custom Raw HTML Sample</span>
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setUseRawHtmlMode(false);
                    setCampaignSubject('✨ New Stock Arrival: Organic Shilajit & Herbal Teas | Time N Life');
                    setCampaignContent(
                      `Hello Friend,\n\nFresh stock of 100% Natural Organic Shilajit Resin and Premium Herbal Teas has just arrived at Time N Life!\n\nBoost your energy, immunity, and vitality with nature's finest ingredients. Guaranteed 100% pure & lab tested.\n\nOrder online today and enjoy fast Cash on Delivery anywhere in Pakistan.`
                    );
                    setCampaignButtonLabel('EXPLORE NEW ARRIVALS');
                    setCampaignButtonUrl('https://timenlife.com');
                  }}
                  className="px-2.5 py-1 bg-white hover:bg-amber-100 border border-amber-300 rounded-lg text-amber-900 font-semibold transition-colors cursor-pointer"
                >
                  🌱 Standard Branded Text
                </button>
              </div>
            </div>

            {/* Campaign Fields */}
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-stone-800 mb-1">
                  3. Email Subject Line *
                </label>
                <input
                  type="text"
                  placeholder="e.g. 🌿 Exclusive 20% OFF Organic Honey & Nuts | Time N Life"
                  value={campaignSubject}
                  onChange={(e) => setCampaignSubject(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-stone-50 border border-stone-200 rounded-xl text-xs font-medium focus:ring-2 focus:ring-[#C81E3D] outline-none"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-stone-800 mb-1 flex items-center justify-between">
                  <span>
                    4. Email Code / Message Content * ({useRawHtmlMode ? 'Custom HTML Code' : 'Plain Text / Body'})
                  </span>
                  <span className="text-[10px] font-normal text-stone-500">
                    {useRawHtmlMode ? 'Direct Raw HTML Mode' : 'Branded Wrapper Mode'}
                  </span>
                </label>
                <textarea
                  rows={10}
                  placeholder={
                    useRawHtmlMode
                      ? "Write or paste your complete HTML template code here (e.g. <html><body><h1>Hello</h1></body></html>). No header or footer will be attached!"
                      : "Write your email text here in simple paragraphs. The system will automatically place it inside the Time N Life header and footer template."
                  }
                  value={campaignContent}
                  onChange={(e) => setCampaignContent(e.target.value)}
                  className="w-full p-3.5 bg-stone-50 border border-stone-200 rounded-xl text-xs font-mono leading-relaxed focus:ring-2 focus:ring-[#C81E3D] outline-none"
                />
              </div>

              {/* Optional Advanced Customizations */}
              {!useRawHtmlMode && (
                <details className="bg-stone-50 p-3.5 rounded-xl border border-stone-200 text-xs">
                  <summary className="font-bold text-stone-700 cursor-pointer select-none">
                    ⚙️ Optional Branded Frame Customizations (Image & CTA Button)
                  </summary>
                  <div className="mt-3 space-y-3 pt-2 border-t border-stone-200">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs font-bold text-stone-700 mb-1">
                          Featured Banner Image URL (Optional)
                        </label>
                        <input
                          type="url"
                          placeholder="https://example.com/banner.jpg"
                          value={campaignFeaturedImage}
                          onChange={(e) => setCampaignFeaturedImage(e.target.value)}
                          className="w-full px-3 py-2 bg-white border border-stone-200 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
                        />
                      </div>

                      <div>
                        <label className="block text-xs font-bold text-stone-700 mb-1">
                          CTA Button Label
                        </label>
                        <input
                          type="text"
                          placeholder="e.g. SHOP NOW"
                          value={campaignButtonLabel}
                          onChange={(e) => setCampaignButtonLabel(e.target.value)}
                          className="w-full px-3 py-2 bg-white border border-stone-200 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
                        />
                      </div>
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-stone-700 mb-1">
                        CTA Button Link URL
                      </label>
                      <input
                        type="url"
                        placeholder="https://timenlife.com"
                        value={campaignButtonUrl}
                        onChange={(e) => setCampaignButtonUrl(e.target.value)}
                        className="w-full px-3 py-2 bg-white border border-stone-200 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
                      />
                    </div>
                  </div>
                </details>
              )}
            </div>

            {/* Sending Progress Display */}
            {isSending && sendProgress && (
              <div className="bg-amber-50 border border-amber-300 p-4 rounded-xl space-y-2">
                <div className="flex justify-between items-center text-xs font-bold text-amber-900">
                  <div className="flex items-center gap-2">
                    <Loader2 className="w-4 h-4 animate-spin text-[#C81E3D]" />
                    <span>Broadcasting Newsletter...</span>
                  </div>
                  <span>
                    {sendProgress.sent} / {sendProgress.total} Sent ({sendProgress.failed} Failed)
                  </span>
                </div>
                <div className="w-full bg-amber-200 rounded-full h-2.5 overflow-hidden">
                  <div
                    className="bg-[#C81E3D] h-2.5 transition-all duration-200"
                    style={{
                      width: `${Math.round(((sendProgress.sent + sendProgress.failed) / sendProgress.total) * 100)}%`,
                    }}
                  />
                </div>
              </div>
            )}

            {sendResultNotice && (
              <div
                className={`p-3.5 rounded-xl text-xs font-semibold flex items-center gap-2 ${
                  sendResultNotice.type === 'success'
                    ? 'bg-emerald-50 text-emerald-800 border border-emerald-200'
                    : 'bg-rose-50 text-rose-800 border border-rose-200'
                }`}
              >
                {sendResultNotice.type === 'success' ? (
                  <CheckCircle className="w-4 h-4 text-emerald-600 shrink-0" />
                ) : (
                  <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
                )}
                <span>{sendResultNotice.msg}</span>
              </div>
            )}

            {/* Send Action Button */}
            <button
              onClick={handleSendCampaign}
              disabled={isSending}
              className="w-full py-3.5 bg-[#C81E3D] hover:bg-[#a81631] text-white font-bold text-xs uppercase tracking-wider rounded-xl transition-all duration-200 flex items-center justify-center gap-2 shadow-md hover:shadow-rose-900/30 active:scale-98 disabled:opacity-50 cursor-pointer"
            >
              {isSending ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span>Sending Campaign in Queue...</span>
                </>
              ) : (
                <>
                  <Send className="w-4 h-4" />
                  <span>SEND NEWSLETTER CAMPAIGN NOW</span>
                </>
              )}
            </button>
          </div>

          {/* Live Template Preview Side */}
          <div className="lg:col-span-5 bg-stone-100 p-4 rounded-2xl border border-stone-300 space-y-3">
            <h4 className="text-xs font-bold text-stone-700 uppercase tracking-wider flex items-center gap-2 border-b border-stone-200 pb-2">
              <Sparkles className="w-4 h-4 text-amber-800" />
              <span>Live Email Template Preview</span>
            </h4>

            <div className="bg-white rounded-xl shadow-md border border-stone-200 overflow-hidden max-h-[600px] overflow-y-auto">
              <iframe
                title="Newsletter Live Preview"
                srcDoc={generateNewsletterHTML({
                  title: campaignSubject || 'Your Newsletter Subject Line Here',
                  content: campaignContent || '<p style="font-family: Arial; padding: 20px; color: #64748b;">Write or paste your custom HTML code here...</p>',
                  buttonLabel: campaignButtonLabel,
                  buttonUrl: campaignButtonUrl,
                  featuredImage: campaignFeaturedImage,
                  useRawHtml: useRawHtmlMode,
                })}
                className="w-full h-[550px] border-none"
              />
            </div>
          </div>

        </div>
      )}

      {/* SUB-TAB 3: EMAIL HISTORY LOG */}
      {activeSubTab === 'history' && (
        <div className="bg-white rounded-2xl border border-stone-200 shadow-sm p-6 space-y-4">
          <h3 className="text-sm font-bold text-stone-900 flex items-center gap-2 border-b border-stone-200 pb-2">
            <Clock className="w-4 h-4 text-[#C81E3D]" />
            <span>Past Newsletter Campaign Broadcasts</span>
          </h3>

          <div className="overflow-x-auto border border-stone-200 rounded-xl">
            <table className="w-full text-left text-xs border-collapse">
              <thead>
                <tr className="bg-stone-100/80 text-stone-700 uppercase text-[10px] tracking-wider font-extrabold border-b border-stone-200">
                  <th className="p-3">Broadcast Ref</th>
                  <th className="p-3">Subject</th>
                  <th className="p-3">Recipients</th>
                  <th className="p-3">Success</th>
                  <th className="p-3">Failed</th>
                  <th className="p-3">Started At</th>
                  <th className="p-3">Created By</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-stone-100">
                {history.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="p-8 text-center text-stone-500">
                      No broadcast history recorded yet.
                    </td>
                  </tr>
                ) : (
                  history.map((item) => (
                    <tr key={item.id} className="hover:bg-amber-50/40 transition-colors">
                      <td className="p-3 font-mono font-bold text-stone-800">{item.id}</td>
                      <td className="p-3 font-medium text-stone-900">{item.subject}</td>
                      <td className="p-3 font-bold text-stone-800">{item.totalRecipients}</td>
                      <td className="p-3 font-bold text-emerald-700">{item.successCount}</td>
                      <td className="p-3 font-bold text-rose-600">{item.failedCount}</td>
                      <td className="p-3 text-stone-600">
                        {new Date(item.startedAt).toLocaleString('en-PK', {
                          day: 'numeric',
                          month: 'short',
                          year: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </td>
                      <td className="p-3 text-stone-500">{item.createdBy}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* SUB-TAB 4: DEDICATED NEWSLETTER EMAILJS CREDENTIALS */}
      {activeSubTab === 'credentials' && (
        <div className="bg-white rounded-2xl border border-purple-200 shadow-sm p-6 sm:p-8 space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-purple-100 pb-5">
            <div>
              <h3 className="text-lg font-bold font-serif text-slate-900 flex items-center gap-2">
                <Mail className="w-5 h-5 text-purple-600" />
                <span>Dedicated Newsletter EmailJS Account</span>
              </h3>
              <p className="text-xs text-slate-500 mt-1">
                Configure dedicated EmailJS credentials stored in Firebase Firestore so marketing campaigns use a separate quota.
              </p>
            </div>

            <div className="flex items-center gap-3 bg-purple-50 border border-purple-200 rounded-xl px-4 py-2">
              <div>
                <div className="text-[10px] font-bold text-purple-800 uppercase tracking-wider">Newsletter Quota</div>
                <div className="text-xs font-mono font-bold text-slate-800">
                  {emailConfig.newsletterUsed || 0} / {emailConfig.newsletterLimit || 200}
                  <span className="text-[11px] text-purple-800 font-sans ml-1.5 font-semibold">
                    ({Math.max(0, (emailConfig.newsletterLimit || 200) - (emailConfig.newsletterUsed || 0))} Left)
                  </span>
                </div>
              </div>
              <button
                type="button"
                onClick={async () => {
                  if (confirm('Are you sure you want to reset the Newsletter email counter to 0?')) {
                    await resetEmailCounter('newsletter');
                  }
                }}
                className="px-2.5 py-1 bg-purple-200 hover:bg-purple-300 text-purple-900 rounded-lg text-[11px] font-bold transition-all cursor-pointer"
              >
                Reset Count
              </button>
            </div>
          </div>

          {configNotice && (
            <div className="p-4 bg-emerald-100 border border-emerald-300 text-emerald-900 rounded-2xl flex items-center gap-2 text-xs font-bold animate-in fade-in">
              <Check className="w-4 h-4 text-emerald-700" />
              <span>{configNotice}</span>
            </div>
          )}

          <form onSubmit={handleSaveNewsletterEmailConfig} className="space-y-6 max-w-3xl">
            {/* Separate Toggle */}
            <div className="p-4 bg-purple-50/70 border border-purple-200 rounded-2xl flex items-start gap-3">
              <input
                type="checkbox"
                id="useSeparateNewsletterAccount"
                checked={Boolean(emailConfig.useSeparateNewsletterAccount)}
                onChange={(e) => setEmailConfig({ ...emailConfig, useSeparateNewsletterAccount: e.target.checked })}
                className="mt-0.5 w-4 h-4 text-purple-600 accent-purple-600 rounded border-slate-300 focus:ring-purple-600 cursor-pointer"
              />
              <div>
                <label htmlFor="useSeparateNewsletterAccount" className="font-bold text-slate-900 text-sm cursor-pointer block">
                  Use Dedicated EmailJS Credentials for Newsletter Marketing
                </label>
                <p className="text-xs text-slate-600 mt-0.5">
                  When enabled, all bulk newsletters &amp; promotional emails will use these dedicated credentials, preserving your transactional order email limits.
                </p>
              </div>
            </div>

            {emailConfig.useSeparateNewsletterAccount ? (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-5 animate-in fade-in">
                {/* Public Key */}
                <div className="space-y-1.5">
                  <label className="block text-xs font-bold text-slate-800 uppercase tracking-wider">
                    Newsletter Public Key *
                  </label>
                  <input
                    type="text"
                    required={emailConfig.useSeparateNewsletterAccount}
                    placeholder="e.g. Newsletter_Public_Key_Here"
                    value={emailConfig.newsletterPublicKey || ''}
                    onChange={(e) => setEmailConfig({ ...emailConfig, newsletterPublicKey: e.target.value.trim() })}
                    className="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-300 rounded-xl text-xs font-mono font-medium focus:bg-white focus:ring-2 focus:ring-purple-600 outline-none"
                  />
                  <p className="text-[11px] text-slate-500">Account &gt; General Settings (Newsletter account)</p>
                </div>

                {/* Service ID */}
                <div className="space-y-1.5">
                  <label className="block text-xs font-bold text-slate-800 uppercase tracking-wider">
                    Newsletter Service ID *
                  </label>
                  <input
                    type="text"
                    required={emailConfig.useSeparateNewsletterAccount}
                    placeholder="e.g. service_newsletter123"
                    value={emailConfig.newsletterServiceId || ''}
                    onChange={(e) => setEmailConfig({ ...emailConfig, newsletterServiceId: e.target.value.trim() })}
                    className="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-300 rounded-xl text-xs font-mono font-medium focus:bg-white focus:ring-2 focus:ring-purple-600 outline-none"
                  />
                  <p className="text-[11px] text-slate-500">EmailJS Email Services tab for Newsletter</p>
                </div>

                {/* Template ID */}
                <div className="space-y-1.5">
                  <label className="block text-xs font-bold text-slate-800 uppercase tracking-wider">
                    Newsletter Template ID *
                  </label>
                  <input
                    type="text"
                    required={emailConfig.useSeparateNewsletterAccount}
                    placeholder="e.g. template_newsletter456"
                    value={emailConfig.newsletterTemplateId || ''}
                    onChange={(e) => setEmailConfig({ ...emailConfig, newsletterTemplateId: e.target.value.trim() })}
                    className="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-300 rounded-xl text-xs font-mono font-medium focus:bg-white focus:ring-2 focus:ring-purple-600 outline-none"
                  />
                  <p className="text-[11px] text-slate-500">Template ID with {'{{TITLE}}'}, {'{{CONTENT}}'}, {'{{BUTTON}}'} variables</p>
                </div>

                {/* Quota Limit */}
                <div className="space-y-1.5">
                  <label className="block text-xs font-bold text-slate-800 uppercase tracking-wider">
                    Monthly Email Limit (Quota) *
                  </label>
                  <input
                    type="number"
                    required={emailConfig.useSeparateNewsletterAccount}
                    min={0}
                    placeholder="200"
                    value={emailConfig.newsletterLimit ?? 200}
                    onChange={(e) => setEmailConfig({ ...emailConfig, newsletterLimit: parseInt(e.target.value) || 0 })}
                    className="w-full px-3.5 py-2.5 bg-slate-50 border border-slate-300 rounded-xl text-xs font-mono font-bold focus:bg-white focus:ring-2 focus:ring-purple-600 outline-none"
                  />
                  <p className="text-[11px] text-slate-500">Free EmailJS account limit (e.g. 200)</p>
                </div>
              </div>
            ) : (
              <p className="text-xs text-stone-500 italic p-4 bg-stone-50 rounded-xl border border-stone-200">
                Disabled: Bulk newsletters will fallback to sharing your primary transactional order email quota.
              </p>
            )}

            <div className="pt-2">
              <button
                type="submit"
                disabled={isSavingConfig}
                className="px-6 py-3 bg-purple-700 hover:bg-purple-800 text-white font-bold text-xs uppercase tracking-wider rounded-xl shadow-md transition-colors flex items-center gap-2 cursor-pointer disabled:opacity-50"
              >
                {isSavingConfig ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span>Saving to Firebase...</span>
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4" />
                    <span>Save Newsletter EmailJS Credentials</span>
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* MODAL: ADD SUBSCRIBER */}
      {showAddModal && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white max-w-md w-full rounded-2xl p-6 shadow-2xl space-y-4 border border-stone-200">
            <div className="flex justify-between items-center border-b border-stone-200 pb-3">
              <h3 className="text-base font-bold text-stone-900 flex items-center gap-2">
                <Plus className="w-5 h-5 text-[#C81E3D]" />
                <span>Add New Subscriber</span>
              </h3>
              <button
                onClick={() => setShowAddModal(false)}
                className="text-stone-400 hover:text-stone-700 font-bold"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleAddSubscriberSubmit} className="space-y-4">
              <div>
                <label className="block text-xs font-bold text-stone-700 mb-1">Email Address *</label>
                <input
                  type="email"
                  required
                  placeholder="subscriber@example.com"
                  value={newEmail}
                  onChange={(e) => setNewEmail(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-stone-50 border border-stone-200 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-stone-700 mb-1">Notes / Tag (Optional)</label>
                <input
                  type="text"
                  placeholder="e.g. VIP Customer, Wholesale Inquiry..."
                  value={newNotes}
                  onChange={(e) => setNewNotes(e.target.value)}
                  className="w-full px-3 py-2 bg-stone-50 border border-stone-200 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
                />
              </div>

              {addNotice && (
                <div
                  className={`p-3 rounded-xl text-xs font-semibold ${
                    addNotice.type === 'success'
                      ? 'bg-emerald-50 text-emerald-800 border border-emerald-200'
                      : 'bg-rose-50 text-rose-800 border border-rose-200'
                  }`}
                >
                  {addNotice.msg}
                </div>
              )}

              <div className="flex justify-end gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setShowAddModal(false)}
                  className="px-4 py-2 bg-stone-100 hover:bg-stone-200 text-stone-700 rounded-xl text-xs font-bold cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isAdding}
                  className="px-5 py-2 bg-[#C81E3D] hover:bg-[#a81631] text-white rounded-xl text-xs font-bold flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                >
                  {isAdding ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                  <span>Save Subscriber</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* MODAL: EDIT NOTES */}
      {editingSubscriber && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white max-w-md w-full rounded-2xl p-6 shadow-2xl space-y-4 border border-stone-200">
            <div className="flex justify-between items-center border-b border-stone-200 pb-3">
              <h3 className="text-sm font-bold text-stone-900">
                Edit Notes for <span className="text-[#C81E3D] font-mono">{editingSubscriber.email}</span>
              </h3>
              <button
                onClick={() => setEditingSubscriber(null)}
                className="text-stone-400 hover:text-stone-700 font-bold"
              >
                ✕
              </button>
            </div>

            <div>
              <label className="block text-xs font-bold text-stone-700 mb-1">Subscriber Notes</label>
              <textarea
                rows={3}
                value={editNotesText}
                onChange={(e) => setEditNotesText(e.target.value)}
                placeholder="Enter custom subscriber tag or customer note..."
                className="w-full p-3 bg-stone-50 border border-stone-200 rounded-xl text-xs focus:ring-2 focus:ring-[#C81E3D] outline-none"
              />
            </div>

            <div className="flex justify-end gap-2">
              <button
                onClick={() => setEditingSubscriber(null)}
                className="px-4 py-2 bg-stone-100 hover:bg-stone-200 text-stone-700 rounded-xl text-xs font-bold cursor-pointer"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveNotes}
                className="px-5 py-2 bg-[#C81E3D] hover:bg-[#a81631] text-white rounded-xl text-xs font-bold cursor-pointer"
              >
                Save Changes
              </button>
            </div>
          </div>
        </div>
      )}

      {/* MODAL: VIEW DETAILS */}
      {viewingSubscriber && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200">
          <div className="bg-white max-w-md w-full rounded-2xl p-6 shadow-2xl space-y-4 border border-stone-200 text-xs">
            <div className="flex justify-between items-center border-b border-stone-200 pb-3">
              <h3 className="text-sm font-bold text-stone-900">Subscriber Profile Details</h3>
              <button
                onClick={() => setViewingSubscriber(null)}
                className="text-stone-400 hover:text-stone-700 font-bold"
              >
                ✕
              </button>
            </div>

            <div className="space-y-2 bg-stone-50 p-4 rounded-xl border border-stone-200 font-medium text-stone-800">
              <div><strong>Email:</strong> {viewingSubscriber.email}</div>
              <div><strong>Status:</strong> <span className="uppercase font-bold text-emerald-700">{viewingSubscriber.status}</span></div>
              <div><strong>Source:</strong> <span className="capitalize">{viewingSubscriber.source}</span></div>
              <div><strong>Subscribed Date:</strong> {new Date(viewingSubscriber.subscribedAt).toLocaleString('en-PK')}</div>
              <div><strong>Total Emails Delivered:</strong> {viewingSubscriber.totalEmailsSent || 0}</div>
              <div><strong>Last Email Sent:</strong> {viewingSubscriber.lastEmailSent ? new Date(viewingSubscriber.lastEmailSent).toLocaleString('en-PK') : 'None'}</div>
              {viewingSubscriber.notes && (
                <div><strong>Notes:</strong> {viewingSubscriber.notes}</div>
              )}
            </div>

            <div className="flex justify-end">
              <button
                onClick={() => setViewingSubscriber(null)}
                className="px-5 py-2 bg-stone-800 hover:bg-stone-900 text-white rounded-xl text-xs font-bold cursor-pointer"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
};
