"use client";

import { useState, useEffect } from "react";
import { api, getApiBaseUrl } from "@/lib/api";

type Member = {
  id: number;
  name: string;
  birthMonth: number;
  birthDay: number;
};

type LogEntry = {
  id: number;
  memberName: string;
  messageType: string;
  message: string;
  status: string;
  response?: string | null;
  sentAt: string;
};

type ScheduledMessage = {
  id: number;
  message: string;
  scheduledAt: string;
  status: string;
  sentAt?: string | null;
};

type ContributionRecord = {
  memberId: number;
  memberName: string;
  yearMonth: string;
  week1: number;
  week2: number;
  week3: number;
  week4: number;
  week5: number;
};

type DashboardData = {
  upcomingBirthdays: Array<{
    id: number;
    name: string;
    birthMonth: number;
    birthDay: number;
    daysUntil: number;
    date: string;
  }>;
  upcomingScheduled: ScheduledMessage[];
  recentLogs: LogEntry[];
  stats: {
    totalMembers: number;
    totalMessagesSent: number;
    pendingScheduled: number;
    upcomingBirthdays: number;
  };
  waClient: {
    configured: boolean;
    groupId: string;
    groupName: string;
    instanceId: string;
  };
  serverTime: string;
  timezone: string;
};

type Settings = Record<string, string>;

const monthNames = [
  "January","February","March","April","May","June",
  "July","August","September","October","November","December",
];

function getOrdinal(day: number) {
  if (day >= 11 && day <= 13) return "th";
  switch (day % 10) {
    case 1: return "st";
    case 2: return "nd";
    case 3: return "rd";
    default: return "th";
  }
}

function formatBirthday(month: number, day: number) {
  return `${monthNames[month - 1]} ${day}${getOrdinal(day)}`;
}

function formatDateTime(dateStr: string) {
  const date = new Date(dateStr);
  return date.toLocaleString('en-NG', { 
    dateStyle: 'medium', 
    timeStyle: 'short',
    timeZone: 'Africa/Lagos'
  });
}

function daysUntilBirthday(month: number, day: number) {
  const now = new Date();
  const thisYear = now.getFullYear();
  let birthday = new Date(thisYear, month - 1, day);
  if (birthday < now) {
    birthday = new Date(thisYear + 1, month - 1, day);
  }
  const diff = birthday.getTime() - now.getTime();
  return Math.ceil(diff / (1000 * 60 * 60 * 24));
}

function getCurrentYearMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
}

function formatYearMonth(ym: string) {
  const [year, month] = ym.split('-');
  return `${monthNames[parseInt(month) - 1]} ${year}`;
}

