
    const { useState, useEffect, useMemo } = React;

    const API = 'https://srrmgsgbhjiimttjpgop.supabase.co/functions/v1/admin-api';
    let PIN = '0102'; try { PIN = localStorage.getItem('abu_admin_pin') || '0102'; } catch(e) {}

    // Simplified Icons using SVGs
    const Icons = {
      Home: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>,
      Users: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
      Waitlist: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><path d="M12 11h4"/><path d="M12 16h4"/><path d="M8 11h.01"/><path d="M8 16h.01"/></svg>,
      Feedback: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>,
      Safety: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>,
      Finance: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
      Reports: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>,
      Config: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>,
      System: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>,
      QA: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    };

    const SummaryCard = ({ tabName, summaries }) => {
      const summary = summaries?.find(s => s.tab_name === tabName);
      if (!summary) return null;

      const timeAgo = (date) => {
        const seconds = Math.floor((new Date() - new Date(date)) / 1000);
        if (seconds < 60) return 'Just now';
        const minutes = Math.floor(seconds / 60);
        if (minutes < 60) return `${minutes}m ago`;
        const hours = Math.floor(minutes / 60);
        if (hours < 24) return `${hours}h ago`;
        return new Date(date).toLocaleDateString();
      };

      return (
        <div className="mb-6 p-5 rounded-2xl border border-blue-500/30 bg-gradient-to-br from-blue-500/10 to-indigo-500/10 shadow-[0_0_20px_rgba(59,130,246,0.05)] backdrop-blur-md relative overflow-hidden group">
          <div className="absolute inset-0 bg-gradient-to-br from-blue-500/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none"></div>
          <div className="flex flex-col md:flex-row justify-between gap-4 relative z-10">
            <div className="flex-1">
              <div className="flex items-start gap-3">
                <span className="text-xl">💡</span>
                <div>
                  <div className="text-xs font-bold text-blue-400 uppercase tracking-wider mb-1">AI Insight</div>
                  <p className="text-sm text-gray-200 leading-relaxed">{summary.summary}</p>
                </div>
              </div>
            </div>
            <div className="w-[1px] bg-white/10 hidden md:block"></div>
            <div className="flex-1">
              <div className="flex items-start gap-3">
                <span className="text-xl">🚀</span>
                <div>
                  <div className="text-xs font-bold text-indigo-400 uppercase tracking-wider mb-1">Recommendation</div>
                  <p className="text-sm text-gray-200 leading-relaxed">{summary.recommendation}</p>
                </div>
              </div>
            </div>
          </div>
          <div className="mt-4 text-[10px] text-gray-500 text-right">
            Updated: {timeAgo(summary.generated_at)}
          </div>
        </div>
      );
    };

    function generateInsights(data) {
      if (!data) return [];
      const insights = [];
      const safeVal = (v) => v || 0;
      const waitlistCount = safeVal(data.funnel?.waitlist);
      const signedUpCount = safeVal(data.funnel?.signedUp);
      
      if (waitlistCount > signedUpCount * 5) {
        insights.push({
          type: 'opportunity',
          icon: '💡',
          title: 'Waitlist conversion opportunity',
          text: `${waitlistCount} waitlist signups but only ${signedUpCount} converted (${Math.round(signedUpCount/Math.max(1, waitlistCount)*100)}%). Target 10% conversion by sending personalized invites.`,
          action: 'Go to Waitlist →',
          link: '#/waitlist'
        });
      }
      
      const paidUsers = (data.usersList || []).filter(u => u.plan && u.plan !== 'free').length;
      if (paidUsers === 0 && (data.usersList || []).length > 0) {
        insights.push({
          type: 'critical',
          icon: '💰',
          title: 'No paying users yet',
          text: `All ${(data.usersList || []).length} users are on free plan. Revenue = $0. First priority: demonstrate Pro value to convert your most active user.`,
          action: 'View Users →',
          link: '#/users'
        });
      }
      
      const activeUsers = (data.usersList || []).filter(u => u.status === 'active').length;
      if (activeUsers === 0 && (data.usersList || []).length > 0) {
        insights.push({
          type: 'warning',
          icon: '📉',
          title: 'No active users this week',
          text: `None of your ${(data.usersList || []).length} users were active in the last 7 days. Consider sending a re-engagement WhatsApp message or asking for direct feedback.`,
          action: 'Send nudge →',
          link: '#/users'
        });
      }
      
      const criticalSafety = (data.safety || []).filter(s => s.tier >= 2).length;
      if (criticalSafety > 0) {
        insights.push({
          type: 'critical',
          icon: '🚨',
          title: `${criticalSafety} critical safety event(s) this week`,
          text: `Tier 2+ distress detected. Parent alerts were sent. Review the events immediately to ensure appropriate follow-up.`,
          action: 'View Safety →',
          link: '#/safety'
        });
      }
      
      const proPrice = 7.99;
      const familyPrice = 11.99;
      const avgPrice = (proPrice + familyPrice) / 2;
      const usersFor1MARR = Math.ceil(1000000 / 12 / avgPrice);
      insights.push({
        type: 'info',
        icon: '🎯',
        title: 'Path to $1M ARR',
        text: `You need ~${usersFor1MARR.toLocaleString()} paying users at avg $${avgPrice.toFixed(2)}/mo. At 15% free→paid conversion, that's ${Math.ceil(usersFor1MARR/0.15).toLocaleString()} total users to acquire.`,
        action: 'Growth Simulator →',
        link: '#/finance'
      });
      
      return insights;
    }

    
    function Dashboard({ data }) { 
      if (!data) return null;
      
      const totalUsers = data.users ? data.users.length : 0;
      const activeUsers = data.users ? data.users.filter(u => u.status === 'active').length : 0;
      const waitlistTotal = data.funnel ? data.funnel.waitlist : 0;
      const signedUp = data.funnel ? data.funnel.signedUp : 0;
      const imported = data.funnel ? data.funnel.imported : 0;
      const active7d = data.funnel ? data.funnel.active7d : 0;
      
      const mrr = data.finance?.revenue?.mrr || 0;
      const totalCost = data.finance?.totalCost || 0;

      const usersSparkline = [totalUsers-2 < 0 ? 0 : totalUsers-2, totalUsers-1 < 0 ? 0 : totalUsers-1, totalUsers];
      const mrrSparkline = [mrr*0.9, mrr*0.95, mrr];
      const activeSparkline = [activeUsers-1 < 0 ? 0 : activeUsers-1, activeUsers, activeUsers];

      const insights = generateInsights({ funnel: data.funnel, usersList: data.users, safety: data.safety });
      
      return (
        <div className="space-y-6">
          <SummaryCard tabName="Dashboard" summaries={data.summaries} />

          <div className="grid grid-cols-4 gap-4">
            <a href="#/users" className="card hover:bg-white/5 transition cursor-pointer">
              <div className="text-xs text-gray-400 mb-1">Total Users</div>
              <div className="flex items-end justify-between">
                <div>
                  <div className="text-2xl font-bold">{totalUsers}</div>
                  <div className="text-xs text-green-400 mt-1">Active DB</div>
                </div>
                <Sparkline data={usersSparkline} color="#4ade80" />
              </div>
            </a>
            <a href="#/finance" className="card hover:bg-white/5 transition cursor-pointer">
              <div className="text-xs text-gray-400 mb-1">MRR</div>
              <div className="flex items-end justify-between">
                <div>
                  <div className="text-2xl font-bold">${mrr.toFixed(2)}</div>
                  <div className="text-xs text-gray-400 mt-1">Based on plans</div>
                </div>
                <Sparkline data={mrrSparkline} color="#94a3b8" />
              </div>
            </a>
            <a href="#/users" className="card hover:bg-white/5 transition cursor-pointer">
              <div className="text-xs text-gray-400 mb-1">Active Users (7d)</div>
              <div className="flex items-end justify-between">
                <div>
                  <div className="text-2xl font-bold">{activeUsers} <span className="text-sm font-normal text-gray-400">({totalUsers ? Math.round((activeUsers/totalUsers)*100) : 0}%)</span></div>
                  <div className="text-xs text-gray-400 mt-1">Has 7d messages</div>
                </div>
                <Sparkline data={activeSparkline} color="#3b82f6" />
              </div>
            </a>
            <a href="#/safety" className="card flex items-center justify-between hover:bg-white/5 transition cursor-pointer">
              <div>
                <div className="text-xs text-gray-400 mb-1">Health Score</div>
                <div className="text-3xl font-bold">{100 - ((data.safety || []).filter(s => s.tier >= 2).length * 5 || 0)}</div>
              </div>
              <div className={`w-4 h-4 rounded-full ${(data.safety || []).some(s => s.tier >= 2) ? 'bg-red-500 shadow-[0_0_12px_rgba(239,68,68,0.6)]' : 'bg-green-500 shadow-[0_0_12px_rgba(34,197,94,0.6)]'}`}></div>
            </a>
          </div>

          <div className="grid grid-cols-2 gap-6">
            <a href="#/waitlist" className="card hover:bg-white/5 transition cursor-pointer block">
              <h3 className="font-semibold mb-4">Conversion Funnel</h3>
              <div className="flex justify-between items-center text-sm font-medium">
                <div className="flex flex-col items-center"><div className="w-16 h-16 rounded-full border-4 border-gray-700 flex items-center justify-center mb-2 hover:scale-110 transition">{waitlistTotal}</div>Waitlist</div>
                <div className="text-xs text-gray-500">→ {waitlistTotal ? Math.round((signedUp/waitlistTotal)*100) : 0}%</div>
                <div className="flex flex-col items-center"><div className="w-16 h-16 rounded-full border-4 border-blue-500 flex items-center justify-center mb-2 hover:scale-110 transition">{signedUp}</div>Signed Up</div>
                <div className="text-xs text-gray-500">→ {signedUp ? Math.round((imported/signedUp)*100) : 0}%</div>
                <div className="flex flex-col items-center"><div className="w-16 h-16 rounded-full border-4 border-purple-500 flex items-center justify-center mb-2 hover:scale-110 transition">{imported}</div>Imported</div>
                <div className="text-xs text-gray-500">→ {imported ? Math.round((active7d/imported)*100) : 0}%</div>
                <div className="flex flex-col items-center"><div className="w-16 h-16 rounded-full border-4 border-green-500 flex items-center justify-center mb-2 hover:scale-110 transition">{active7d}</div>Active</div>
              </div>
            </a>
            
            <a href="#/finance" className="card hover:bg-white/5 transition cursor-pointer block">
              <h3 className="font-semibold mb-4">Revenue vs Cost</h3>
              <div className="flex h-24 items-end gap-4">
                <div className="w-1/2 bg-green-500/20 border border-green-500 rounded-t-lg relative group transition-all" style={{ height: `${Math.min(100, Math.max(5, (mrr/100)*100))}%` }}>
                  <div className="absolute -top-6 w-full text-center text-xs font-bold text-green-400">${mrr.toFixed(2)}</div>
                  <div className="absolute bottom-2 w-full text-center text-xs text-gray-400">MRR</div>
                </div>
                <div className="w-1/2 bg-red-500/20 border border-red-500 rounded-t-lg relative group transition-all" style={{ height: `${Math.min(100, Math.max(5, (totalCost/100)*100))}%` }}>
                  <div className="absolute -top-6 w-full text-center text-xs font-bold text-red-400">${totalCost.toFixed(2)}</div>
                  <div className="absolute bottom-2 w-full text-center text-xs text-gray-400">Cost</div>
                </div>
              </div>
              <div className="mt-4 text-center text-sm font-semibold text-gray-400">Gross Margin: <span className="text-white">{mrr > 0 ? Math.round(((mrr - totalCost)/mrr)*100) : 0}%</span></div>
            </a>
          </div>

          <div className="card bg-[#111827] border-blue-500/30 shadow-[0_0_20px_rgba(59,130,246,0.05)]">
            <h3 className="font-semibold mb-4 flex items-center gap-2"><span className="text-blue-400">✨</span> CEO Insights</h3>
            <div className="grid grid-cols-2 gap-4">
              {(insights || []).map((ins, i) => (
                <a key={i} href={ins.link} className="p-4 rounded-xl border border-white/5 bg-white/5 flex gap-4 hover:bg-white/10 transition cursor-pointer">
                  <div className="text-2xl">{ins.icon}</div>
                  <div>
                    <div className="font-semibold text-sm mb-1">{ins.title}</div>
                    <div className="text-xs text-gray-400 leading-relaxed mb-3">{ins.text}</div>
                    <div className="text-xs text-blue-400 font-semibold">{ins.action}</div>
                  </div>
                </a>
              ))}
              {insights.length === 0 && (
                <div className="col-span-2 text-center text-gray-500 text-sm py-4">No new insights. You're doing great!</div>
              )}
            </div>
          </div>
        </div>
      );
    }


    const Sparkline = ({ data, color = "#3b82f6" }) => {
      if (!data || data.length === 0) return null;
      const min = Math.min(...data);
      const max = Math.max(...data);
      const range = max - min || 1;
      const pts = (data || []).map((d, i) => `${(i / (data.length - 1)) * 40},${20 - ((d - min) / range) * 20}`).join(' ');
      return (
        <svg width="40" height="20" viewBox="0 0 40 20" style={{ overflow: 'visible' }}>
          <polyline points={pts} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      );
    };

    
    
    function UserDrawer({ user, onClose, isWaitlist }) {
      const [onboarding, setOnboarding] = useState(false);
      const [deleting, setDeleting] = useState(false);
      const [copied, setCopied] = useState(false);
      const [coupon, setCoupon] = useState('');
      
      const parseDevice = (ua) => {
         if (!ua) return 'Unknown';
         if (ua.includes('iPhone')) return 'iPhone';
         if (ua.includes('iPad')) return 'iPad';
         if (ua.includes('Android')) return 'Android';
         if (ua.includes('Mac OS')) return 'Mac';
         if (ua.includes('Windows')) return 'Windows';
         return 'Desktop/Other';
      };

      const handleDelete = async () => {
        if (!confirm('Are you sure you want to delete this request?')) return;
        setDeleting(true);
        try {
          const res = await fetch(`${API}?action=delete_waitlist`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'x-admin-pin': PIN },
            body: JSON.stringify({ id: user.id })
          });
          if (res.ok) {
             alert('Deleted successfully');
             onClose();
             window.location.reload();
          } else {
             alert('Failed to delete');
          }
        } catch(e) {
          console.error(e);
          alert('Error during deletion');
        } finally {
          setDeleting(false);
        }
      };

      const handleOnboard = async () => {
        setOnboarding(true);
        try {
          const email = user.email || `user_${(user.id || 'new').substring(0,8)}@temp.abu-genie.com`;
          const res = await fetch(`${API}?action=add_user`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'x-admin-pin': PIN },
            body: JSON.stringify({
              name: user.name || 'New User',
              email: email,
              phone: user.phone || '',
              language: 'he',
              waitlistId: isWaitlist ? user.id : undefined,
              coupon: coupon
            })
          });
          if (res.ok) {
             alert('User onboarded successfully! Magic link sent to ' + email + (coupon ? ' with coupon ' + coupon : ''));
             onClose();
             window.location.reload();
          } else {
             alert('Failed to onboard user');
          }
        } catch(e) {
          console.error(e);
          alert('Error during onboarding');
        } finally {
          setOnboarding(false);
        }
      };
      
      const deviceOS = parseDevice(user.user_agent);
      const reqDate = new Date(user.created_at);
      
      return (
        <div className="fixed inset-0 z-50 flex justify-end">
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
          <div className="relative w-[50vw] min-w-[500px] bg-surface h-full shadow-2xl border-l border-white/10 flex flex-col animate-slide-in-right overflow-y-auto">
            
            <div className="p-6 border-b border-white/5 flex justify-between items-center bg-white/5 sticky top-0 z-10 backdrop-blur-xl">
              <h2 className="text-xl font-bold">{isWaitlist ? 'Waitlist Registration' : 'User Details'}</h2>
              <div className="flex gap-2">
                {isWaitlist && (
                  <button onClick={handleDelete} disabled={deleting} className="px-3 py-1.5 bg-red-500/10 text-red-400 hover:bg-red-500/20 rounded-lg text-sm font-medium transition disabled:opacity-50">
                    {deleting ? 'Deleting...' : 'Delete Request'}
                  </button>
                )}
                <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full transition"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
              </div>
            </div>
            
            <div className="p-6 flex-1 space-y-8">
                <div className="flex items-center gap-4 bg-white/5 p-4 rounded-xl border border-white/5 shadow-inner">
                   <div className="w-14 h-14 rounded-full bg-blue-500 flex items-center justify-center text-xl font-bold text-white shadow-lg">
                      {((user.display_name || user.name || "U")[0]).toUpperCase()}
                   </div>
                   <div>
                      <div className="text-lg font-bold">{user.display_name || user.name || "Unknown"}</div>
                      <div className="text-sm text-gray-400">{user.parent_email || user.email || user.phone || 'No contact info'}</div>
                   </div>
                   {isWaitlist && <span className="ml-auto badge-amber">Waiting for Onboarding</span>}
                   {!isWaitlist && <span className={`ml-auto badge-${user.status==='active'?'green':'gray'}`}>{user.status}</span>}
                </div>

                {isWaitlist ? (
                  <div className="space-y-6">
                    <div className="space-y-4">
                      <h4 className="font-semibold text-gray-300 border-b border-white/10 pb-2">Registration Metadata</h4>
                      <div className="grid grid-cols-2 gap-4 text-sm">
                        <div className="bg-white/5 p-4 rounded-xl border border-white/5">
                           <span className="text-gray-500 block mb-1 text-xs uppercase tracking-wider">Contact Info</span>
                           <div className="font-semibold text-gray-200">{user.phone || '-'}</div>
                        </div>
                        <div className="bg-white/5 p-4 rounded-xl border border-white/5">
                           <span className="text-gray-500 block mb-1 text-xs uppercase tracking-wider">Location</span>
                           <div className="font-semibold text-gray-200">{user.country || 'Unknown'}</div>
                        </div>
                        <div className="bg-white/5 p-4 rounded-xl border border-white/5">
                           <span className="text-gray-500 block mb-1 text-xs uppercase tracking-wider">Platform & Device</span>
                           <div className="font-semibold text-gray-200">{deviceOS}</div>
                        </div>
                        <div className="bg-white/5 p-4 rounded-xl border border-white/5">
                           <span className="text-gray-500 block mb-1 text-xs uppercase tracking-wider">Request Date</span>
                           <div className="font-semibold text-gray-200">{reqDate.toLocaleDateString()}</div>
                        </div>
                      </div>
                    </div>

                    <div className="card border-blue-500/30 bg-blue-500/5 mt-4">
                      <h3 className="font-semibold text-blue-400 mb-2 flex items-center gap-2">🚀 Onboard User</h3>
                      <p className="text-sm text-gray-400 mb-4 leading-relaxed">This will automatically provision a new clean workspace for this user, link their phone number to Abu, and dispatch a magic link email.</p>
                      
                      <div className="mb-4 bg-black/20 p-4 rounded-xl border border-white/5">
                        <label className="block text-xs font-semibold text-gray-300 mb-2 uppercase tracking-wider">Promo Code</label>
                        <input 
                          type="text" 
                          value={coupon} 
                          onChange={e => setCoupon(e.target.value)} 
                          placeholder="e.g. NOA20" 
                          className="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-2.5 text-sm text-white outline-none focus:border-blue-500 focus:bg-white/10 transition-colors" 
                        />
                      </div>

                      <button 
                        onClick={handleOnboard}
                        disabled={onboarding}
                        className="w-full bg-blue-600 hover:bg-blue-500 text-white py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 transition disabled:opacity-50"
                      >
                        {onboarding ? 'Provisioning...' : 'Onboard User Automatically'}
                      </button>
                    </div>
                  </div>
                
                ) : (
                  <div className="space-y-6">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="card p-4 border border-blue-500/20 bg-blue-500/5">
                        <div className="text-xs text-gray-500 mb-1 uppercase tracking-wider font-semibold">Current Plan</div>
                        <div className="font-bold capitalize text-blue-400 text-lg flex items-center gap-2">
                           {user.plan || 'Free'}
                        </div>
                      </div>
                      <div className="card p-4 border border-white/5">
                        <div className="text-xs text-gray-500 mb-1 uppercase tracking-wider font-semibold">Social Graph</div>
                        <div className="font-bold text-lg text-white">{user.nodes || 0} Nodes</div>
                      </div>
                    </div>

                    <div className="space-y-4">
                      <h4 className="font-semibold text-gray-300 border-b border-white/10 pb-2">User Profile & Metadata</h4>
                      <div className="grid grid-cols-1 gap-3 text-sm">
                        <div className="flex justify-between items-center bg-white/5 p-3 rounded-lg"><span className="text-gray-500">User ID</span><span className="font-mono text-xs bg-black/50 px-2 py-1 rounded select-all cursor-copy hover:text-white transition" onClick={(e) => { navigator.clipboard.writeText(user.user_id); setCopied(true); setTimeout(()=>setCopied(false), 2000); }}>{user.user_id} {copied ? '✅' : '📋'}</span></div>
                        <div className="flex justify-between items-center bg-white/5 p-3 rounded-lg"><span className="text-gray-500">Auth Email</span><span className="font-medium text-gray-300">{user.email || 'No email associated'}</span></div>
                        <div className="flex justify-between items-center bg-white/5 p-3 rounded-lg"><span className="text-gray-500">Phone (WhatsApp)</span><span className="font-medium text-gray-300">{user.phone || 'No phone mapped'}</span></div>
                        <div className="flex justify-between items-center bg-white/5 p-3 rounded-lg"><span className="text-gray-500">Registered</span><span className="font-medium text-gray-300">{new Date(user.created_at).toLocaleString()}</span></div>
                      </div>
                    </div>
                  </div>
                )}

            </div>
          </div>
          <style dangerouslySetInnerHTML={{__html: `
            @keyframes slideInRight { from { transform: translateX(100%); } to { transform: translateX(0); } }
            .animate-slide-in-right { animation: slideInRight 0.3s cubic-bezier(0.16, 1, 0.3, 1); }
          `}} />
        </div>
      );
    }


    function UserDetail({ userId, onClose }) {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);

      useEffect(() => {
        async function fetchDetail() {
          try {
            const res = await fetch(`${API}?action=user_detail&user_id=${userId}`, {
              headers: { 'x-admin-pin': PIN }
            });
            if (!res.ok) throw new Error('Failed to fetch user details');
            const json = await res.json();
            setData(json);
          } catch (err) {
            setError(err.message);
          } finally {
            setLoading(false);
          }
        }
        fetchDetail();
      }, [userId]);

      if (loading) return <div className="text-center py-20 text-white">Loading...</div>;
      if (error) return <div className="text-center py-20 text-red-500">Error: {error}</div>;
      if (!data) return null;

      const { profile, stats, subscription, nodes, top_relationships, recent_conversations, safety_events, usage } = data;

      return (
        <div className="space-y-6 text-white rtl" dir="rtl">
          <div className="bg-white/5 border border-white/10 rounded-2xl p-6 backdrop-blur-md relative">
            <button onClick={onClose} className="absolute top-6 left-6 text-gray-400 hover:text-white flex items-center gap-2 transition-colors">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
              Back
            </button>
            <div className="flex items-start gap-4">
              <div className="w-16 h-16 rounded-full bg-blue-500 text-white flex items-center justify-center font-bold text-2xl">
                {((profile.display_name || "U")[0]).toUpperCase()}
              </div>
              <div className="flex-1">
                <h1 className="text-3xl font-black">{profile.display_name || 'Unknown'}</h1>
                <p className="text-gray-400">{profile.email}</p>
              </div>
            </div>
          </div>
          <div className="grid grid-cols-4 gap-4">
            <div className="card text-center"><div className="text-sm text-gray-400">Nodes</div><div className="text-2xl font-bold">{stats.total_nodes}</div></div>
            <div className="card text-center"><div className="text-sm text-gray-400">Edges</div><div className="text-2xl font-bold">{stats.total_edges}</div></div>
            <div className="card text-center"><div className="text-sm text-gray-400">Messages</div><div className="text-2xl font-bold">{stats.total_messages}</div></div>
            <div className="card text-center"><div className="text-sm text-gray-400">Cost MTD</div><div className="text-2xl font-bold">${(usage.gemini_cost_mtd || 0).toFixed(2)}</div></div>
          </div>
        </div>
      );
    }

    function Users({ data }) { 
      if (!data) return null;
      const [filter, setFilter] = useState('');
      const [tab, setTab] = useState('active'); 
      const [selectedUser, setSelectedUser] = useState(null);

      const users = data.users ? data.users.filter(u => (u.display_name || u.name || '').toLowerCase().includes(filter.toLowerCase()) || (u.email || '').toLowerCase().includes(filter.toLowerCase())) : [];
      const waitlist = data.waitlist ? data.waitlist.filter(w => (w.phone || '').includes(filter)) : [];
      
      if (selectedUser && !selectedUser.isWaitlist) {
        return <UserDetail userId={selectedUser.user_id} onClose={() => setSelectedUser(null)} />;
      }
      
      return (
        <div className="space-y-6">
          <SummaryCard tabName="Users" summaries={data.summaries} />
          <div className="flex justify-between items-center gap-4 bg-white/5 p-4 rounded-2xl border border-white/5">
            <div className="flex bg-black/40 p-1 rounded-xl">
               <button onClick={() => setTab('active')} className={`px-6 py-2 rounded-lg text-sm font-semibold transition-all ${tab==='active'?'bg-blue-600 text-white':'text-gray-400 hover:text-white'}`}>Active Users ({users.length})</button>
               <button onClick={() => setTab('backlog')} className={`px-6 py-2 rounded-lg text-sm font-semibold transition-all ${tab==='backlog'?'bg-blue-600 text-white':'text-gray-400 hover:text-white'}`}>Waitlist ({waitlist.length})</button>
            </div>
            <input type="text" placeholder="Search..." className="bg-black/40 border border-white/10 rounded-xl px-4 py-2 text-sm text-white outline-none focus:border-blue-500" value={filter} onChange={e => setFilter(e.target.value)} />
          </div>
          <div className="card p-0 overflow-x-auto">
            <table className="w-full text-left">
              <thead>
                <tr className="border-b border-white/10 bg-white/5">
                  <th className="p-4">Name</th>
                  <th className="p-4">Contact</th>
                  <th className="p-4">Plan</th>
                  <th className="p-4">Status</th>
                  <th className="p-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {tab === 'active' && users.map((u, i) => (
                  <tr key={i} className="hover:bg-white/5 cursor-pointer" onClick={() => setSelectedUser({...u, isWaitlist: false})}>
                    <td className="p-4 font-bold">{u.display_name || u.name}</td>
                    <td className="p-4 text-gray-400">{u.email || u.phone}</td>
                    <td className="p-4 capitalize">{u.plan || 'Free'}</td>
                    <td className="p-4"><span className={`badge-${u.status==='active'?'green':'gray'}`}>{u.status}</span></td>
                    <td className="p-4 text-right text-blue-400 font-bold">Details →</td>
                  </tr>
                ))}
                {tab === 'backlog' && waitlist.map((w, i) => (
                  <tr key={i} className="hover:bg-white/5 cursor-pointer" onClick={() => setSelectedUser({...w, isWaitlist: true})}>
                    <td className="p-4 font-bold">{w.phone}</td>
                    <td className="p-4 text-gray-400">{w.country}</td>
                    <td className="p-4">{w.source}</td>
                    <td className="p-4"><span className="badge-amber">Waiting</span></td>
                    <td className="p-4 text-right text-blue-400 font-bold">Onboard →</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {selectedUser && selectedUser.isWaitlist && <UserDrawer user={selectedUser} isWaitlist={true} onClose={() => setSelectedUser(null)} />}
        </div>
      );
    }


    function Waitlist({ data }) { 
      if (!data) return null;
      return (
        <div className="space-y-4">
          <SummaryCard tabName="Waitlist" summaries={data.summaries} />
          <div className="flex justify-between items-center">
            <div className="text-2xl font-bold">{(data.waitlist || []).length} Signups</div>
          </div>
          <div className="card p-0">
            <table>
              <thead><tr><th>Phone</th><th>Country</th><th>Source</th><th>Date</th></tr></thead>
              <tbody>
                {(data.waitlist || []).map((w, i) => (
                  <tr key={i}><td>{w.phone}</td><td>{w.country}</td><td>{w.source}</td><td>{new Date(w.created_at).toLocaleDateString()}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      );
    }

    function Feedback({ data }) { 
      if (!data) return null;
      return (
        <div className="space-y-4">
          <SummaryCard tabName="Feedback" summaries={data.summaries} />
          <div className="grid grid-cols-2 gap-4">
            {(data.feedback || []).map(f => (
              <div key={f.id} className="card flex flex-col gap-2">
                <div className="flex justify-between items-center"><span className="badge-blue">{f.type}</span><span className="text-xs text-gray-500">{new Date(f.created).toLocaleDateString()}</span></div>
                <div className="text-lg text-right" dir="rtl">{f.text}</div>
                <div className="text-xs text-gray-400">— {f.user}</div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    function Safety({ data }) { 
      if (!data) return null;
      return (
        <div className="space-y-6">
          <SummaryCard tabName="Safety" summaries={data.summaries} />
          <div className="card p-0">
            <table>
              <thead><tr><th>Tier</th><th>User</th><th>Message</th><th>Time</th></tr></thead>
              <tbody>
                {(data.safety || []).map((s, i) => (
                  <tr key={i}>
                    <td><span className={`badge-${s.tier>=2?'red':'amber'}`}>T{s.tier}</span></td>
                    <td className="font-bold">{s.userName}</td>
                    <td dir="rtl" className="text-gray-300">{s.message_preview}</td>
                    <td className="text-xs text-gray-500">{new Date(s.created_at).toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      );
    }

    function Finance({ data }) {
      if (!data) return null;
      const fpa = data.finance_fpa || {};
      
      const {
        ytdActual = 0,
        mtdActual = 0,
        annualBudget = 0,
        annualForecast = 0,
        mrr = 0,
        arr = 0,
        activeUsers = 1,
        softwareList = [],
        topUsers = [],
        topFeatures = [],
        aiAnalysis = "Analyzing YTD data...",
        currentYear = 2026,
        currentMonthStr = "Feb"
      } = fpa;

      const [activeTab, setActiveTab] = useState('Annual');

      const formatK = (val) => '$' + (val / 1000).toFixed(1) + 'K';
      const formatCurrency = (val) => '$' + val.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
      const formatPct = (val) => (val > 0 ? '+' : '') + val.toFixed(1) + '%';
      
      const annualGap = annualBudget - annualForecast;
      const annualVarPct = annualBudget > 0 ? (annualGap / annualBudget) * 100 : 0;
      const isOverBudget = annualForecast > annualBudget;

      const gaugeFillPct = Math.min(100, Math.max(0, (ytdActual / (annualBudget || 1)) * 100));
      
      const startBudget = annualBudget;
      let runningTotal = startBudget;
      const bridgeBars = softwareList.map(sw => {
         const diff = sw.forecast - sw.budget;
         const previous = runningTotal;
         runningTotal += diff;
         return { name: sw.vendor, diff, start: previous, end: runningTotal, color: diff > 0 ? '#ef4444' : '#22c55e' };
      }).sort((a,b) => Math.abs(b.diff) - Math.abs(a.diff)).slice(0, 5);

      return (
        <div className="text-gray-100 bg-[#0A0F1C] min-h-screen -m-6 p-8 font-sans">
          
          <div className="mb-8">
            <h1 className="text-3xl font-light text-white mb-2">{currentYear} — {currentMonthStr} YTD</h1>
            <div className="flex items-center gap-3">
              <h2 className="text-xl font-medium text-gray-300">FP&A Executive Summary</h2>
              <span className={`text-xs px-2 py-1 rounded ${isOverBudget ? 'bg-red-500/20 text-red-400' : 'bg-green-500/20 text-green-400'}`}>
                {Math.abs(annualVarPct).toFixed(1)}% {isOverBudget ? 'over budget' : 'under budget'}
              </span>
            </div>
          </div>

          <div className="bg-white/5 border border-white/10 rounded-xl p-6 mb-8 flex gap-6 shadow-lg relative overflow-hidden">
            <div className="absolute left-0 top-0 bottom-0 w-1 bg-blue-500"></div>
            <div className="w-8 h-8 rounded bg-blue-500/20 text-blue-400 flex items-center justify-center flex-shrink-0">
               <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
            </div>
            <div className="flex-1">
              <h3 className="text-sm font-semibold text-gray-300 uppercase tracking-widest mb-3">AI FP&A Summary</h3>
              <p className="text-gray-300 text-sm leading-relaxed">{aiAnalysis || 'Data syncing for FP&A analysis...'}</p>
            </div>
          </div>

          <div className="flex border-b border-white/10 mb-8 text-sm">
             {['YTD Performance', 'Annual', 'Software', 'Users', 'Features'].map(tab => (
                <button 
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`px-6 py-3 font-medium transition-colors ${activeTab === tab ? 'text-blue-400 border-b-2 border-blue-400' : 'text-gray-500 hover:text-gray-300'}`}
                >
                  {tab}
                </button>
             ))}
          </div>

          {activeTab === 'Annual' && (
            <>
              <div className="grid grid-cols-3 gap-6 mb-8">
                <div className="bg-white/5 border border-white/10 rounded-xl p-6">
                  <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-2">Annual Budget</div>
                  <div className="text-3xl font-light text-blue-400 mb-1">{formatK(annualBudget)}</div>
                  <div className="text-xs text-gray-600">FY {currentYear}</div>
                </div>
                <div className="bg-white/5 border border-white/10 rounded-xl p-6">
                  <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-2">Annual Forecast</div>
                  <div className={`text-3xl font-light mb-1 ${isOverBudget ? 'text-red-400' : 'text-green-400'}`}>{formatK(annualForecast)}</div>
                  <div className="text-xs text-gray-600">incl. Projected Run-Rate</div>
                </div>
                <div className="bg-white/5 border border-white/10 rounded-xl p-6 relative">
                  <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-2">Annual Savings</div>
                  <div className={`text-3xl font-light mb-1 ${!isOverBudget ? 'text-green-400' : 'text-red-400'}`}>{formatK(annualGap)}</div>
                  <div className="text-xs text-gray-600">{formatPct(annualVarPct)} vs budget</div>
                  {!isOverBudget && <div className="absolute top-6 right-6 text-green-400"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg></div>}
                </div>
              </div>

              <div className="grid grid-cols-3 gap-6">
                <div className="bg-white/5 border border-white/10 rounded-xl p-6 flex flex-col">
                  <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-6">Budget Gauge</div>
                  <div className="flex-1 flex flex-col items-center justify-center relative">
                     <div className="w-48 h-24 overflow-hidden relative">
                        <div className="w-48 h-48 border-[16px] border-white/10 rounded-full absolute top-0 left-0"></div>
                        <div className="w-48 h-48 border-[16px] border-blue-500 rounded-full absolute top-0 left-0" style={{ clipPath: 'polygon(0 0, 100% 0, 100% 50%, 0 50%)', transform: `rotate(${(gaugeFillPct/100)*180 - 180}deg)`, transformOrigin: 'center' }}></div>
                     </div>
                     <div className="absolute bottom-0 text-center">
                       <div className="text-xs text-gray-500 uppercase tracking-wider mb-1">YTD Actuals</div>
                       <div className="text-2xl font-bold text-red-400">{formatK(ytdActual)}</div>
                       <div className="text-[10px] text-gray-600">{gaugeFillPct.toFixed(1)}% of annual</div>
                     </div>
                  </div>
                  <div className="flex justify-between text-xs text-gray-500 mt-4 px-4">
                     <div className="text-center"><div>Annual</div><div>{formatK(annualBudget)}</div></div>
                     <div className="text-center"><div>YTD Bud</div><div>{formatK(annualBudget * ((fpa.daysPassed || 1)/365))}</div></div>
                     <div className="text-center"><div>YTD Act</div><div className="text-red-400">{formatK(ytdActual)}</div></div>
                  </div>
                </div>
                
                <div className="col-span-2 bg-white/5 border border-white/10 rounded-xl p-6">
                  <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-6">Budget → Actual Bridge (Annual)</div>
                  <div className="h-48 flex items-end justify-between px-8 relative mt-12 pb-6 border-b border-white/10">
                     <div className="flex flex-col items-center justify-end w-12 group relative">
                        <div className="absolute -top-6 text-[10px] text-gray-400 group-hover:text-white">{formatK(annualBudget)}</div>
                        <div className="w-full bg-blue-900 rounded-t" style={{ height: '100px' }}></div>
                        <div className="absolute -bottom-6 text-[10px] text-gray-500 whitespace-nowrap">Budget</div>
                     </div>
                     {bridgeBars.map((b, i) => (
                        <div key={i} className="flex flex-col items-center justify-end w-12 relative group" style={{ height: '100px' }}>
                           <div className="absolute text-[10px] font-semibold" style={{ bottom: `${(Math.min(b.start, b.end)/(annualBudget || 1))*100}%`, color: b.color, marginBottom: '20px' }}>{b.diff > 0 ? '+' : ''}{formatK(b.diff)}</div>
                           <div className="w-full rounded-sm opacity-80 group-hover:opacity-100" style={{ 
                             backgroundColor: b.color,
                             position: 'absolute',
                             bottom: `${(Math.min(b.start, b.end)/(annualBudget || 1))*100}%`,
                             height: `${(Math.abs(b.diff)/(annualBudget || 1))*100}%` 
                           }}></div>
                           <div className="absolute -bottom-6 text-[10px] text-gray-500 whitespace-nowrap truncate w-16 text-center">{b.name}</div>
                        </div>
                     ))}
                     <div className="flex flex-col items-center justify-end w-12 group relative">
                        <div className="absolute -top-6 text-[10px] text-gray-400 group-hover:text-white">{formatK(annualForecast)}</div>
                        <div className="w-full bg-blue-500 rounded-t" style={{ height: `${(annualForecast/(annualBudget || 1))*100}px` }}></div>
                        <div className="absolute -bottom-6 text-[10px] text-gray-500 whitespace-nowrap">Actual</div>
                     </div>
                  </div>
                </div>
              </div>
            </>
          )}

          {activeTab === 'Software' && (
            <div className="bg-white/5 border border-white/10 rounded-xl overflow-hidden">
               <div className="p-6 border-b border-white/10 flex justify-between items-end">
                 <div>
                   <h3 className="text-lg font-medium text-gray-200">Software — Full Year Forecast</h3>
                   <div className="text-xs text-gray-500 mt-1">FY {currentYear} Budget vs Forecast by vendor · {softwareList.length} vendors</div>
                 </div>
                 <div className="text-sm font-medium text-gray-400">
                    Total gap: <span className={`font-bold ${annualGap < 0 ? 'text-red-400' : 'text-green-400'}`}>{formatK(annualGap)}</span>
                 </div>
               </div>
               <table className="w-full text-left text-sm">
                 <thead>
                   <tr className="bg-black/20 text-xs font-semibold text-gray-500 tracking-wider">
                     <th className="p-4 border-b border-white/10 w-1/4">VENDOR</th>
                     <th className="p-4 border-b border-white/10">BUDGET</th>
                     <th className="p-4 border-b border-white/10">FORECAST</th>
                     <th className="p-4 border-b border-white/10">GAP</th>
                     <th className="p-4 border-b border-white/10">VAR %</th>
                     <th className="p-4 border-b border-white/10">REASON</th>
                   </tr>
                 </thead>
                 <tbody className="divide-y divide-white/5">
                   {softwareList.map((sw, i) => (
                     <tr key={i} className="hover:bg-white/5 transition-colors">
                       <td className="p-4 font-medium text-gray-300">{sw.vendor}</td>
                       <td className="p-4 text-gray-400">{formatCurrency(sw.budget)}</td>
                       <td className="p-4 text-gray-400">{formatCurrency(sw.forecast)}</td>
                       <td className={`p-4 font-medium ${sw.gap < 0 ? 'text-red-400' : 'text-green-400'}`}>{formatCurrency(sw.gap)}</td>
                       <td className="p-4">
                         {sw.varPct !== 0 && (
                           <span className={`text-xs px-2 py-1 rounded ${sw.varPct < 0 ? 'bg-red-500/10 text-red-400' : 'bg-green-500/10 text-green-400'}`}>
                             {formatPct(sw.varPct)}
                           </span>
                         )}
                       </td>
                       <td className="p-4 text-gray-500 text-xs">{sw.reason}</td>
                     </tr>
                   ))}
                 </tbody>
               </table>
            </div>
          )}

          {activeTab === 'Users' && (
            <div className="bg-white/5 border border-white/10 rounded-xl overflow-hidden">
               <div className="p-6 border-b border-white/10">
                 <h3 className="text-lg font-medium text-gray-200">Top Users (YTD Consumption)</h3>
                 <div className="text-xs text-gray-500 mt-1">Infrastructure cost driven by high-engagement accounts. Average Cost Per User: {formatCurrency(ytdActual / activeUsers)}</div>
               </div>
               <table className="w-full text-left text-sm">
                 <thead>
                   <tr className="bg-black/20 text-xs font-semibold text-gray-500 tracking-wider">
                     <th className="p-4 border-b border-white/10">USER NAME</th>
                     <th className="p-4 border-b border-white/10">API CALLS</th>
                     <th className="p-4 border-b border-white/10 text-right">TOTAL COST</th>
                   </tr>
                 </thead>
                 <tbody className="divide-y divide-white/5">
                   {topUsers.map((u, i) => (
                     <tr key={i} className="hover:bg-white/5 transition-colors">
                       <td className="p-4 font-medium text-blue-400">{u.name}</td>
                       <td className="p-4 text-gray-400">{u.calls.toLocaleString()}</td>
                       <td className="p-4 font-medium text-red-400 text-right">{formatCurrency(u.cost)}</td>
                     </tr>
                   ))}
                   {topUsers.length === 0 && <tr><td colSpan="3" className="p-8 text-center text-gray-500">No user data available</td></tr>}
                 </tbody>
               </table>
            </div>
          )}

          {activeTab === 'Features' && (
            <div className="bg-white/5 border border-white/10 rounded-xl overflow-hidden">
               <div className="p-6 border-b border-white/10">
                 <h3 className="text-lg font-medium text-gray-200">Cost by Feature</h3>
                 <div className="text-xs text-gray-500 mt-1">YTD variable cost breakdown by application feature/operation.</div>
               </div>
               <table className="w-full text-left text-sm">
                 <thead>
                   <tr className="bg-black/20 text-xs font-semibold text-gray-500 tracking-wider">
                     <th className="p-4 border-b border-white/10">FEATURE / OPERATION</th>
                     <th className="p-4 border-b border-white/10 text-right">YTD COST</th>
                     <th className="p-4 border-b border-white/10 text-right">% OF VARIABLE SPEND</th>
                   </tr>
                 </thead>
                 <tbody className="divide-y divide-white/5">
                   {topFeatures.map((f, i) => (
                     <tr key={i} className="hover:bg-white/5 transition-colors">
                       <td className="p-4 font-medium text-purple-400 capitalize">{f.name.replace(/_/g, ' ')}</td>
                       <td className="p-4 font-medium text-red-400 text-right">{formatCurrency(f.cost)}</td>
                       <td className="p-4 text-gray-500 text-right">{ytdActual > 0 ? ((f.cost / ytdActual) * 100).toFixed(1) : 0}%</td>
                     </tr>
                   ))}
                   {topFeatures.length === 0 && <tr><td colSpan="3" className="p-8 text-center text-gray-500">No feature data available</td></tr>}
                 </tbody>
               </table>
            </div>
          )}

          {activeTab === 'YTD Performance' && (
             <div className="grid grid-cols-2 gap-6">
                <div className="bg-white/5 border border-white/10 rounded-xl p-6 text-center">
                   <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-2">YTD Budget</div>
                   <div className="text-4xl font-light text-blue-400">{formatK(annualBudget * ((fpa.daysPassed||1)/365))}</div>
                </div>
                <div className="bg-white/5 border border-white/10 rounded-xl p-6 text-center">
                   <div className="text-xs text-gray-500 font-semibold tracking-wider uppercase mb-2">YTD Actuals</div>
                   <div className="text-4xl font-light text-red-400">{formatK(ytdActual)}</div>
                </div>
                <div className="col-span-2 bg-white/5 border border-white/10 rounded-xl p-6">
                   <h3 className="font-semibold text-gray-300 mb-6">Unit Economics (Annualized)</h3>
                   <div className="grid grid-cols-4 gap-4">
                      <div>
                         <div className="text-xs text-gray-500 mb-1">ARPU (Revenue/User)</div>
                         <div className="text-xl text-green-400 font-medium">{formatCurrency((arr / activeUsers))}</div>
                      </div>
                      <div>
                         <div className="text-xs text-gray-500 mb-1">CPPU (Cost/User)</div>
                         <div className="text-xl text-red-400 font-medium">{formatCurrency((annualForecast / activeUsers))}</div>
                      </div>
                      <div>
                         <div className="text-xs text-gray-500 mb-1">LTV (Assumed 24mo)</div>
                         <div className="text-xl text-blue-400 font-medium">{formatCurrency((arr / activeUsers) * 2)}</div>
                      </div>
                      <div>
                         <div className="text-xs text-gray-500 mb-1">Gross Margin</div>
                         <div className="text-xl text-white font-medium">{arr > 0 ? Math.round(((arr - annualForecast)/arr)*100) : 0}%</div>
                      </div>
                   </div>
                </div>
             </div>
          )}
        </div>
      );
    }

    function Reports({ data }) { 
      if (!data) return null;
      return (
        <div className="space-y-6">
          <SummaryCard tabName="Reports" summaries={data.summaries} />
          <div className="card p-0">
            <table className="w-full text-left">
              <thead><tr><th>Date</th><th>User</th><th>Status</th><th>Report</th></tr></thead>
              <tbody>
                {(data.reports || []).map((r, i) => (
                  <tr key={i}>
                    <td>{new Date(r.date).toLocaleDateString()}</td>
                    <td>{r.userName}</td>
                    <td><span className={`badge-${r.status==='sent'?'green':'amber'}`}>{r.status}</span></td>
                    <td><a href={r.url} target="_blank" className="text-blue-400 font-bold">View →</a></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      );
    }

    function Config({ data }) { 
      if (!data) return null;
      return (
        <div className="space-y-6">
          <SummaryCard tabName="Config" summaries={data.summaries} />
          <div className="grid grid-cols-2 gap-6">
            {(data.config || []).map(c => (
              <div key={c.key} className="card">
                <div className="font-bold text-blue-400 mb-2">{c.key}</div>
                <pre className="bg-black/40 p-3 rounded-lg text-xs overflow-x-auto text-gray-300">
                  {typeof c.value === 'object' ? JSON.stringify(c.value, null, 2) : c.value}
                </pre>
              </div>
            ))}
          </div>
        </div>
      );
    }

    function System({ data }) { 
      if (!data) return null;
      return (
        <div className="space-y-6">
          <SummaryCard tabName="System" summaries={data.summaries} />
          <div className="grid grid-cols-3 gap-6">
            {(data.system || []).map((s, i) => (
              <div key={i} className="card flex justify-between items-center">
                <div><div className="font-bold">{s.name}</div><div className="text-xs text-gray-500">{s.message}</div></div>
                <div className={`w-3 h-3 rounded-full ${s.status === 'ok' ? 'bg-green-500' : 'bg-red-500'}`}></div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    function QA({ data }) { 
      if (!data) return null;
      const q = data.qa || {};
      return (
        <div className="space-y-6">
          <SummaryCard tabName="QA" summaries={data.summaries} />
          <div className="grid grid-cols-4 gap-4">
            <div className="card text-center"><div className="text-xs text-gray-400">Total</div><div className="text-2xl font-bold">{q.total}</div></div>
            <div className="card text-center"><div className="text-xs text-gray-400">Pass Rate</div><div className="text-2xl font-bold text-green-400">{q.passRate}%</div></div>
            <div className="card text-center"><div className="text-xs text-gray-400">Open Tickets</div><div className="text-2xl font-bold text-amber-400">{q.openTickets}</div></div>
            <div className="card text-center"><div className="text-xs text-gray-400">Blockers</div><div className="text-2xl font-bold text-red-400">{q.blockers}</div></div>
          </div>
          <div className="card">
            <h3 className="font-bold mb-4">Recent Tests</h3>
            <div className="space-y-2">
              {(q.tests || []).slice(0, 10).map((t, i) => (
                <div key={i} className="flex justify-between items-center border-b border-white/5 pb-2">
                  <span className="text-sm">{t.name}</span>
                  <span className={`badge-${t.status==='pass'?'green':'red'}`}>{t.status}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      );
    }

    
    function App() {
      const [isAuthenticated, setIsAuthenticated] = useState(false);
      const [pinInput, setPinInput] = useState('');
      const [pinError, setPinError] = useState(false);

      const [route, setRoute] = useState(window.location.hash || '#/');
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);

      useEffect(() => {
        const authData = JSON.parse(localStorage.getItem('abu_admin_auth') || 'null');
        if (authData && authData.pin === '0102') {
          setIsAuthenticated(true);
          window.PIN = '0102';
        }
      }, []);

      const handleLogin = (e) => {
         e.preventDefault();
         if (pinInput === '0102') {
            localStorage.setItem('abu_admin_auth', JSON.stringify({ pin: '0102', timestamp: Date.now() }));
            setIsAuthenticated(true);
            window.PIN = '0102';
         } else {
            setPinError(true);
            setPinInput('');
         }
      };

      useEffect(() => {
        const handleHash = () => setRoute(window.location.hash || '#/');
        window.addEventListener('hashchange', handleHash);
        return () => window.removeEventListener('hashchange', handleHash);
      }, []);

      useEffect(() => {
        if (!isAuthenticated) return;
        const loadData = async () => {
          setLoading(true);
          try {
            const activePin = window.PIN || '0102';
            const [dash, fin, cfg, qaStats, qaResults, qaTickets, reports, system, summaries] = await Promise.all([
              fetch(`${API}?pin=${activePin}&action=dashboard`).then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch(`${API}?pin=${activePin}&action=finance_fpa`).then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch(`${API}?pin=${activePin}&action=config`).then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch('https://srrmgsgbhjiimttjpgop.supabase.co/functions/v1/qa-api?pin=' + activePin + '&action=stats').then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch('https://srrmgsgbhjiimttjpgop.supabase.co/functions/v1/qa-api?pin=' + activePin + '&action=latest_results').then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch('https://srrmgsgbhjiimttjpgop.supabase.co/functions/v1/qa-api?pin=' + activePin + '&action=tickets&status=open').then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch(`${API}?pin=${activePin}&action=reports`).then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch(`${API}?pin=${activePin}&action=system`).then(r => r.ok ? r.json() : null).catch(()=>null),
              fetch(`${API}?pin=${activePin}&action=get_summaries`).then(r => r.ok ? r.json() : null).catch(()=>null)
            ]);
            
            setData({
              ...(dash || { users: [], waitlist: [], safety: [], funnel: {} }),
              finance_fpa: fin || {}, finance: {},
              qa: { 
                ...(qaStats || { total: 0, passRate: 0, openTickets: 0, blockers: 0 }), 
                tests: (qaResults?.results || []).map(r => ({ name: r.test_id, status: r.status })),
                tickets: (qaTickets?.tickets || []).map(t => ({ title: t.title, severity: t.severity, created_at: new Date(t.created_at).toLocaleDateString() }))
              },
              config: cfg || [],
              reports: reports || [],
              system: system || [],
              summaries: summaries || []
            });
          } catch(e) {
            console.error("API failed", e);
          } finally {
            setLoading(false);
          }
        };
        loadData();
      }, [isAuthenticated]);

      const navItems = [
        { id: '#/', label: 'Dashboard', icon: Icons.Home },
        { id: '#/users', label: 'Users', icon: Icons.Users },
        { id: '#/waitlist', label: 'Waitlist', icon: Icons.Waitlist },
        { id: '#/feedback', label: 'Feedback', icon: Icons.Feedback },
        { id: '#/safety', label: 'Safety', icon: Icons.Safety },
        { id: '#/finance', label: 'Finance', icon: Icons.Finance },
        { id: '#/reports', label: 'Reports', icon: Icons.Reports },
        { id: '#/config', label: 'Config', icon: Icons.Config },
        { id: '#/system', label: 'System', icon: Icons.System },
        { id: '#/qa', label: 'QA', icon: Icons.QA },
      ];

      if (!isAuthenticated) {
        return (
          <div className="min-h-screen flex items-center justify-center bg-[#030712]">
            <div className="card p-8 w-full max-w-sm text-center">
               <div className="text-5xl mb-4">🧞</div>
               <h1 className="text-2xl font-bold text-white mb-6">Abu Genie Admin</h1>
               <form onSubmit={handleLogin} className="space-y-4">
                  <input type="password" value={pinInput} onChange={e => setPinInput(e.target.value)} placeholder="PIN" className="w-full bg-black/50 border border-white/10 rounded-xl px-4 py-3 text-center text-white outline-none" />
                  <button type="submit" className="w-full bg-blue-600 hover:bg-blue-500 text-white font-bold py-3 rounded-xl transition-all">Unlock</button>
               </form>
            </div>
          </div>
        );
      }

      return (
        <div className="flex w-full min-h-screen">
          <div className="w-[220px] bg-sidebar border-r border-white/5 flex flex-col fixed h-full z-10">
            <div className="p-6 font-bold text-lg">🧞 Abu Genie Admin</div>
            <div className="flex-1 px-3 py-2 space-y-1">
              {navItems.map(item => (
                <a key={item.id} href={item.id} className={`nav-item ${route === item.id ? 'active' : ''}`}>
                  <item.icon /> {item.label}
                </a>
              ))}
            </div>
          </div>

          <div className="flex-1 ml-[220px] p-6 max-w-[1200px] mx-auto w-full">
            <div className="mb-8 flex justify-between items-center border-b border-white/5 pb-4">
              <h1 className="text-2xl font-bold">{navItems.find(n => n.id === route)?.label || 'Dashboard'}</h1>
              {loading && <div className="text-xs text-gray-500">Syncing...</div>}
            </div>
            
            {!data ? (
              <div className="text-center py-20 text-gray-500">Loading Data...</div>
            ) : (
              <>
                {route === '#/' && <Dashboard data={data} />}
                {route === '#/users' && <Users data={data} />}
                {route === '#/waitlist' && <Waitlist data={data} />}
                {route === '#/feedback' && <Feedback data={data} />}
                {route === '#/safety' && <Safety data={data} />}
                {route === '#/finance' && <Finance data={data} />}
                {route === '#/reports' && <Reports data={data} />}
                {route === '#/config' && <Config data={data} />}
                {route === '#/system' && <System data={data} />}
                {route === '#/qa' && <QA data={data} />}
              </>
            )}
          </div>
        </div>
      );
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<App />);
  