import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../lib/api';
import {
  Users,
  PhoneCall,
  Clock,
  CheckCircle,
  Activity,
  ArrowUpRight,
  ArrowDownRight,
  Download,
  Sparkles,
  Globe,
  Mic,
  Calendar,
  BookOpen,
  PhoneForwarded,
  CheckCircle2,
  ChevronRight,
  X,
  DollarSign,
} from 'lucide-react';
import { motion, AnimatePresence, type Variants } from 'framer-motion';

interface CallItem {
  _id: string;
  sessionId: string;
  callerNumber?: string;
  durationSeconds?: number;
  status?: string;
  resolutionStatus?: string;
  outcomeTag?: string;
  aiSummary?: string;
  createdAt?: string;
  startTime?: string;
}

interface CompanyItem {
  _id: string;
  companyName: string;
  twilioPhoneNumber?: string;
  systemPrompt?: string;
  crmConfig?: {
    provider?: string;
    webhookUrl?: string;
  };
  calendarConfig?: {
    provider?: string;
  };
}

interface AppointmentItem {
  _id: string;
  status?: string;
}

interface DraftedAgentPreview {
  companyName: string;
  industry: string;
  voiceGender: 'male' | 'female';
  language: string;
  welcomeGreeting: string;
  systemPrompt: string;
  faqs: Array<{ question: string; answer: string }>;
  sourceUrl?: string;
}

const SKIPPED_STEPS_STORAGE_KEY = 'voxi_onboarding_skipped_steps_v1';