// ==================== LOGIN COMPONENT ====================
function LoginPage({ onLogin }: { onLogin: () => void }) {
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [dbStatus, setDbStatus] = useState<"checking" | "connected" | "disconnected">("checking");

  useEffect(() => {
    api.dbStatus()
      .then((r) => r.json())
      .then((d) => setDbStatus(d.connected ? "connected" : "disconnected"))
      .catch(() => setDbStatus("disconnected"));
  }, []);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");
    try {
      const res = await api.auth(password);
      const data = await res.json();
      if (data.success) {
        localStorage.setItem("auth_token", data.token);
        onLogin();
      } else {
        setError("Invalid password");
      }
    } catch {
      setError("Connection error");
    }
    setLoading(false);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary to-primary-dark p-4">
      <div className="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-md">
        <div className="text-center mb-8">
          <div className="text-6xl mb-4">🎂</div>
          <h1 className="text-2xl font-bold text-primary">Umu Emily Family Manager</h1>
          <p className="text-gray-500 text-sm mt-1">Birthdays • Contributions • Messages</p>
        </div>

        <form onSubmit={handleLogin} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-accent focus:border-transparent outline-none"
              placeholder="Enter password"
              required
            />
          </div>
          {error && <p className="text-red-500 text-sm">{error}</p>}
          <button
            type="submit"
            disabled={loading}
            className="w-full bg-accent hover:bg-accent-dark text-white font-semibold py-3 rounded-lg transition-colors disabled:opacity-50"
          >
            {loading ? "Logging in..." : "Login"}
          </button>
        </form>

        <div className="mt-6 pt-4 border-t border-gray-200">
          <div className="flex items-center justify-center gap-2 text-sm">
            <span className="text-gray-500">Database Status:</span>
            {dbStatus === "checking" && (
              <span className="flex items-center gap-1 text-yellow-600">
                <span className="w-2 h-2 bg-yellow-500 rounded-full animate-pulse"></span>
                Checking...
              </span>
            )}
            {dbStatus === "connected" && (
              <span className="flex items-center gap-1 text-green-600 font-medium">
                <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                Connected
              </span>
            )}
            {dbStatus === "disconnected" && (
              <span className="flex items-center gap-1 text-red-600 font-medium">
                <span className="w-2 h-2 bg-red-500 rounded-full"></span>
                Disconnected
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ==================== DASHBOARD ====================
function Dashboard({ onLogout }: { onLogout: () => void }) {
  const [activeTab, setActiveTab] = useState<"dashboard" | "members" | "contributions" | "scheduler" | "send" | "settings" | "logs">("dashboard");
  const [members, setMembers] = useState<Member[]>([]);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [appSettings, setAppSettings] = useState<Settings>({});
  const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
  const [scheduledMessages, setScheduledMessages] = useState<ScheduledMessage[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchMembers = async () => {
    const res = await api.getMembers();
    const data = await res.json();
    setMembers(data);
  };

  const fetchLogs = async () => {
    const res = await api.getLogs();
    const data = await res.json();
    setLogs(data);
  };

  const fetchSettings = async () => {
    const res = await api.getSettings();
    const data = await res.json();
    setAppSettings(data);
  };

  const fetchDashboard = async () => {
    try {
      const res = await api.getDashboard();
      const data = await res.json();
      setDashboardData(data);
    } catch (e) {
      console.error('Failed to fetch dashboard', e);
    }
  };

  const fetchScheduledMessages = async () => {
    const res = await api.getScheduledMessages('all');
    const data = await res.json();
    setScheduledMessages(data);
  };

  useEffect(() => {
    Promise.all([
      fetchMembers(), 
      fetchSettings(), 
      fetchLogs(), 
      fetchDashboard(),
      fetchScheduledMessages()
    ]).then(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="text-4xl animate-bounce mb-4">🎂</div>
          <p className="text-gray-500">Loading...</p>
        </div>
      </div>
    );
  }

  const tabs = [
    { key: "dashboard" as const, label: "📊 Dashboard", mobileLabel: "📊" },
    { key: "members" as const, label: "👥 Members", mobileLabel: "👥" },
    { key: "contributions" as const, label: "💰 Dues", mobileLabel: "💰" },
    { key: "scheduler" as const, label: "📅 Scheduler", mobileLabel: "📅" },
    { key: "send" as const, label: "📨 Send", mobileLabel: "📨" },
    { key: "settings" as const, label: "⚙️ Settings", mobileLabel: "⚙️" },
    { key: "logs" as const, label: "📋 Logs", mobileLabel: "📋" },
  ];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-primary text-white shadow-lg">
        <div className="max-w-6xl mx-auto px-4 py-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span className="text-3xl">🎂</span>
            <div>
              <h1 className="text-lg font-bold">Umu Emily Family Manager</h1>
              <p className="text-xs text-green-200">Birthdays • Contributions • Messages</p>
            </div>
          </div>
          <button onClick={onLogout} className="bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg text-sm transition-colors">
            Logout
          </button>
        </div>
      </header>

      {/* Tabs */}
      <div className="max-w-6xl mx-auto px-4 mt-4">
        <div className="flex gap-1 bg-white rounded-xl p-1 shadow-sm overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`flex-1 py-2.5 px-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
                activeTab === tab.key
                  ? "bg-primary text-white shadow-sm"
                  : "text-gray-600 hover:bg-gray-100"
              }`}
            >
              <span className="hidden md:inline">{tab.label}</span>
              <span className="md:hidden">{tab.mobileLabel}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div className="max-w-6xl mx-auto px-4 py-4 pb-8">
        {activeTab === "dashboard" && <DashboardTab data={dashboardData} onRefresh={fetchDashboard} />}
        {activeTab === "members" && <MembersTab members={members} onRefresh={fetchMembers} />}
        {activeTab === "contributions" && <ContributionsTab />}
        {activeTab === "scheduler" && <SchedulerTab messages={scheduledMessages} onRefresh={fetchScheduledMessages} />}
        {activeTab === "send" && <SendTab members={members} settings={appSettings} onRefresh={fetchLogs} />}
        {activeTab === "settings" && <SettingsTab settings={appSettings} onRefresh={fetchSettings} />}
        {activeTab === "logs" && <LogsTab logs={logs} onRefresh={fetchLogs} />}
      </div>
    </div>
  );
}

// ==================== DASHBOARD TAB ====================
function DashboardTab({ data, onRefresh }: { data: DashboardData | null; onRefresh: () => void }) {
  if (!data) {
    return <div className="text-center py-8 text-gray-500">Loading dashboard...</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-gray-800">📊 Dashboard</h2>
        <button onClick={onRefresh} className="bg-gray-100 hover:bg-gray-200 text-gray-600 px-4 py-2 rounded-lg text-sm transition-colors">
          🔄 Refresh
        </button>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl p-4 shadow-sm text-center">
          <div className="text-3xl font-bold text-primary">{data.stats.totalMembers}</div>
          <div className="text-sm text-gray-500">Total Members</div>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm text-center">
          <div className="text-3xl font-bold text-accent">{data.stats.upcomingBirthdays}</div>
          <div className="text-sm text-gray-500">Upcoming (30d)</div>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm text-center">
          <div className="text-3xl font-bold text-blue-600">{data.stats.pendingScheduled}</div>
          <div className="text-sm text-gray-500">Scheduled</div>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm text-center">
          <div className="text-3xl font-bold text-purple-600">{data.stats.totalMessagesSent}</div>
          <div className="text-sm text-gray-500">Messages Sent</div>
        </div>
      </div>

      {/* Two Column Layout */}
      <div className="grid md:grid-cols-2 gap-6">
        {/* Upcoming Birthdays */}
        <div className="bg-white rounded-xl p-4 shadow-sm">
          <h3 className="font-semibold text-gray-800 mb-3">🎂 Upcoming Birthdays</h3>
          {data.upcomingBirthdays.length === 0 ? (
            <p className="text-gray-400 text-sm">No birthdays in the next 30 days</p>
          ) : (
            <div className="space-y-2">
              {data.upcomingBirthdays.slice(0, 5).map((b) => (
                <div key={b.id} className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0">
                  <div>
                    <p className="font-medium text-gray-800">{b.name}</p>
                    <p className="text-xs text-gray-500">{formatBirthday(b.birthMonth, b.birthDay)}</p>
                  </div>
                  <span className={`text-xs px-2 py-1 rounded-full font-medium ${
                    b.daysUntil === 0 ? 'bg-red-100 text-red-700' :
                    b.daysUntil <= 7 ? 'bg-yellow-100 text-yellow-700' :
                    'bg-gray-100 text-gray-600'
                  }`}>
                    {b.daysUntil === 0 ? 'Today! 🎉' : b.daysUntil === 1 ? 'Tomorrow!' : `${b.daysUntil} days`}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Upcoming Scheduled Messages */}
        <div className="bg-white rounded-xl p-4 shadow-sm">
          <h3 className="font-semibold text-gray-800 mb-3">📅 Scheduled Messages</h3>
          {data.upcomingScheduled.length === 0 ? (
            <p className="text-gray-400 text-sm">No scheduled messages</p>
          ) : (
            <div className="space-y-2">
              {data.upcomingScheduled.slice(0, 5).map((m) => (
                <div key={m.id} className="py-2 border-b border-gray-100 last:border-0">
                  <p className="text-sm text-gray-800 line-clamp-1">{m.message}</p>
                  <p className="text-xs text-gray-500 mt-1">📆 {formatDateTime(m.scheduledAt)}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Recent Logs */}
      <div className="bg-white rounded-xl p-4 shadow-sm">
        <h3 className="font-semibold text-gray-800 mb-3">📋 Recent Activity</h3>
        {data.recentLogs.length === 0 ? (
          <p className="text-gray-400 text-sm">No recent activity</p>
        ) : (
          <div className="space-y-2">
            {data.recentLogs.slice(0, 5).map((log) => (
              <div key={log.id} className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0">
                <div className="flex items-center gap-2">
                  <span className={`w-2 h-2 rounded-full ${log.status === 'sent' ? 'bg-green-500' : 'bg-red-500'}`}></span>
                  <span className="font-medium text-gray-800">{log.memberName}</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${
                    log.messageType === 'birthday' ? 'bg-pink-100 text-pink-700' :
                    log.messageType === '1day' ? 'bg-yellow-100 text-yellow-700' :
                    log.messageType === '7day' ? 'bg-blue-100 text-blue-700' :
                    log.messageType === 'contribution' ? 'bg-green-100 text-green-700' :
                    'bg-purple-100 text-purple-700'
                  }`}>
                    {log.messageType}
                  </span>
                </div>
                <span className="text-xs text-gray-400">{formatDateTime(log.sentAt)}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Server Time */}
      <div className="text-center text-xs text-gray-400">
        Server Time: {data.serverTime} ({data.timezone})
      </div>
    </div>
  );
}

// ==================== CONTRIBUTIONS TAB ====================
function ContributionsTab() {
  const [yearMonth, setYearMonth] = useState(getCurrentYearMonth());
  const [contributions, setContributions] = useState<ContributionRecord[]>([]);
  const [localChanges, setLocalChanges] = useState<Record<number, { week1: boolean; week2: boolean; week3: boolean; week4: boolean; week5: boolean }>>({});
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState(false);
  const [sending, setSending] = useState(false);
  const [showSummary, setShowSummary] = useState(false);
  const [summary, setSummary] = useState<{ fullyPaid: string[]; partialOrUnpaid: Array<{ name: string; weeks: number[]; paidCount: number }> } | null>(null);
  const [sendResult, setSendResult] = useState<{ success: boolean; message: string } | null>(null);

  const fetchContributions = async () => {
    setLoading(true);
    try {
      const res = await api.getContributions(yearMonth);
      const data = await res.json();
      setContributions(data.contributions || []);
      // Initialize local changes
      const changes: Record<number, { week1: boolean; week2: boolean; week3: boolean; week4: boolean; week5: boolean }> = {};
      (data.contributions || []).forEach((c: ContributionRecord) => {
        changes[c.memberId] = {
          week1: c.week1 === 1,
          week2: c.week2 === 1,
          week3: c.week3 === 1,
          week4: c.week4 === 1,
          week5: c.week5 === 1,
        };
      });
      setLocalChanges(changes);
    } catch (e) {
      console.error('Failed to fetch contributions', e);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchContributions();
  }, [yearMonth]);

  const handleWeekToggle = (memberId: number, week: 'week1' | 'week2' | 'week3' | 'week4' | 'week5') => {
    // Find original contribution
    const original = contributions.find(c => c.memberId === memberId);
    const originalValue = original ? original[week] === 1 : false;
    
    // If already paid (locked), don't allow toggle
    if (originalValue) return;

    setLocalChanges(prev => ({
      ...prev,
      [memberId]: {
        ...prev[memberId],
        [week]: !prev[memberId]?.[week]
      }
    }));
  };

  const handleUpdate = async () => {
    setUpdating(true);
    setShowSummary(false);
    setSendResult(null);

    const updates = contributions.map(c => ({
      memberId: c.memberId,
      week1: localChanges[c.memberId]?.week1 || false,
      week2: localChanges[c.memberId]?.week2 || false,
      week3: localChanges[c.memberId]?.week3 || false,
      week4: localChanges[c.memberId]?.week4 || false,
      week5: localChanges[c.memberId]?.week5 || false,
    }));

    try {
      const res = await api.updateContributions(yearMonth, updates);
      const data = await res.json();
      if (data.success) {
        setContributions(data.contributions);
        setSummary(data.summary);
        setShowSummary(true);
        // Update local changes to reflect new locked state
        const changes: Record<number, { week1: boolean; week2: boolean; week3: boolean; week4: boolean; week5: boolean }> = {};
        data.contributions.forEach((c: ContributionRecord) => {
          changes[c.memberId] = {
            week1: c.week1 === 1,
            week2: c.week2 === 1,
            week3: c.week3 === 1,
            week4: c.week4 === 1,
            week5: c.week5 === 1,
          };
        });
        setLocalChanges(changes);
      }
    } catch (e) {
      console.error('Failed to update contributions', e);
    }
    setUpdating(false);
  };

  const handleSendToWhatsApp = async () => {
    setSending(true);
    setSendResult(null);
    try {
      const res = await api.sendContributionReport(yearMonth);
      const data = await res.json();
      setSendResult({
        success: data.success,
        message: data.success ? 'Report sent to WhatsApp group!' : 'Failed to send: ' + (data.error || data.response)
      });
    } catch {
      setSendResult({ success: false, message: 'Connection error' });
    }
    setSending(false);
  };

  const getMonthOptions = () => {
    const options = [];
    const now = new Date();
    for (let i = -3; i <= 3; i++) {
      const d = new Date(now.getFullYear(), now.getMonth() + i, 1);
      const ym = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
      options.push({ value: ym, label: formatYearMonth(ym) });
    }
    return options;
  };

  if (loading) {
    return <div className="text-center py-8 text-gray-500">Loading contributions...</div>;
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between flex-wrap gap-2">
        <h2 className="text-xl font-bold text-gray-800">💰 Weekly Dues (₦200)</h2>
        <select
          value={yearMonth}
          onChange={(e) => setYearMonth(e.target.value)}
          className="px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
        >
          {getMonthOptions().map(opt => (
            <option key={opt.value} value={opt.value}>{opt.label}</option>
          ))}
        </select>
      </div>

      {/* Contribution Table */}
      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">Member</th>
                <th className="px-2 py-3 text-center text-sm font-semibold text-gray-700 w-16">Wk 1</th>
                <th className="px-2 py-3 text-center text-sm font-semibold text-gray-700 w-16">Wk 2</th>
                <th className="px-2 py-3 text-center text-sm font-semibold text-gray-700 w-16">Wk 3</th>
                <th className="px-2 py-3 text-center text-sm font-semibold text-gray-700 w-16">Wk 4</th>
                <th className="px-2 py-3 text-center text-sm font-semibold text-gray-700 w-16">Wk 5</th>
                <th className="px-4 py-3 text-center text-sm font-semibold text-gray-700 w-20">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {contributions.map((c) => {
                const local = localChanges[c.memberId] || { week1: false, week2: false, week3: false, week4: false, week5: false };
                const totalPaid = [local.week1, local.week2, local.week3, local.week4, local.week5].filter(Boolean).length;
                const totalAmount = totalPaid * 200;

                return (
                  <tr key={c.memberId} className="hover:bg-gray-50">
                    <td className="px-4 py-3 text-sm font-medium text-gray-800">{c.memberName}</td>
                    {(['week1', 'week2', 'week3', 'week4', 'week5'] as const).map((week) => {
                      const isLocked = c[week] === 1;
                      const isChecked = local[week];
                      return (
                        <td key={week} className="px-2 py-3 text-center">
                          <button
                            onClick={() => handleWeekToggle(c.memberId, week)}
                            disabled={isLocked}
                            className={`w-8 h-8 rounded-lg text-lg transition-all ${
                              isLocked
                                ? 'bg-green-100 text-green-600 cursor-not-allowed'
                                : isChecked
                                ? 'bg-green-500 text-white hover:bg-green-600'
                                : 'bg-gray-100 text-gray-400 hover:bg-gray-200'
                            }`}
                          >
                            {isChecked ? '✓' : ''}
                          </button>
                        </td>
                      );
                    })}
                    <td className="px-4 py-3 text-center">
                      <span className={`text-sm font-semibold ${totalPaid === 5 ? 'text-green-600' : 'text-gray-600'}`}>
                        ₦{totalAmount.toLocaleString()}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Update Button */}
      <button
        onClick={handleUpdate}
        disabled={updating}
        className="w-full bg-primary hover:bg-primary-dark text-white font-semibold py-3 rounded-lg transition-colors disabled:opacity-50"
      >
        {updating ? 'Updating...' : '✅ Update Records'}
      </button>

      {/* Summary Section */}
      {showSummary && summary && (
        <div className="space-y-4">
          <div className="bg-white rounded-xl p-4 shadow-sm">
            <h3 className="font-semibold text-gray-800 mb-3">📊 Summary for {formatYearMonth(yearMonth)}</h3>
            
            {summary.fullyPaid.length > 0 && (
              <div className="mb-4">
                <h4 className="text-sm font-medium text-green-700 mb-2">✅ Fully Paid ({summary.fullyPaid.length})</h4>
                <div className="flex flex-wrap gap-2">
                  {summary.fullyPaid.map((name, i) => (
                    <span key={i} className="bg-green-100 text-green-700 px-3 py-1 rounded-full text-sm">{name}</span>
                  ))}
                </div>
              </div>
            )}

            {summary.partialOrUnpaid.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-orange-700 mb-2">⏳ Pending ({summary.partialOrUnpaid.length})</h4>
                <div className="space-y-1">
                  {summary.partialOrUnpaid.map((m, i) => (
                    <div key={i} className="flex items-center justify-between bg-orange-50 px-3 py-2 rounded-lg">
                      <span className="text-sm text-gray-800">{m.name}</span>
                      <span className="text-sm text-orange-600">
                        {m.weeks.map((w, wi) => w ? '✅' : '❌').join('')} (₦{m.paidCount * 200})
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Send to WhatsApp Button */}
          <button
            onClick={handleSendToWhatsApp}
            disabled={sending}
            className="w-full bg-accent hover:bg-accent-dark text-white font-semibold py-3 rounded-lg transition-colors disabled:opacity-50"
          >
            {sending ? 'Sending...' : '📲 Send Report to WhatsApp Group'}
          </button>

          {sendResult && (
            <div className={`p-3 rounded-lg text-sm ${sendResult.success ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
              {sendResult.success ? '✅' : '❌'} {sendResult.message}
            </div>
          )}
        </div>
      )}

      {/* Info */}
      <div className="bg-blue-50 rounded-xl p-4 text-sm text-blue-700">
        <strong>ℹ️ Note:</strong> Once a week is marked as paid and updated, it becomes locked and cannot be changed.
        Green locked checkmarks (✓) indicate confirmed payments.
      </div>
    </div>
  );
}

// ==================== SCHEDULER TAB ====================
function SchedulerTab({ messages, onRefresh }: { messages: ScheduledMessage[]; onRefresh: () => void }) {
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [message, setMessage] = useState("");
  const [scheduledDate, setScheduledDate] = useState("");
  const [scheduledTime, setScheduledTime] = useState("08:00");
  const [filter, setFilter] = useState<'pending' | 'sent' | 'all'>('pending');
  const [submitting, setSubmitting] = useState(false);

  const resetForm = () => {
    setMessage("");
    setScheduledDate("");
    setScheduledTime("08:00");
    setEditingId(null);
    setShowForm(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!message || !scheduledDate || !scheduledTime) return;
    
    setSubmitting(true);
    const scheduledAt = `${scheduledDate} ${scheduledTime}:00`;
    
    if (editingId) {
      await api.updateScheduledMessage(editingId, message, scheduledAt);
    } else {
      await api.addScheduledMessage(message, scheduledAt);
    }
    
    setSubmitting(false);
    resetForm();
    onRefresh();
  };

  const handleEdit = (m: ScheduledMessage) => {
    setEditingId(m.id);
    setMessage(m.message);
    const dt = new Date(m.scheduledAt);
    setScheduledDate(dt.toISOString().split('T')[0]);
    setScheduledTime(dt.toTimeString().slice(0, 5));
    setShowForm(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this scheduled message?")) return;
    await api.deleteScheduledMessage(id);
    onRefresh();
  };

  const filteredMessages = messages.filter(m => {
    if (filter === 'all') return true;
    return m.status === filter;
  });

  const pendingMessages = messages.filter(m => m.status === 'pending');
  const sentMessages = messages.filter(m => m.status === 'sent');

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between flex-wrap gap-2">
        <h2 className="text-xl font-bold text-gray-800">📅 Message Scheduler</h2>
        <button
          onClick={() => { resetForm(); setShowForm(!showForm); }}
          className="bg-accent hover:bg-accent-dark text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        >
          {showForm ? "Cancel" : "+ Schedule Message"}
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 gap-4">
        <div className="bg-blue-50 rounded-xl p-4 text-center">
          <div className="text-2xl font-bold text-blue-600">{pendingMessages.length}</div>
          <div className="text-sm text-blue-600">Pending</div>
        </div>
        <div className="bg-green-50 rounded-xl p-4 text-center">
          <div className="text-2xl font-bold text-green-600">{sentMessages.length}</div>
          <div className="text-sm text-green-600">Sent</div>
        </div>
      </div>

      {/* Add/Edit Form */}
      {showForm && (
        <form onSubmit={handleSubmit} className="bg-white rounded-xl p-4 shadow-sm space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Message</label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={4}
              className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
              placeholder="Enter your message for the WhatsApp group..."
              required
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
              <input
                type="date"
                value={scheduledDate}
                onChange={(e) => setScheduledDate(e.target.value)}
                min={new Date().toISOString().split('T')[0]}
                className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Time (WAT)</label>
              <input
                type="time"
                value={scheduledTime}
                onChange={(e) => setScheduledTime(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
                required
              />
            </div>
          </div>
          <button
            type="submit"
            disabled={submitting}
            className="w-full bg-primary hover:bg-primary-dark text-white font-semibold py-3 rounded-lg transition-colors disabled:opacity-50"
          >
            {submitting ? "Saving..." : editingId ? "Update Schedule" : "Schedule Message"}
          </button>
        </form>
      )}

      {/* Filter */}
      <div className="flex gap-2">
        {(['pending', 'sent', 'all'] as const).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
              filter === f ? 'bg-primary text-white' : 'bg-white text-gray-600 hover:bg-gray-100'
            }`}
          >
            {f.charAt(0).toUpperCase() + f.slice(1)}
          </button>
        ))}
        <button onClick={onRefresh} className="ml-auto bg-gray-100 hover:bg-gray-200 text-gray-600 px-4 py-2 rounded-lg text-sm transition-colors">
          🔄
        </button>
      </div>

      {/* Messages List */}
      {filteredMessages.length === 0 ? (
        <div className="bg-white rounded-xl p-8 text-center shadow-sm">
          <div className="text-4xl mb-2">📭</div>
          <p className="text-gray-500">No {filter === 'all' ? '' : filter} scheduled messages</p>
        </div>
      ) : (
        <div className="space-y-3">
          {filteredMessages.map((m) => (
            <div key={m.id} className="bg-white rounded-xl p-4 shadow-sm">
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <span className={`w-2 h-2 rounded-full ${m.status === 'pending' ? 'bg-blue-500' : m.status === 'sent' ? 'bg-green-500' : 'bg-red-500'}`}></span>
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                      m.status === 'pending' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'
                    }`}>
                      {m.status}
                    </span>
                    <span className="text-xs text-gray-400">
                      📆 {formatDateTime(m.scheduledAt)}
                    </span>
                  </div>
                  <p className="text-sm text-gray-800 whitespace-pre-wrap">{m.message}</p>
                  {m.sentAt && (
                    <p className="text-xs text-gray-400 mt-2">Sent: {formatDateTime(m.sentAt)}</p>
                  )}
                </div>
                {m.status === 'pending' && (
                  <div className="flex gap-1">
                    <button onClick={() => handleEdit(m)} className="text-gray-400 hover:text-blue-500 p-1" title="Edit">✏️</button>
                    <button onClick={() => handleDelete(m.id)} className="text-gray-400 hover:text-red-500 p-1" title="Delete">🗑️</button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Info */}
      <div className="bg-blue-50 rounded-xl p-4 text-sm text-blue-700">
        <strong>ℹ️ How it works:</strong> Scheduled messages are sent automatically when the cron job runs. 
        Make sure cron-job.org is configured to run frequently (e.g., every 5-15 minutes) for accurate timing.
      </div>
    </div>
  );
}

// ==================== MEMBERS TAB ====================
function MembersTab({ members, onRefresh }: { members: Member[]; onRefresh: () => void }) {
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [name, setName] = useState("");
  const [birthMonth, setBirthMonth] = useState(1);
  const [birthDay, setBirthDay] = useState(1);

  const resetForm = () => {
    setName("");
    setBirthMonth(1);
    setBirthDay(1);
    setEditingId(null);
    setShowForm(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (editingId) {
      await api.updateMember(editingId, name, birthMonth, birthDay);
    } else {
      await api.addMember(name, birthMonth, birthDay);
    }
    resetForm();
    onRefresh();
  };

  const handleEdit = (m: Member) => {
    setEditingId(m.id);
    setName(m.name);
    setBirthMonth(m.birthMonth);
    setBirthDay(m.birthDay);
    setShowForm(true);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-gray-800">👥 Family Members ({members.length})</h2>
        <button
          onClick={() => { resetForm(); setShowForm(!showForm); }}
          className="bg-accent hover:bg-accent-dark text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        >
          {showForm ? "Cancel" : "+ Add Member"}
        </button>
      </div>

      {showForm && (
        <form onSubmit={handleSubmit} className="bg-white rounded-xl p-4 shadow-sm space-y-3">
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Full Name"
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            required
          />
          <div className="flex gap-3">
            <select
              value={birthMonth}
              onChange={(e) => setBirthMonth(Number(e.target.value))}
              className="flex-1 px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            >
              {monthNames.map((m, i) => (
                <option key={i} value={i + 1}>{m}</option>
              ))}
            </select>
            <input
              type="number"
              min={1}
              max={31}
              value={birthDay}
              onChange={(e) => setBirthDay(Number(e.target.value))}
              placeholder="Day"
              className="w-24 px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
              required
            />
          </div>
          <button type="submit" className="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg text-sm font-medium transition-colors">
            {editingId ? "Update" : "Add Member"}
          </button>
        </form>
      )}

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {members.map((m) => {
          const days = daysUntilBirthday(m.birthMonth, m.birthDay);
          return (
            <div key={m.id} className="bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow">
              <div className="flex items-start justify-between">
                <div>
                  <h3 className="font-semibold text-gray-800">{m.name}</h3>
                  <p className="text-sm text-gray-500 mt-1">🎂 {formatBirthday(m.birthMonth, m.birthDay)}</p>
                  <p className={`text-xs mt-1 font-medium ${
                    days === 0 ? "text-red-600" : days <= 7 ? "text-yellow-600" : "text-gray-400"
                  }`}>
                    {days === 0 ? "🎉 Birthday Today!" : days === 1 ? "⏰ Tomorrow!" : `${days} days away`}
                  </p>
                </div>
                <button onClick={() => handleEdit(m)} className="text-gray-400 hover:text-blue-500 p-1" title="Edit">✏️</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ==================== SEND TAB ====================
function SendTab({ members, settings, onRefresh }: { members: Member[]; settings: Settings; onRefresh: () => void }) {
  const [selectedMember, setSelectedMember] = useState<number | "">("");
  const [messageType, setMessageType] = useState<"7day" | "1day" | "birthday">("birthday");
  const [sending, setSending] = useState(false);
  const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);
  const [preview, setPreview] = useState("");
  const [customMessage, setCustomMessage] = useState("");
  const [useCustom, setUseCustom] = useState(false);

  useEffect(() => {
    if (selectedMember && !useCustom) {
      const member = members.find((m) => m.id === Number(selectedMember));
      if (member) {
        const templateKey = `message_${messageType}`;
        const template = settings[templateKey] || "";
        const filled = template
          .replace(/\{name\}/g, member.name)
          .replace(/\{date\}/g, formatBirthday(member.birthMonth, member.birthDay));
        setPreview(filled);
      }
    }
  }, [selectedMember, messageType, settings, members, useCustom]);

  const handleSend = async () => {
    if (!selectedMember) return;
    setSending(true);
    setResult(null);

    const member = members.find((m) => m.id === Number(selectedMember));
    if (!member) return;

    try {
      let res;
      if (useCustom && customMessage) {
        res = await api.sendMessage(member.name, "custom", customMessage);
      } else {
        res = await api.testSend(Number(selectedMember), messageType);
      }
      const data = await res.json();
      setResult({ success: data.success || false, message: data.error || (data.success ? "Message sent!" : "Failed: " + data.response) });
    } catch {
      setResult({ success: false, message: "Connection error" });
    }
    setSending(false);
    onRefresh();
  };

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-bold text-gray-800">📨 Send Message</h2>

      <div className="bg-white rounded-xl p-4 shadow-sm space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Select Member</label>
          <select
            value={selectedMember}
            onChange={(e) => setSelectedMember(e.target.value ? Number(e.target.value) : "")}
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
          >
            <option value="">-- Select a member --</option>
            {members.map((m) => (
              <option key={m.id} value={m.id}>
                {m.name} ({formatBirthday(m.birthMonth, m.birthDay)})
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Message Type</label>
          <div className="flex gap-2 flex-wrap">
            {[
              { key: "7day" as const, label: "7-Day 📅" },
              { key: "1day" as const, label: "1-Day ⏰" },
              { key: "birthday" as const, label: "Birthday 🎂" },
            ].map((type) => (
              <button
                key={type.key}
                onClick={() => { setMessageType(type.key); setUseCustom(false); }}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                  messageType === type.key && !useCustom
                    ? "bg-primary text-white"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                {type.label}
              </button>
            ))}
            <button
              onClick={() => setUseCustom(!useCustom)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                useCustom ? "bg-primary text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
              }`}
            >
              Custom ✍️
            </button>
          </div>
        </div>

        {useCustom && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Custom Message</label>
            <textarea
              value={customMessage}
              onChange={(e) => setCustomMessage(e.target.value)}
              rows={5}
              className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
              placeholder="Type your custom message..."
            />
          </div>
        )}

        {!useCustom && preview && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Preview</label>
            <div className="bg-green-50 rounded-lg p-4 text-sm whitespace-pre-wrap border border-green-200">
              {preview}
            </div>
          </div>
        )}

        <button
          onClick={handleSend}
          disabled={sending || !selectedMember || (useCustom && !customMessage)}
          className="w-full bg-accent hover:bg-accent-dark text-white font-semibold py-3 rounded-lg transition-colors disabled:opacity-50"
        >
          {sending ? "Sending..." : "Send to WhatsApp Group 📲"}
        </button>

        {result && (
          <div className={`p-3 rounded-lg text-sm ${result.success ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"}`}>
            {result.success ? "✅" : "❌"} {result.message}
          </div>
        )}
      </div>
    </div>
  );
}

// ==================== SETTINGS TAB ====================
function SettingsTab({ settings, onRefresh }: { settings: Settings; onRefresh: () => void }) {
  const [accessToken, setAccessToken] = useState(settings.whatsapp_access_token || "");
  const [instanceId, setInstanceId] = useState(settings.whatsapp_instance_id || "");
  const [groupId, setGroupId] = useState(settings.whatsapp_group_id || "");
  const [groupName, setGroupName] = useState(settings.whatsapp_group_name || "");
  const [cronSecret, setCronSecret] = useState(settings.cron_secret || "");
  const [msg7day, setMsg7day] = useState(settings.message_7day || "");
  const [msg1day, setMsg1day] = useState(settings.message_1day || "");
  const [msgBirthday, setMsgBirthday] = useState(settings.message_birthday || "");
  const [password, setPassword] = useState("");
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  const handleSave = async () => {
    setSaving(true);
    const updates: Record<string, string> = {
      whatsapp_access_token: accessToken,
      whatsapp_instance_id: instanceId,
      whatsapp_group_id: groupId,
      whatsapp_group_name: groupName,
      cron_secret: cronSecret,
      message_7day: msg7day,
      message_1day: msg1day,
      message_birthday: msgBirthday,
    };
    if (password) {
      updates.app_password = password;
    }
    await api.updateSettings(updates);
    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 3000);
    onRefresh();
  };

  const apiBaseUrl = getApiBaseUrl();
  const cronUrl = `${apiBaseUrl}/api/cron.php?secret=${cronSecret}`;

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-bold text-gray-800">⚙️ Settings</h2>

      {/* WhatsApp API */}
      <div className="bg-white rounded-xl p-4 shadow-sm space-y-3">
        <h3 className="font-semibold text-gray-700">WA Client API Configuration</h3>
        <p className="text-xs text-gray-500">Get these from your waclient.com dashboard</p>
        <div>
          <label className="block text-sm text-gray-600 mb-1">Access Token</label>
          <input
            type="password"
            value={accessToken}
            onChange={(e) => setAccessToken(e.target.value)}
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            placeholder="Your WA Client access token"
          />
        </div>
        <div>
          <label className="block text-sm text-gray-600 mb-1">Instance ID</label>
          <input
            type="text"
            value={instanceId}
            onChange={(e) => setInstanceId(e.target.value)}
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            placeholder="e.g., 609ACF283XXXX"
          />
        </div>
        <div>
          <label className="block text-sm text-gray-600 mb-1">WhatsApp Group ID (chat_id)</label>
          <input
            type="text"
            value={groupId}
            onChange={(e) => setGroupId(e.target.value)}
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            placeholder="e.g., 2348012345678-1234567890@g.us"
          />
        </div>
        <div>
          <label className="block text-sm text-gray-600 mb-1">Group Name (for display)</label>
          <input
            type="text"
            value={groupName}
            onChange={(e) => setGroupName(e.target.value)}
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            placeholder="e.g., Umu Emily Grandchildren"
          />
        </div>
      </div>

      {/* Cron Settings */}
      <div className="bg-white rounded-xl p-4 shadow-sm space-y-3">
        <h3 className="font-semibold text-gray-700">Cron Job (cron-job.org)</h3>
        <div>
          <label className="block text-sm text-gray-600 mb-1">Cron Secret</label>
          <input
            type="text"
            value={cronSecret}
            onChange={(e) => setCronSecret(e.target.value)}
            className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
            placeholder="Secret for cron endpoint"
          />
        </div>
        <div>
          <label className="block text-sm text-gray-600 mb-1">Cron URL (use on cron-job.org)</label>
          <div className="bg-gray-50 p-3 rounded-lg text-xs font-mono break-all border">{cronUrl}</div>
          <p className="text-xs text-gray-500 mt-1">
            <strong>For birthdays:</strong> Daily at 8:00 AM (WAT)<br/>
            <strong>For scheduled messages:</strong> Every 5-15 minutes for accurate timing
          </p>
        </div>
      </div>

      {/* Message Templates */}
      <div className="bg-white rounded-xl p-4 shadow-sm space-y-3">
        <h3 className="font-semibold text-gray-700">Message Templates</h3>
        <p className="text-xs text-gray-500">Use {"{name}"} for member name and {"{date}"} for birthday date</p>

        <div>
          <label className="block text-sm text-gray-600 mb-1">7-Day Notice 📅</label>
          <textarea value={msg7day} onChange={(e) => setMsg7day(e.target.value)} rows={4} className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent text-sm" />
        </div>
        <div>
          <label className="block text-sm text-gray-600 mb-1">1-Day Notice ⏰</label>
          <textarea value={msg1day} onChange={(e) => setMsg1day(e.target.value)} rows={4} className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent text-sm" />
        </div>
        <div>
          <label className="block text-sm text-gray-600 mb-1">Birthday Message 🎂</label>
          <textarea value={msgBirthday} onChange={(e) => setMsgBirthday(e.target.value)} rows={6} className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent text-sm" />
        </div>
      </div>

      {/* Password */}
      <div className="bg-white rounded-xl p-4 shadow-sm space-y-3">
        <h3 className="font-semibold text-gray-700">Change Password</h3>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-accent"
          placeholder="New password (leave blank to keep current)"
        />
      </div>

      <button
        onClick={handleSave}
        disabled={saving}
        className="w-full bg-primary hover:bg-primary-dark text-white font-semibold py-3 rounded-lg transition-colors disabled:opacity-50"
      >
        {saving ? "Saving..." : saved ? "✅ Saved!" : "Save Settings"}
      </button>
    </div>
  );
}

// ==================== LOGS TAB ====================
function LogsTab({ logs, onRefresh }: { logs: LogEntry[]; onRefresh: () => void }) {
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-gray-800">📋 Message Logs</h2>
        <button
          onClick={onRefresh}
          className="bg-gray-100 hover:bg-gray-200 text-gray-600 px-4 py-2 rounded-lg text-sm transition-colors"
        >
          🔄 Refresh
        </button>
      </div>

      {logs.length === 0 ? (
        <div className="bg-white rounded-xl p-8 text-center shadow-sm">
          <div className="text-4xl mb-2">📭</div>
          <p className="text-gray-500">No messages sent yet</p>
        </div>
      ) : (
        <div className="space-y-2">
          {logs.map((log) => (
            <div key={log.id} className="bg-white rounded-xl p-4 shadow-sm">
              <div className="flex items-start justify-between flex-wrap gap-2">
                <div className="flex items-center gap-2">
                  <span className={`w-2 h-2 rounded-full ${log.status === "sent" ? "bg-green-500" : "bg-red-500"}`}></span>
                  <span className="font-medium text-gray-800">{log.memberName}</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${
                    log.messageType === "birthday" ? "bg-pink-100 text-pink-700" :
                    log.messageType === "1day" ? "bg-yellow-100 text-yellow-700" :
                    log.messageType === "7day" ? "bg-blue-100 text-blue-700" :
                    log.messageType === "scheduled" ? "bg-purple-100 text-purple-700" :
                    log.messageType === "contribution" ? "bg-green-100 text-green-700" :
                    "bg-gray-100 text-gray-700"
                  }`}>
                    {log.messageType}
                  </span>
                </div>
                <span className="text-xs text-gray-400">
                  {formatDateTime(log.sentAt)}
                </span>
              </div>
              <p className="text-sm text-gray-500 mt-2 whitespace-pre-wrap line-clamp-3">{log.message}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ==================== MAIN APP ====================
export default function Home() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    const token = localStorage.getItem("auth_token");
    if (token) {
      setIsLoggedIn(true);
    }
    setChecking(false);
  }, []);

  if (checking) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-4xl animate-bounce">🎂</div>
      </div>
    );
  }

  if (!isLoggedIn) {
    return <LoginPage onLogin={() => setIsLoggedIn(true)} />;
  }

  return (
    <Dashboard
      onLogout={() => {
        localStorage.removeItem("auth_token");
        setIsLoggedIn(false);
      }}
    />
  );
}