const Dashboard = () => {
  const navigate = useNavigate();
  const [calls, setCalls] = useState<CallItem[]>([]);
  const [companies, setCompanies] = useState<CompanyItem[]>([]);
  const [appointmentsCount, setAppointmentsCount] = useState<number>(0);
  const [selectedCompanyId, setSelectedCompanyId] = useState<string>('');

  // Guided Onboarding Wizard state
  const [skippedSteps, setSkippedSteps] = useState<string[]>(() => {
    try {
      const saved = localStorage.getItem(SKIPPED_STEPS_STORAGE_KEY);
      return saved ? (JSON.parse(saved) as string[]) : [];
    } catch {
      return [];
    }
  });
  const [hideOnboarding, setHideOnboarding] = useState<boolean>(false);
  const [showQuickWizardModal, setShowQuickWizardModal] = useState<boolean>(false);
  const [wizardUrl, setWizardUrl] = useState<string>('');
  const [wizardLoading, setWizardLoading] = useState<boolean>(false);
  const [wizardError, setWizardError] = useState<string>('');
  const [draftPreview, setDraftPreview] = useState<DraftedAgentPreview | null>(null);
  const [wizardPhone, setWizardPhone] = useState<string>('+18005550199');
  const [savingDraft, setSavingDraft] = useState<boolean>(false);

  useEffect(() => {
    let isMounted = true;
    const fetchInitial = async () => {
      try {
        const res = await api.get<CompanyItem[]>('/company');
        if (!isMounted) return;
        setCompanies(res.data);
        if (res.data.length > 0) {
          setSelectedCompanyId(res.data[0]._id);
        }
      } catch (err) {
        console.error('Failed to fetch companies', err);
      }
    };
    fetchInitial();
    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;
    const fetchStats = async () => {
      try {
        const callsUrl = selectedCompanyId
          ? `/calls?companyId=${selectedCompanyId}`
          : '/calls';
        const [callsRes, apptRes] = await Promise.all([
          api.get<CallItem[]>(callsUrl),
          api
            .get<AppointmentItem[]>(
              selectedCompanyId
                ? `/appointments?companyId=${selectedCompanyId}`
                : '/appointments'
            )
            .catch(() => ({ data: [] as AppointmentItem[] })),
        ]);
        if (!isMounted) return;
        setCalls(callsRes.data);
        setAppointmentsCount(Array.isArray(apptRes.data) ? apptRes.data.length : 0);
      } catch (error) {
        console.error('Failed to fetch dashboard calls', error);
      }
    };

    fetchStats();
    const interval = setInterval(fetchStats, 5000);
    return () => {
      isMounted = false;
      clearInterval(interval);
    };
  }, [selectedCompanyId]);

  const handleSkipStep = (stepId: string) => {
    const updated = Array.from(new Set([...skippedSteps, stepId]));
    setSkippedSteps(updated);
    try {
      localStorage.setItem(SKIPPED_STEPS_STORAGE_KEY, JSON.stringify(updated));
    } catch {
      // Ignore storage errors
    }
  };

  const handleGenerateFromUrl = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!wizardUrl.trim()) return;
    setWizardLoading(true);
    setWizardError('');
    try {
      const res = await api.post<DraftedAgentPreview>('/company/generate-from-url', {
        url: wizardUrl.trim(),
      });
      setDraftPreview(res.data);
    } catch (err: unknown) {
      const apiErr = err as { response?: { data?: { error?: string } } };
      setWizardError(
        apiErr?.response?.data?.error ||
          'Could not crawl website. Please check the URL or ensure it is publicly reachable.'
      );
    } finally {
      setWizardLoading(false);
    }
  };

  const handleConfirmQuickAgent = async () => {
    if (!draftPreview) return;
    setSavingDraft(true);
    setWizardError('');
    try {
      const res = await api.post<CompanyItem>('/company', {
        companyName: draftPreview.companyName,
        twilioPhoneNumber: wizardPhone.trim() || '+18005550199',
        systemPrompt: draftPreview.systemPrompt,
        voiceGender: draftPreview.voiceGender,
        language: draftPreview.language,
      });
      const updatedCompanies = [res.data, ...companies];
      setCompanies(updatedCompanies);
      setSelectedCompanyId(res.data._id);
      setShowQuickWizardModal(false);
      setDraftPreview(null);
      setWizardUrl('');
    } catch (err: unknown) {
      const apiErr = err as { response?: { data?: { error?: string } } };
      setWizardError(apiErr?.response?.data?.error || 'Failed to save generated AI agent.');
    } finally {
      setSavingDraft(false);
    }
  };

  const totalCalls = calls.length;
  const validDurations = calls
    .map((c) => c.durationSeconds)
    .filter((d): d is number => typeof d === 'number' && d > 0);
  const totalSeconds = validDurations.reduce((a, b) => a + b, 0);
  const avgDuration = validDurations.length
    ? Math.round(totalSeconds / validDurations.length)
    : 0;
  const totalMinutes = Math.ceil(totalSeconds / 60);
  const estimatedCostUsd = (totalMinutes * 0.14).toFixed(2);

  const completedCalls = calls.filter(
    (c) => c.status === 'completed' || c.status === 'transferred'
  );
  const resolutionRate =
    totalCalls > 0 ? Math.round((completedCalls.length / totalCalls) * 100) : 100;

  const activeCalls = calls.filter(
    (c) => c.status?.startsWith('active') || c.status === 'initiated'
  );
  const activeAgents = activeCalls.length > 0 ? activeCalls.length : Math.max(companies.length, 1);

  const selectedCompanyObj = companies.find((c) => c._id === selectedCompanyId) || companies[0];

  // Onboarding Steps Evaluation
  const onboardingSteps = [
    {
      id: 'agent_profile',
      title: '1. Create AI Agent from Website or Template',
      desc: 'Enter your website URL or choose an industry playbook to draft your greeting & persona.',
      completed: companies.length > 0 && Boolean(selectedCompanyObj?.systemPrompt),
      skipped: skippedSteps.includes('agent_profile'),
      icon: Globe,
      actionLabel: 'Auto-Generate from URL',
      onAction: () => setShowQuickWizardModal(true),
    },
    {
      id: 'knowledge_base',
      title: '2. Upload FAQ & Knowledge Base (RAG)',
      desc: 'Add PDFs, pricing sheets, or policies so your agent answers with zero hallucinations.',
      completed: skippedSteps.includes('knowledge_base') || totalCalls > 0,
      skipped: skippedSteps.includes('knowledge_base'),
      icon: BookOpen,
      actionLabel: 'Manage Knowledge Base',
      onAction: () => navigate('/knowledge-base'),
    },
    {
      id: 'test_call',
      title: '3. Run Browser Voice Simulator Call',
      desc: 'Test real-time interruption (barge-in) and tool calling in your browser before going live.',
      completed: totalCalls > 0,
      skipped: skippedSteps.includes('test_call'),
      icon: Mic,
      actionLabel: 'Launch Voice Simulator',
      onAction: () => navigate('/simulator'),
    },
    {
      id: 'calendar_crm',
      title: '4. Connect Calendar & CRM Webhooks',
      desc: 'Link Google/Outlook Calendar for live booking and HubSpot/Zapier for post-call summaries.',
      completed: Boolean(
        selectedCompanyObj?.crmConfig?.webhookUrl ||
          (selectedCompanyObj?.calendarConfig?.provider &&
            selectedCompanyObj?.calendarConfig?.provider !== 'none')
      ),
      skipped: skippedSteps.includes('calendar_crm'),
      icon: Calendar,
      actionLabel: 'Configure Integrations',
      onAction: () => navigate('/crm'),
    },
    {
      id: 'phone_live',
      title: '5. Connect Phone Number & Go Live',
      desc: 'Assign a dedicated Twilio number or configure *72 / GSM call forwarding from your existing line.',
      completed: Boolean(selectedCompanyObj?.twilioPhoneNumber),
      skipped: skippedSteps.includes('phone_live'),
      icon: PhoneForwarded,
      actionLabel: 'Setup Phone Routing',
      onAction: () => navigate('/company-registration'),
    },
  ];

  const completedStepsCount = onboardingSteps.filter((s) => s.completed || s.skipped).length;
  const onboardingProgressPct = Math.round(
    (completedStepsCount / onboardingSteps.length) * 100
  );

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}m ${secs}s`;
  };

  const handleGenerateReport = () => {
    const selectedCompany =
      companies.find((c) => c._id === selectedCompanyId)?.companyName ||
      'All Organizations';
    const headers = [
      'Session ID',
      'Caller Number',
      'Duration (s)',
      'Status',
      'Outcome Tag',
      'Resolution Status',
      'Timestamp',
    ];
    const rows = calls.map((c) => [
      `"${(c.sessionId || '').replace(/"/g, '""')}"`,
      `"${(c.callerNumber || '').replace(/"/g, '""')}"`,
      String(c.durationSeconds || 0),
      `"${c.status || ''}"`,
      `"${c.outcomeTag || 'general_inquiry'}"`,
      `"${(c.resolutionStatus || '').replace(/"/g, '""')}"`,
      `"${c.createdAt || c.startTime || ''}"`,
    ]);
    const summarySection = [
      `Organization,"${selectedCompany}"`,
      `Total Calls,${totalCalls}`,
      `Average Duration (s),${avgDuration}`,
      `Resolution Rate (%),${resolutionRate}%`,
      `Booked Appointments,${appointmentsCount}`,
      `Estimated Usage Value ($),$${estimatedCostUsd}`,
      '',
      headers.join(','),
      ...rows.map((r) => r.join(',')),
    ].join('\n');

    const blob = new Blob([summarySection], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `executive-report-${new Date().toISOString().slice(0, 10)}.csv`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const stats = [
    {
      name: 'Total Calls',
      value: totalCalls.toLocaleString(),
      icon: PhoneCall,
      change: '+12%',
      changeType: 'increase',
    },
    {
      name: 'Avg. Duration',
      value: formatDuration(avgDuration),
      icon: Clock,
      change: `${totalMinutes}m total`,
      changeType: 'neutral',
    },
    {
      name: 'Resolution Rate',
      value: `${resolutionRate}%`,
      icon: CheckCircle,
      change: '+4.3%',
      changeType: 'increase',
    },
    {
      name: 'Booked Appointments',
      value: appointmentsCount.toLocaleString(),
      icon: Calendar,
      change: 'In-Call Sync',
      changeType: 'increase',
    },
    {
      name: 'Active AI Agents',
      value: activeAgents.toString(),
      icon: Users,
      change: '24/7 Online',
      changeType: 'neutral',
    },
    {
      name: 'Metered Usage',
      value: `$${estimatedCostUsd}`,
      icon: DollarSign,
      change: `${totalMinutes} mins`,
      changeType: 'neutral',
    },
  ];

  const containerVariants: Variants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: { staggerChildren: 0.08 },
    },
  };

  const itemVariants: Variants = {
    hidden: { y: 20, opacity: 0 },
    visible: {
      y: 0,
      opacity: 1,
      transition: { type: 'spring' as const, stiffness: 100, damping: 15 },
    },
  };

  const chartData = calls
    .slice(0, 14)
    .reverse()
    .map((c) => Math.max(c.durationSeconds || 10, 10));
  while (chartData.length < 14) chartData.push(10);

  const liveActivity = calls.slice(0, 5).map((c) => ({
    time:
      c.createdAt || c.startTime
        ? new Date((c.createdAt || c.startTime) as string).toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit',
          })
        : 'Recent',
    title:
      c.status === 'completed'
        ? 'Call Completed'
        : c.status === 'transferred'
        ? 'Call Transferred'
        : c.status === 'failed'
        ? 'Call Failed'
        : 'Call Active',
    desc: c.aiSummary || c.resolutionStatus || `Outcome: ${c.outcomeTag || c.status}`,
    status:
      c.status === 'completed'
        ? 'success'
        : c.status === 'failed'
        ? 'error'
        : c.status === 'transferred'
        ? 'info'
        : 'system',
    num: c.callerNumber || 'Unknown',
  }));
  if (liveActivity.length === 0) {
    liveActivity.push({
      time: 'Just now',
      title: 'System Online',
      desc: 'Awaiting inbound calls or browser simulator session...',
      status: 'system',
      num: 'System',
    });
  }

  return (
    <div className="space-y-8 pb-12">
      <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">System Overview</h1>
          <p className="mt-1 text-sm text-slate-400">
            Monitor your AI phone assistants, live call outcomes, and onboarding readiness.
          </p>
        </div>
        <div className="flex items-center gap-3 flex-wrap">
          <select
            value={selectedCompanyId}
            onChange={(e) => setSelectedCompanyId(e.target.value)}
            aria-label="Select organization"
            className="px-4 py-2 bg-slate-900 border border-slate-700 rounded-lg text-sm font-medium text-slate-200 transition-colors focus:ring-2 focus:ring-indigo-500 outline-none"
          >
            {companies.map((c) => (
              <option key={c._id} value={c._id}>
                {c.companyName}
              </option>
            ))}
          </select>
          <div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-emerald-500/10 border border-emerald-500/20">
            <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
            <span className="text-xs font-medium text-emerald-400 uppercase tracking-wider">
              All Systems Operational
            </span>
          </div>
          <button
            onClick={handleGenerateReport}
            className="flex items-center gap-2 px-4 py-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-sm font-medium text-slate-200 transition-colors"
          >
            <Download className="w-4 h-4" />
            Generate Report
          </button>
        </div>
      </div>

      {/* Guided 5-Step Launch Wizard Banner */}
      {!hideOnboarding && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="rounded-2xl bg-gradient-to-br from-indigo-950/60 via-slate-900/90 to-slate-900 border border-indigo-500/30 p-6 shadow-xl"
        >
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-5 border-b border-white/10">
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-xl bg-indigo-500/20 border border-indigo-500/40 flex items-center justify-center text-indigo-400 shrink-0 mt-0.5">
                <Sparkles className="w-5 h-5" />
              </div>
              <div>
                <div className="flex items-center gap-3">
                  <h2 className="text-lg font-bold text-white">
                    Quick-Start AI Receptionist Wizard
                  </h2>
                  <span className="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                    {onboardingProgressPct}% Ready
                  </span>
                </div>
                <p className="text-xs text-slate-400 mt-1">
                  Go live in under 3 minutes: auto-generate your agent from your website URL, test in browser, and connect your phone line.
                </p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <button
                onClick={() => setShowQuickWizardModal(true)}
                className="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-semibold flex items-center gap-2 shadow-lg shadow-indigo-500/25 transition-all"
              >
                <Globe className="w-4 h-4" />
                1-Click Website to Agent
              </button>
              <button
                onClick={() => setHideOnboarding(true)}
                className="p-2 text-slate-400 hover:text-white rounded-lg hover:bg-white/5 transition-colors"
                title="Dismiss onboarding checklist"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-5 gap-3 mt-5">
            {onboardingSteps.map((step) => {
              const StepIcon = step.icon;
              const isDone = step.completed || step.skipped;
              return (
                <div
                  key={step.id}
                  className={`rounded-xl p-4 border flex flex-col justify-between transition-all ${
                    isDone
                      ? 'bg-emerald-500/5 border-emerald-500/25'
                      : 'bg-white/[0.03] border-white/10 hover:border-indigo-500/40'
                  }`}
                >
                  <div>
                    <div className="flex items-center justify-between mb-2">
                      <div
                        className={`w-8 h-8 rounded-lg flex items-center justify-center ${
                          isDone
                            ? 'bg-emerald-500/20 text-emerald-400'
                            : 'bg-indigo-500/15 text-indigo-400'
                        }`}
                      >
                        {isDone ? (
                          <CheckCircle2 className="w-4 h-4" />
                        ) : (
                          <StepIcon className="w-4 h-4" />
                        )}
                      </div>
                      {step.completed ? (
                        <span className="text-[10px] font-semibold uppercase tracking-wider text-emerald-400">
                          Complete
                        </span>
                      ) : step.skipped ? (
                        <span className="text-[10px] font-semibold uppercase tracking-wider text-slate-400">
                          Skipped
                        </span>
                      ) : (
                        <button
                          onClick={() => handleSkipStep(step.id)}
                          className="text-[10px] text-slate-500 hover:text-slate-300 underline"
                        >
                          Skip
                        </button>
                      )}
                    </div>
                    <h3 className="text-xs font-bold text-white leading-snug">{step.title}</h3>
                    <p className="text-[11px] text-slate-400 mt-1 leading-relaxed">{step.desc}</p>
                  </div>

                  <button
                    onClick={step.onAction}
                    className="mt-4 w-full py-1.5 px-2.5 rounded-lg bg-white/5 hover:bg-white/10 text-[11px] font-semibold text-indigo-300 flex items-center justify-between transition-colors"
                  >
                    <span>{step.actionLabel}</span>
                    <ChevronRight className="w-3.5 h-3.5" />
                  </button>
                </div>
              );
            })}
          </div>
        </motion.div>
      )}

      {/* KPI Cards (6 Executive Metrics) */}
      <motion.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6"
      >
        {stats.map((stat) => {
          const Icon = stat.icon;
          return (
            <motion.div
              key={stat.name}
              variants={itemVariants}
              className="relative overflow-hidden rounded-2xl bg-white/[0.02] border border-white/10 p-5 hover:bg-white/[0.04] transition-colors group"
            >
              <div className="flex items-center justify-between relative z-10">
                <div className="flex items-center justify-center w-10 h-10 rounded-xl bg-white/5 border border-white/10 group-hover:border-indigo-500/30 transition-colors">
                  <Icon className="w-5 h-5 text-indigo-400" />
                </div>
                <div
                  className={`flex items-center gap-1 text-xs font-medium ${
                    stat.changeType === 'increase'
                      ? 'text-emerald-400'
                      : stat.changeType === 'decrease'
                      ? 'text-rose-400'
                      : 'text-slate-400'
                  }`}
                >
                  {stat.changeType === 'increase' && <ArrowUpRight className="w-3.5 h-3.5" />}
                  {stat.changeType === 'decrease' && <ArrowDownRight className="w-3.5 h-3.5" />}
                  {stat.changeType === 'neutral' && <Activity className="w-3.5 h-3.5" />}
                  {stat.change}
                </div>
              </div>
              <div className="mt-4 relative z-10">
                <p className="text-xs font-medium text-slate-400">{stat.name}</p>
                <p className="text-2xl font-bold text-white tracking-tight mt-1">{stat.value}</p>
              </div>
            </motion.div>
          );
        })}
      </motion.div>

      {/* Two Column Layout for Charts and Activity */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="col-span-2 rounded-2xl bg-white/[0.02] border border-white/10 p-6"
        >
          <div className="flex items-center justify-between mb-8">
            <div>
              <h3 className="text-lg font-semibold text-white">Recent Call Durations</h3>
              <p className="text-sm text-slate-400">Duration in seconds of the last 14 calls.</p>
            </div>
            <button
              onClick={() => navigate('/calls')}
              className="px-3 py-1.5 hover:bg-white/5 rounded-lg text-xs font-medium text-indigo-400 hover:text-indigo-300 border border-white/5 transition-colors"
            >
              Inspect Logs
            </button>
          </div>

          <div className="h-[300px] w-full flex items-end justify-between gap-2 pb-4 border-b border-white/10 relative">
            {chartData.map((h, i) => {
              const maxVal = Math.max(...chartData, 150);
              const heightPercent = Math.min((h / maxVal) * 100, 100);
              return (
                <div
                  key={i}
                  className="w-full flex flex-col justify-end gap-1 group relative h-full"
                >
                  <div className="absolute -top-10 left-1/2 -translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity bg-slate-800 text-white text-xs py-1 px-2 rounded pointer-events-none z-10 whitespace-nowrap border border-slate-700 shadow-xl">
                    {h} secs
                  </div>
                  <div
                    className="w-full bg-indigo-500/20 hover:bg-indigo-500/40 rounded-t-sm transition-all duration-300 relative overflow-hidden"
                    style={{ height: `${heightPercent}%` }}
                  >
                    <div className="absolute inset-0 bg-gradient-to-t from-transparent to-indigo-400/50"></div>
                  </div>
                </div>
              );
            })}

            <div className="absolute top-0 left-0 w-full h-px bg-white/5"></div>
            <div className="absolute top-[25%] left-0 w-full h-px bg-white/5"></div>
            <div className="absolute top-[50%] left-0 w-full h-px bg-white/5"></div>
            <div className="absolute top-[75%] left-0 w-full h-px bg-white/5"></div>
          </div>
          <div className="flex justify-between mt-4 text-xs text-slate-500">
            <span>Older</span>
            <span>Newer</span>
          </div>
        </motion.div>

        {/* Live Activity Feed */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="col-span-1 rounded-2xl bg-white/[0.02] border border-white/10 p-6 flex flex-col"
        >
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-white flex items-center gap-2">
              <Activity className="w-5 h-5 text-indigo-400" />
              Live Activity
            </h3>
            <span className="text-xs font-medium text-slate-500 bg-white/5 px-2 py-1 rounded-md">
              Real-time
            </span>
          </div>

          <div className="flex-1 overflow-y-auto pr-2 space-y-6">
            {liveActivity.map((item, i) => (
              <div key={i} className="relative pl-6">
                {i !== liveActivity.length - 1 && (
                  <div className="absolute left-[9px] top-6 bottom-[-24px] w-px bg-white/10"></div>
                )}
                <div
                  className={`absolute left-0 top-1.5 w-5 h-5 rounded-full border-4 border-[#0a0a0f] flex items-center justify-center ${
                    item.status === 'success'
                      ? 'bg-emerald-500'
                      : item.status === 'error'
                      ? 'bg-rose-500'
                      : item.status === 'info'
                      ? 'bg-blue-500'
                      : 'bg-slate-500'
                  }`}
                ></div>

                <div className="flex justify-between items-start mb-1">
                  <p className="text-sm font-medium text-slate-200">{item.title}</p>
                  <span className="text-xs text-slate-500">{item.time}</span>
                </div>
                <p className="text-xs text-slate-400 mb-1 line-clamp-2">{item.desc}</p>
                <p className="text-[10px] text-slate-500 font-mono">{item.num}</p>
              </div>
            ))}
          </div>

          <button
            onClick={() => navigate('/calls')}
            className="w-full mt-6 py-2 rounded-lg bg-white/5 hover:bg-white/10 text-sm font-medium text-slate-300 transition-colors"
          >
            View All Activity
          </button>
        </motion.div>
      </div>

      {/* 1-Click Website-to-Agent Modal */}
      <AnimatePresence>
        {showQuickWizardModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/75 backdrop-blur-sm"
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-slate-900 border border-white/15 rounded-2xl max-w-2xl w-full p-6 max-h-[88vh] overflow-y-auto shadow-2xl space-y-5"
            >
              <div className="flex items-center justify-between border-b border-white/10 pb-4">
                <div className="flex items-center gap-2.5">
                  <Sparkles className="w-5 h-5 text-indigo-400" />
                  <h3 className="text-lg font-bold text-white">
                    Instant Website-to-Agent Generator
                  </h3>
                </div>
                <button
                  onClick={() => setShowQuickWizardModal(false)}
                  className="text-slate-400 hover:text-white"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <form onSubmit={handleGenerateFromUrl} className="space-y-3">
                <label className="block text-xs font-medium text-slate-300">
                  Enter your business website URL (protected by SSRF Guard)
                </label>
                <div className="flex gap-2">
                  <input
                    type="url"
                    required
                    value={wizardUrl}
                    onChange={(e) => setWizardUrl(e.target.value)}
                    placeholder="https://your-business.com"
                    className="flex-1 px-4 py-2.5 rounded-xl bg-slate-950 border border-white/10 text-sm text-white outline-none focus:border-indigo-500"
                  />
                  <button
                    type="submit"
                    disabled={wizardLoading}
                    className="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm font-semibold transition-all"
                  >
                    {wizardLoading ? 'Scanning...' : 'Draft AI Agent'}
                  </button>
                </div>
              </form>

              {wizardError && (
                <div className="p-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-xs text-rose-300">
                  {wizardError}
                </div>
              )}

              {draftPreview && (
                <div className="space-y-4 pt-3 border-t border-white/10">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs text-slate-400 mb-1">Company Name</label>
                      <input
                        type="text"
                        value={draftPreview.companyName}
                        onChange={(e) =>
                          setDraftPreview({ ...draftPreview, companyName: e.target.value })
                        }
                        className="w-full px-3 py-2 rounded-lg bg-slate-950 border border-white/10 text-sm text-white"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-slate-400 mb-1">
                        Inbound Phone / Twilio Number
                      </label>
                      <input
                        type="text"
                        value={wizardPhone}
                        onChange={(e) => setWizardPhone(e.target.value)}
                        className="w-full px-3 py-2 rounded-lg bg-slate-950 border border-white/10 text-sm text-white"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs text-slate-400 mb-1">Welcome Greeting</label>
                    <input
                      type="text"
                      value={draftPreview.welcomeGreeting}
                      onChange={(e) =>
                        setDraftPreview({ ...draftPreview, welcomeGreeting: e.target.value })
                      }
                      className="w-full px-3 py-2 rounded-lg bg-slate-950 border border-white/10 text-sm text-white"
                    />
                  </div>

                  <div>
                    <label className="block text-xs text-slate-400 mb-1">
                      Auto-Generated System Prompt
                    </label>
                    <textarea
                      rows={4}
                      value={draftPreview.systemPrompt}
                      onChange={(e) =>
                        setDraftPreview({ ...draftPreview, systemPrompt: e.target.value })
                      }
                      className="w-full px-3 py-2 rounded-lg bg-slate-950 border border-white/10 text-xs text-slate-200"
                    />
                  </div>

                  <div className="flex justify-end gap-3 pt-2">
                    <button
                      type="button"
                      onClick={() => setDraftPreview(null)}
                      className="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-xs font-medium text-slate-300"
                    >
                      Reset
                    </button>
                    <button
                      type="button"
                      disabled={savingDraft}
                      onClick={handleConfirmQuickAgent}
                      className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-xs font-bold text-white shadow-lg"
                    >
                      {savingDraft ? 'Creating Agent...' : 'Create & Launch Agent'}
                    </button>
                  </div>
                </div>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default Dashboard;
