// CeyRide — Admin Portal v3 (Mobile-fixed, Image Manager, all modules)

// Site image slot schema — defines the manageable image positions in the frontend.
// 'src' values are fallbacks only; actual paths are loaded from get_homepage_config on login.
const UI_IMAGE_SCHEMA = [
  { id:1,  section:'Homepage', key:'hero_bg',           label:'Hero Background',     src:'', used:'Hero section background'          },
  // Featured Vehicle slots removed — featured vehicles are managed
  // via CMS → Vehicles → star toggle (vehicles.is_featured_home)
  // NOT via static image upload. See cms_vehicles.php action=feature.
  { id:2,  section:'Services', key:'vehicle_rental_img',label:'Vehicle Rental',      src:'', used:'Services — Vehicle Rental card'   },
  { id:3,  section:'Services', key:'hire_driver_img',   label:'Hire a Driver',       src:'',    used:'Services — Hire Driver card'      },
  { id:4,  section:'Services', key:'airport_img',       label:'Airport Transfers',   src:'',    used:'Services — Airport Transfer card' },
  { id:5,  section:'Services', key:'tour_img',          label:'Tour Packages',       src:'', used:'Services — Tour Packages card'    },
  { id:6,  section:'Services', key:'corporate_img',      label:'Corporate Fleet',     src:'', used:'Services — Corporate Fleet card'  },
  { id:7,  section:'About',    key:'about_main',         label:'About Main Image',    src:'', used:'About Us — main banner'           },
  { id:8,  section:'Vehicles', key:'vehicles_banner',    label:'Vehicles Page Banner',src:'', used:'Vehicles page header'             },
  { id:9,  section:'Auth',     key:'auth_car',           label:'Login Page Car',      src:'',    used:'Auth page side panel'             },
];

// ── CMS Image URL resolver ────────────────────────────────────────────
// The CMS is served from /cms-dev/ but all media files live at the
// staging root (/images/vehicles/, /images/ui/, etc.).
// A relative path like 'images/vehicles/x.jpg' rendered inside /cms-dev/
// resolves to /cms-dev/images/vehicles/x.jpg → 404.
// resolveImgUrl() prepends the staging origin so every <img> gets the
// correct absolute URL regardless of which sub-path the CMS is served from.
//
// CEYRIDE_API_BASE = 'https://devstaging.ceyride.com/api/'
// CMS_MEDIA_BASE  = 'https://devstaging.ceyride.com/'
const CMS_MEDIA_BASE = (function() {
  const base = window.CEYRIDE_API_BASE || '';
  // Strip trailing 'api/' or 'api' to get the site root
  return base.replace(/api\/?$/, '');
})();

function resolveImgUrl(path) {
  if (!path || typeof path !== 'string' || path.trim() === '') return '';
  const p = path.trim();
  // Already absolute — return as-is
  if (/^https?:\/\//.test(p) || p.startsWith('//') || p.startsWith('/')) return p;
  // Relative path — prefix with staging root
  return CMS_MEDIA_BASE + p;
}

// ─── SHARED HELPERS ──────────────────────────────────────────
const SC = {
  pending:   { bg:'#FEF3C7', color:'#92400E', label:'Pending'   },
  approved:  { bg:'#D1FAE5', color:'#065F46', label:'Approved'  },
  rejected:  { bg:'#FEE2E2', color:'#991B1B', label:'Rejected'  },
  confirmed: { bg:'#D1FAE5', color:'#065F46', label:'Confirmed' },
  cancelled: { bg:'#FEE2E2', color:'#991B1B', label:'Cancelled' },
  active:       { bg:'#D1FAE5', color:'#065F46', label:'Active'       },
  under_review: { bg:'#EFF6FF', color:'#1D4ED8', label:'Under Review'  },
  completed:    { bg:'#F0FDF4', color:'#166534', label:'Completed'      },
  blocked:   { bg:'#FEE2E2', color:'#991B1B', label:'Blocked'   },
};
function CmsBadge({ status }) {
  const s = SC[status] || { bg:'#F3F4F6', color:'#374151', label: status };
  return <span style={{ background:s.bg, color:s.color, fontWeight:700, fontSize:11, padding:'3px 10px', borderRadius:20, textTransform:'uppercase', letterSpacing:'0.04em', whiteSpace:'nowrap' }}>{s.label}</span>;
}
function Stat({ icon, label, value, sub, color='#7C3AED', onClick }) {
  return (
    <div onClick={onClick} style={{ background:'#fff', borderRadius:14, padding:'18px 20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)', cursor: onClick ? 'pointer' : 'default' }}>
      <div style={{ width:38, height:38, borderRadius:10, background:`${color}15`, border:`1px solid ${color}25`, display:'flex', alignItems:'center', justifyContent:'center', marginBottom:12, color:color, flexShrink:0 }}>{icon}</div>
      <div style={{ fontSize:'clamp(22px,4vw,28px)', fontWeight:800, color:'#141413', letterSpacing:'-0.03em', lineHeight:1 }}>{value}</div>
      <div style={{ fontSize:13, fontWeight:600, color:'#141413', marginTop:4 }}>{label}</div>
      {sub && <div style={{ fontSize:11, color:'#969696', marginTop:2 }}>{sub}</div>}
    </div>
  );
}
function Bar({ data, labels, color='#7C3AED', h=80 }) {
  if (!data || data.length === 0) return (
    <div style={{ height:h+20, display:'flex', alignItems:'center', justifyContent:'center', color:'#969696', fontSize:12 }}>No data yet</div>
  );
  const mx = Math.max(...data) || 1;
  return (
    <div style={{ display:'flex', gap:6, alignItems:'flex-end', height:h+20 }}>
      {data.map((v,i) => (
        <div key={i} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:4 }}>
          <div style={{ width:'100%', background:color, borderRadius:'4px 4px 0 0', height:Math.round((v/mx)*h), opacity:.85 }} />
          <div style={{ fontSize:10, color:'#969696', fontWeight:600 }}>{labels[i]}</div>
        </div>
      ))}
    </div>
  );
}
const INP = { padding:'10px 13px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.12)', fontSize:14, fontFamily:'inherit', outline:'none', background:'#fff', color:'#141413', width:'100%', boxSizing:'border-box' };
const BTN = { border:'none', borderRadius:10, padding:'8px 14px', fontWeight:700, fontSize:13, cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap' };

function Modal({ title, onClose, children, wide }) {
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const h = e => { if (e.key==='Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', h); };
  }, []);
  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(20,20,19,0.55)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:3000, padding:16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:20, width:'100%', maxWidth:wide?700:480, maxHeight:'92vh', display:'flex', flexDirection:'column', boxShadow:'0 20px 60px rgba(20,20,19,0.2)' }}>
        <div style={{ padding:'18px 22px 14px', borderBottom:'1px solid rgba(20,20,19,0.08)', display:'flex', justifyContent:'space-between', alignItems:'center', flexShrink:0 }}>
          <div style={{ fontWeight:700, fontSize:16, color:'#141413' }}>{title}</div>
          <button onClick={onClose} style={{ background:'none', border:'none', fontSize:22, cursor:'pointer', color:'#969696', lineHeight:1 }}>×</button>
        </div>
        <div style={{ padding:'18px 22px 22px', overflowY:'auto', flex:1 }}>{children}</div>
      </div>
    </div>
  );
}

// ─── ADMIN LOGIN ─────────────────────────────────────────────
function AdminLogin({ onLogin }) {
  const [email, setEmail]     = React.useState('');
  const [pw, setPw]           = React.useState('');
  const [err, setErr]         = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [showPw, setShowPw]   = React.useState(false);

  const go = async () => {
    setErr('');
    if (!email || !pw) { setErr('Both fields required.'); return; }
    setLoading(true);
    try {
      const res  = await fetch('api/admin.php', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ action: 'admin_login', email: email.trim().toLowerCase(), password: pw }),
      });
      const json = await res.json();
      if (!res.ok || json.error) {
        setLoading(false);
        setErr(json.error || 'Invalid credentials. Access denied.');
        return;
      }
      const s = {
        id:        json.admin.id,
        name:      json.admin.name,
        email:     json.admin.email,
        role:      json.admin.role,
        token:     json.admin.token,   // server-issued JWT — required for all admin API calls
        loginTime: Date.now(),
      };
      localStorage.setItem('cr_admin', JSON.stringify(s));
      onLogin(s);
    } catch {
      setLoading(false);
      setErr('Network error. Could not reach the server — check your connection.');
    }
  };

  return (
    <div style={{ minHeight:'100vh', background:'#0F0F0E', display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
      <div style={{ width:'100%', maxWidth:400 }}>
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', marginBottom:32, gap:14 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ display:'flex', alignItems:'center', gap:1 }}>
              <span style={{ fontWeight:800, fontSize:28, color:'#fff', letterSpacing:'-1px', fontFamily:"'Sofia Sans',sans-serif" }}>Cey</span>
              <div style={{ width:28, height:28, borderRadius:'50%', background:'#E84800', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 1px' }}>
                <span style={{ fontWeight:800, fontSize:15, color:'#fff', fontFamily:"'Sofia Sans',sans-serif" }}>R</span>
              </div>
              <span style={{ fontWeight:800, fontSize:28, color:'#fff', letterSpacing:'-1px', fontFamily:"'Sofia Sans',sans-serif" }}>ide</span>
            </div>
            <div style={{ display:'flex', alignItems:'center', gap:5, background:'#7C3AED', borderRadius:20, padding:'5px 12px' }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{verticalAlign:"middle", marginRight:4}}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
              <span style={{ fontSize:11, fontWeight:700, color:'#fff', letterSpacing:'0.07em' }}>ADMIN PORTAL</span>
            </div>
          </div>
        </div>
        <div style={{ background:'#1A1A19', borderRadius:24, padding:'clamp(24px,5vw,32px)' }}>
          <h2 style={{ fontWeight:800, fontSize:22, color:'#fff', marginBottom:6 }}>Admin Login</h2>
          <p style={{ color:'rgba(255,255,255,0.4)', fontSize:14, marginBottom:24 }}>Secure access for authorised personnel only.</p>
          {err && <div style={{ background:'#FEE2E2', borderRadius:10, padding:'10px 14px', marginBottom:16, fontSize:13, color:'#DC2626' }}>⚠️ {err}</div>}
          <div style={{ marginBottom:14 }}>
            <label style={{ fontSize:11, fontWeight:700, color:'rgba(255,255,255,0.45)', textTransform:'uppercase', letterSpacing:'0.06em', display:'block', marginBottom:7 }}>Admin Email</label>
            <input style={{ ...INP, background:'#0F0F0E', border:'1.5px solid rgba(255,255,255,0.1)', color:'#fff' }} type="email" placeholder="admin@ceyride.com" value={email} onChange={e=>setEmail(e.target.value)} onKeyDown={e=>e.key==='Enter'&&go()} />
          </div>
          <div style={{ marginBottom:22 }}>
            <label style={{ fontSize:11, fontWeight:700, color:'rgba(255,255,255,0.45)', textTransform:'uppercase', letterSpacing:'0.06em', display:'block', marginBottom:7 }}>Password</label>
            <div style={{ position:'relative' }}>
              <input style={{ ...INP, background:'#0F0F0E', border:'1.5px solid rgba(255,255,255,0.1)', color:'#fff', paddingRight:44 }} type={showPw?'text':'password'} placeholder="••••••••" value={pw} onChange={e=>setPw(e.target.value)} onKeyDown={e=>e.key==='Enter'&&go()} />
              <button onClick={()=>setShowPw(!showPw)} style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', background:'none', border:'none', cursor:'pointer', fontSize:14 }}>{showPw?'🙈':'👁️'}</button>
            </div>
          </div>
          <button onClick={go} disabled={loading} style={{ ...BTN, width:'100%', padding:'14px 0', fontSize:15, background:'#7C3AED', color:'#fff', opacity:loading?.7:1, boxShadow:'0 4px 20px rgba(124,58,237,0.35)' }}>
            {loading ? 'Verifying…' : <>{<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{verticalAlign:"middle", marginRight:6}}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>} Sign In to Admin Portal</>}
          </button>
          <div style={{ marginTop:18, padding:'12px 14px', background:'rgba(255,255,255,0.04)', borderRadius:10, border:'1px solid rgba(255,255,255,0.06)' }}>
            <div style={{ fontSize:11, color:'rgba(255,255,255,0.3)', fontWeight:500, letterSpacing:'0.03em' }}>
              Authorised personnel only. Contact the system administrator if you have lost access.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── SVG ICON SYSTEM — replaces all emoji ────────────────────
function SvgIcon({ children, size=18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      {children}
    </svg>
  );
}
const ICONS = {
  dashboard:  <SvgIcon><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></SvgIcon>,
  car:        <SvgIcon><path d="M5 17H3v-4l2.5-5h13L21 13v4h-2"/><circle cx="7.5" cy="17.5" r="1.5"/><circle cx="16.5" cy="17.5" r="1.5"/><path d="M5 13h14"/></SvgIcon>,
  users:      <SvgIcon><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></SvgIcon>,
  compass:    <SvgIcon><circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"/></SvgIcon>,
  package:    <SvgIcon><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><path d="M3.27 6.96L12 12.01l8.73-5.05M12 22.08V12"/></SvgIcon>,
  calendar:   <SvgIcon><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></SvgIcon>,
  route:      <SvgIcon><circle cx="6" cy="19" r="3"/><path d="M9 19h8.5a3.5 3.5 0 000-7h-11a3.5 3.5 0 010-7H15"/><circle cx="18" cy="5" r="3"/></SvgIcon>,
  wallet:     <SvgIcon><path d="M20 12V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h13a2 2 0 002-2v-5z"/><path d="M20 12h-5a2 2 0 100 4h5"/></SvgIcon>,
  image:      <SvgIcon><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></SvgIcon>,
  fileText:   <SvgIcon><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/></SvgIcon>,
  shield:     <SvgIcon><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></SvgIcon>,
  bell:       <SvgIcon><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></SvgIcon>,
  logout:     <SvgIcon><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/></SvgIcon>,
  externalLink:<SvgIcon><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><path d="M15 3h6v6"/><path d="M10 14L21 3"/></SvgIcon>,
  barChart:   <SvgIcon><path d="M18 20V10M12 20V4M6 20v-6"/></SvgIcon>,
};

// ─── SIDEBAR ─────────────────────────────────────────────────
const NAVS = [
  { key:'dashboard',  label:'Dashboard',     icon:ICONS.dashboard },
  { key:'vehicles',   label:'Vehicles',      icon:ICONS.car, badge:'veh' },
  { key:'drivers',    label:'Drivers',       icon:ICONS.users, badge:'drv' },
  { key:'guides',     label:'Tour Guides',   icon:ICONS.compass, badge:'gde' },
  { key:'packages',   label:'Packages',      icon:ICONS.package, badge:'pkg' },
  { key:'bookings',        label:'Bookings',        icon:ICONS.calendar, badge:'bk'  },
  { key:'driver-bookings', label:'Driver Bookings',  icon:ICONS.route, badge:'dbk' },
  { key:'finance',    label:'Finance',       icon:ICONS.wallet },
  { key:'users',      label:'Users',         icon:ICONS.users },
  { key:'images',     label:'UI Images',     icon:ICONS.image },
  { key:'content',    label:'Content',       icon:ICONS.fileText },
  { key:'auditlog',   label:'Audit Log',     icon:ICONS.shield },
  { key:'notifs',     label:'Notifications', icon:ICONS.bell, badge:'ntf' },
];

function Sidebar({ active, setActive, onLogout, open, setOpen, badges }) {
  return (
    <>
      {open && <div onClick={()=>setOpen(false)} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', zIndex:199 }} />}
      <aside style={{ position:'fixed', top:0, left:open?0:-256, width:240, height:'100vh', background:'#141413', zIndex:200, display:'flex', flexDirection:'column', transition:'left 0.25s ease', overflowY:'auto' }} className="admin-sidebar-always">
        <div style={{ padding:'22px 18px 14px', borderBottom:'1px solid rgba(255,255,255,0.06)', flexShrink:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:1, marginBottom:4 }}>
            <span style={{ fontWeight:800, fontSize:18, color:'#fff', letterSpacing:'-1px', fontFamily:"'Sofia Sans',sans-serif" }}>Cey</span>
            <div style={{ width:18, height:18, borderRadius:'50%', background:'#E84800', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 1px' }}>
              <span style={{ fontWeight:800, fontSize:10, color:'#fff', fontFamily:"'Sofia Sans',sans-serif" }}>R</span>
            </div>
            <span style={{ fontWeight:800, fontSize:18, color:'#fff', letterSpacing:'-1px', fontFamily:"'Sofia Sans',sans-serif" }}>ide</span>
          </div>
          <div style={{ fontSize:10, fontWeight:700, color:'#7C3AED', letterSpacing:'0.08em', textTransform:'uppercase' }}>Admin Portal</div>
        </div>
        <nav style={{ flex:1, padding:'10px 10px' }}>
          {NAVS.map(item => {
            const cnt = badges[item.badge] || 0;
            const on  = active === item.key;
            return (
              <div key={item.key} onClick={()=>{ setActive(item.key); setOpen(false); }} style={{ display:'flex', alignItems:'center', gap:9, padding:'10px 12px', borderRadius:10, cursor:'pointer', marginBottom:2, background:on?'#7C3AED':'transparent', transition:'all 0.15s' }}
                onMouseEnter={e=>{ if(!on) e.currentTarget.style.background='rgba(255,255,255,0.07)'; }}
                onMouseLeave={e=>{ if(!on) e.currentTarget.style.background='transparent'; }}>
                <span style={{ flexShrink:0, display:'flex', alignItems:'center', color: on ? '#fff' : 'rgba(255,255,255,0.5)' }}>{item.icon}</span>
                <span style={{ fontSize:13, fontWeight:on?700:500, color:on?'#fff':'rgba(255,255,255,0.65)', flex:1 }}>{item.label}</span>
                {cnt>0 && <span style={{ background:on?'rgba(255,255,255,0.25)':'#E84800', color:'#fff', borderRadius:999, fontSize:10, fontWeight:700, padding:'1px 6px', minWidth:18, textAlign:'center' }}>{cnt}</span>}
              </div>
            );
          })}
        </nav>
        <div style={{ padding:'10px 10px 20px', borderTop:'1px solid rgba(255,255,255,0.06)', flexShrink:0 }}>
          <div onClick={()=>window.open('https://devstaging.ceyride.com','_blank')} style={{ display:'flex', alignItems:'center', gap:9, padding:'10px 12px', borderRadius:10, cursor:'pointer', color:'rgba(255,255,255,0.45)', fontSize:13, fontWeight:500, transition:'all 0.15s', marginBottom:4 }}
            onMouseEnter={e=>{ e.currentTarget.style.background='rgba(255,255,255,0.07)'; e.currentTarget.style.color='rgba(255,255,255,0.8)'; }}
            onMouseLeave={e=>{ e.currentTarget.style.background='transparent'; e.currentTarget.style.color='rgba(255,255,255,0.45)'; }}>
            <span style={{ display:'flex', alignItems:'center', color:'rgba(255,255,255,0.45)' }}>{ICONS.externalLink}</span>
            <span>View Site</span>
          </div>
          <div onClick={onLogout} style={{ display:'flex', alignItems:'center', gap:9, padding:'10px 12px', borderRadius:10, cursor:'pointer', color:'rgba(255,255,255,0.45)', fontSize:13, fontWeight:500, transition:'all 0.15s' }}
            onMouseEnter={e=>{ e.currentTarget.style.background='rgba(220,38,38,0.1)'; e.currentTarget.style.color='#EF4444'; }}
            onMouseLeave={e=>{ e.currentTarget.style.background='transparent'; e.currentTarget.style.color='rgba(255,255,255,0.45)'; }}>
            <span style={{ display:'flex', alignItems:'center', color:'rgba(255,255,255,0.45)' }}>{ICONS.logout}</span>
            <span>Sign Out</span>
          </div>
        </div>
      </aside>
    </>
  );
}

function TopBar({ admin, mod, onMenu, notifCount, setMod, onSync, syncing, onSyncCheck }) {
  const label = NAVS.find(n=>n.key===mod);
  return (
    <div style={{ position:'fixed', top:0, left:0, right:0, height:58, background:'#fff', borderBottom:'1px solid rgba(20,20,19,0.08)', display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 16px 0 16px', zIndex:100, boxShadow:'0 1px 4px rgba(20,20,19,0.06)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:12 }}>
        <button onClick={onMenu} className="admin-menu-btn" style={{ background:'none', border:'none', cursor:'pointer', padding:6, display:'none', flexDirection:'column', gap:4 }}>
          {[1,2,3].map(i => <div key={i} style={{ width:20, height:2, background:'#141413', borderRadius:2 }} />)}
        </button>
        <div style={{ fontWeight:700, fontSize:15, color:'#141413' }}>{label?.icon} {label?.label || 'Admin'}</div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:10 }}>
        {/* ── Save & Sync button (restored) ── */}
        <button
          onClick={onSync}
          disabled={syncing}
          title="Save & Synchronize — reload all data from database"
          style={{ border:'1.5px solid #7C3AED', background:syncing?'#7C3AED10':'#fff', borderRadius:10, padding:'6px 12px', fontWeight:700, fontSize:12, cursor:syncing?'default':'pointer', color:'#7C3AED', display:'flex', alignItems:'center', gap:5, whiteSpace:'nowrap', opacity:syncing?.7:1, transition:'all 0.15s', fontFamily:'inherit' }}
        >
          <span style={{ display:'inline-block', animation: syncing ? 'crSpin 1s linear infinite' : 'none' }}>🔄</span>
          {syncing ? 'Syncing…' : 'Save & Sync'}
        </button>
        {/* ── Sync Check button ── */}
        <button
          onClick={onSyncCheck}
          title="Check synchronization status of all system components"
          style={{ border:'1.5px solid rgba(20,20,19,0.15)', background:'#fff', borderRadius:10, padding:'6px 10px', fontWeight:700, fontSize:12, cursor:'pointer', color:'#696969', display:'flex', alignItems:'center', gap:4, whiteSpace:'nowrap', transition:'all 0.15s', fontFamily:'inherit' }}
        >
          🩺 Sync Check
        </button>
        <div onClick={()=>setMod('notifs')} style={{ position:'relative', cursor:'pointer', fontSize:20 }}>
          🔔
          {notifCount>0 && <span style={{ position:'absolute', top:-3, right:-5, background:'#E84800', color:'#fff', borderRadius:'50%', fontSize:9, fontWeight:700, width:16, height:16, display:'flex', alignItems:'center', justifyContent:'center' }}>{notifCount}</span>}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <div style={{ width:32, height:32, borderRadius:'50%', background:'#7C3AED', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:700, fontSize:13 }}>{(admin?.name||'A')[0]}</div>
          <div className="admin-name-hide">
            <div style={{ fontSize:13, fontWeight:700, color:'#141413' }}>{admin?.name}</div>
            <div style={{ fontSize:11, color:'#969696' }}>{admin?.role}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── DASHBOARD ───────────────────────────────────────────────
function Dashboard({ data, setMod }) {
  const pv = (data.registrations||[]).filter(r=>r.status==='pending').length;
  const pd = data.drivers.filter(d=>d.status==='pending').length;
  const pg = data.guides.filter(g=>g.status==='pending').length;
  const pp = data.packages.filter(p=>p.status==='pending').length;
  const pb = data.bookings.filter(b=>b.status==='pending').length;
  const nr = data.notifications.filter(n=>!n.read).length;
  const totalRev = data.bookings.filter(b=>b.status==='confirmed').reduce((s,b)=>s+(Number(b.total)||0),0);

  return (
    <div>
      <div style={{ marginBottom:22 }}>
        <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Platform Overview</h2>
        <p style={{ color:'#969696', fontSize:13 }}>{new Date().toLocaleDateString('en-GB',{weekday:'long',day:'numeric',month:'long',year:'numeric'})}</p>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(150px,1fr))', gap:12, marginBottom:24 }}>
        <Stat icon={ICONS.car}     label="Vehicles"      value={data.vehicles.length} sub={`${pv} pending`}        color="#E84800" onClick={()=>setMod('vehicles')} />
        <Stat icon={ICONS.users}   label="Drivers"      value={data.drivers.length}  sub={`${pd} pending`}        color="#0066CC" onClick={()=>setMod('drivers')}  />
        <Stat icon={ICONS.compass} label="Guides"        value={data.guides.length}   sub={`${pg} pending`}        color="#7C3AED" onClick={()=>setMod('guides')}   />
        <Stat icon={ICONS.calendar}label="Bookings"      value={data.bookings.length} sub={`${pb} pending`}        color="#059669" onClick={()=>setMod('bookings')} />
        <Stat icon={ICONS.wallet}  label="Revenue"       value={`Rs. ${Math.round(totalRev).toLocaleString()}`} sub="Confirmed bookings" color="#F59E0B" onClick={()=>setMod('finance')} />
        <Stat icon={ICONS.bell}    label="Alerts"        value={nr}                   sub="Unread"                 color="#DC2626" onClick={()=>setMod('notifs')}   />
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(280px,1fr))', gap:18 }}>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)' }}>
          <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:16 }}>Weekly Revenue (LKR)</div>
          <Bar data={data.revenue.daily} labels={data.revenue.labels} color="#7C3AED" h={80} />
          <div style={{ marginTop:12, display:'flex', justifyContent:'space-between', fontSize:12 }}>
            <span style={{ color:'#969696' }}>This week: <strong style={{ color:'#141413' }}>Rs. {data.revenue.daily.reduce((a,b)=>a+b,0).toLocaleString()}</strong></span>
            <span onClick={()=>setMod('finance')} style={{ color:'#E84800', cursor:'pointer', fontWeight:600 }}>View →</span>
          </div>
        </div>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)' }}>
          <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:14 }}>Recent Activity</div>
          {data.notifications.slice(0,5).map((n,i) => (
            <div key={n.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 0', borderBottom:i<4?'1px solid rgba(20,20,19,0.05)':'none' }}>
              <div style={{ width:32, height:32, borderRadius:8, background:n.read?'#F5F5F3':'#7C3AED18', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, flexShrink:0 }}>{n.icon}</div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12, fontWeight:n.read?500:700, color:'#141413', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{n.title}</div>
                <div style={{ fontSize:11, color:'#969696' }}>{n.time}</div>
              </div>
              {!n.read && <div style={{ width:7, height:7, borderRadius:'50%', background:'#7C3AED', flexShrink:0 }} />}
            </div>
          ))}
        </div>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)' }}>
          <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:14 }}>Pending Reviews</div>
          {[{label:'Vehicles', count:pv, color:'#E84800'},{label:'Drivers', count:pd, color:'#0066CC'},{label:'Guides', count:pg, color:'#7C3AED'},{label:'Packages', count:pp, color:'#D97706'}].map((r,i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', gap:12, marginBottom:12 }}>
              <div style={{ width:36, height:36, borderRadius:8, background:`${r.color}18`, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:16, color:r.color, flexShrink:0 }}>{r.count}</div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:'#141413', marginBottom:3 }}>{r.label} Pending</div>
                <div style={{ height:5, borderRadius:3, background:'#F0F0EE' }}>
                  <div style={{ width:`${Math.min(100,(r.count/10)*100)}%`, height:'100%', borderRadius:3, background:r.color }} />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── CMS SHARED HELPERS ──────────────────────────────────────
const FL = { width:'100%', padding:'10px 13px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.12)', fontSize:14, fontFamily:'inherit', outline:'none', background:'#fff', color:'#141413', boxSizing:'border-box' };
const LB = { fontSize:11, fontWeight:700, color:'#696969', textTransform:'uppercase', letterSpacing:'0.06em', display:'block', marginBottom:6 };

function FieldRow({ label, children }) {
  return (
    <div style={{ marginBottom:14 }}>
      <label style={LB}>{label}</label>
      {children}
    </div>
  );
}
function ImageUploadBtn({ onUpload, current, label='Upload Image' }) {
  const [prev, setPrev] = React.useState(current||null);
  const [uploading, setUploading] = React.useState(false);
  const pick = () => {
    const el = document.createElement('input');
    el.type='file'; el.accept='image/jpeg,image/png,image/webp';
    el.onchange = async e => {
      const file = e.target.files[0]; if(!file) return;
      if(file.size > 5*1024*1024) { alert('Max 5MB'); return; }
      setUploading(true);
      const url = URL.createObjectURL(file);
      setPrev(url);
      // Try PHP upload
      try {
        const fd = new FormData(); fd.append('image',file); fd.append('image_key','cms_'+Date.now());
        const res = await fetch('api/upload_image.php',{method:'POST',body:fd});
        const json = await res.json();
        if(json.success) { onUpload(json.cache_url||json.path); }
        else { onUpload(`images/vehicles/${file.name}?t=${Date.now()}`); }
      } catch { onUpload(`images/vehicles/${file.name}?t=${Date.now()}`); }
      setUploading(false);
    };
    el.click();
  };
  return (
    <div style={{ border:'2px dashed rgba(20,20,19,0.15)', borderRadius:12, padding:14, textAlign:'center', cursor:'pointer' }} onClick={pick}>
      {prev ? <img src={resolveImgUrl(prev)} alt="preview" style={{ maxHeight:120, maxWidth:'100%', borderRadius:8, marginBottom:8, display:'block', margin:'0 auto 8px' }} onError={e=>e.target.style.display='none'} /> : <div style={{ fontSize:32, marginBottom:4 }}>🖼️</div>}
      <div style={{ fontSize:12, color:'#7C3AED', fontWeight:700 }}>{uploading?'Uploading…':label}</div>
      <div style={{ fontSize:11, color:'#969696', marginTop:2 }}>JPG / PNG / WebP · Max 5MB</div>
    </div>
  );
}
function CmsSearchBar({ value, onChange, placeholder='Search…' }) {
  return <input style={{ ...FL, maxWidth:280 }} placeholder={placeholder} value={value} onChange={e=>onChange(e.target.value)} />;
}
function StatusToggle({ active, onChange }) {
  return (
    <div onClick={()=>onChange(!active)} style={{ display:'inline-flex', alignItems:'center', gap:8, cursor:'pointer', padding:'4px 10px', borderRadius:20, background:active?'#D1FAE5':'#FEE2E2', border:`1px solid ${active?'#6EE7B7':'#FECACA'}` }}>
      <div style={{ width:10, height:10, borderRadius:'50%', background:active?'#059669':'#DC2626' }} />
      <span style={{ fontSize:12, fontWeight:700, color:active?'#065F46':'#991B1B' }}>{active?'Active':'Inactive'}</span>
    </div>
  );
}

function logAction(logs, setLogs, action, module, detail) {
  const entry = { id:Date.now(), time:new Date().toLocaleTimeString('en-GB'), action, module, detail, by:'Admin' };
  setLogs(prev => [entry, ...prev.slice(0,49)]);
}

// ── Global admin auth header helper (used by all CMS components) ──
function getAdminAuthHdr() {
  try {
    const s = JSON.parse(localStorage.getItem('cr_admin') || '{}');
    return s.token ? { 'Authorization': `Bearer ${s.token}` } : {};
  } catch { return {}; }
}

// ─── CMS: VEHICLES MANAGEMENT ────────────────────────────────
function VehiclesCMS({ data, setData, auditLog }) {
  const [search,   setSearch]   = React.useState('');
  const [filter,   setFilter]   = React.useState('active');
  const [modal,    setModal]    = React.useState(null); // null | 'add' | 'edit'
  const [delConf,  setDelConf]  = React.useState(null);
  const [form,     setForm]     = React.useState({});
  const setF = (k,v) => setForm(f=>({...f,[k]:v}));

  const emptyForm = {
    type:'Car', brand:'', model:'', year:new Date().getFullYear(), seats:4,
    price_per_day:'', fuel_policy:'Full-to-Full', location:'Colombo',
    description:'', image_url:'', is_active:1, is_featured_home:0, featured_order:0,
    // Legacy flags — kept in sync
    with_driver:0, self_drive:1,
    // ── Clean driver system ───────────────────────────────
    has_self_drive:1,   self_drive_price:'',
    has_owner_driver:0, owner_driver_price:'',
    owner_driver_name:'', owner_driver_experience:0,
    owner_driver_photo:'', owner_driver_contact:'', owner_driver_languages:'',
    // Insurance
    insurance_type:'none', insurance_provider:'', insurance_policy_number:'',
    insurance_expiry:'', insurance_doc_path:'',
  };

  const list = data.vehicles.filter(v => {
    const q = search.toLowerCase();
    const sOk = filter==='all'
      || (filter==='active'     && Number(v.is_active) === 1)
      || (filter==='inactive'   && Number(v.is_active) === 0)
      || (filter==='pending'    && v.status==='pending')
      || (filter==='featured' && Number(v.is_featured_home)===1)
      || (filter==='insured'  && v.insurance_type && v.insurance_type !== 'none')
      || (filter==='unverified' && v.insurance_type && v.insurance_type !== 'none' && !v.insurance_verified);
    const tOk = !q || `${v.brand} ${v.model} ${v.type}`.toLowerCase().includes(q);
    return sOk && tOk;
  });

  const openAdd  = ()  => { setForm({...emptyForm}); setModal('add'); };
  const openEdit = (v) => { setForm({...v}); setModal('edit'); };

  const save = async () => {
    if(!form.brand||!form.model||!form.price_per_day) { alert('Brand, Model and Price are required.'); return; }
    try {
      const method = modal==='add' ? 'POST' : 'PUT';
      const res = await fetch(`api/cms_vehicles.php${modal==='edit'?`?id=${form.id}`:''}`, { method, headers:{'Content-Type':'application/json',...getAdminAuthHdr()}, body:JSON.stringify(form) });
      const json = await res.json();
      if(json.id||json.success) {
        if(modal==='add') {
          setData(d=>({...d, vehicles:[{...form, id:json.id||Date.now(), status:'approved', rating:0, review_count:0}, ...d.vehicles]}));
          logAction(auditLog.logs, auditLog.setLogs, 'Created', 'Vehicle', `${form.brand} ${form.model}`);
        } else {
          setData(d=>({...d, vehicles:d.vehicles.map(v=>v.id===form.id?{...v,...form}:v)}));
          logAction(auditLog.logs, auditLog.setLogs, 'Updated', 'Vehicle', `${form.brand} ${form.model}`);
        }
        setModal(null);
      }
    } catch {
      // Offline/dev: update state directly
      if(modal==='add') { setData(d=>({...d, vehicles:[{...form, id:Date.now(), status:'approved', rating:0, review_count:0}, ...d.vehicles]})); }
      else { setData(d=>({...d, vehicles:d.vehicles.map(v=>v.id===form.id?{...v,...form}:v)})); }
      logAction(auditLog.logs, auditLog.setLogs, modal==='add'?'Created':'Updated', 'Vehicle', `${form.brand} ${form.model}`);
      setModal(null);
    }
  };

  const del = async (id) => {
    try {
      const res  = await fetch(`api/cms_vehicles.php?id=${id}`, { method: 'DELETE', headers: getAdminAuthHdr() });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.success) {
        alert('Delete failed: ' + (json.error || 'Server error — vehicle was NOT removed. Please try again.'));
        setDelConf(null);
        return;
      }
    } catch {
      alert('Network error — vehicle was NOT deleted. Please check your connection and try again.');
      setDelConf(null);
      return;
    }
    const v = data.vehicles.find(vv => vv.id === id);
    setData(d => ({ ...d, vehicles: d.vehicles.filter(vv => vv.id !== id) }));
    logAction(auditLog.logs, auditLog.setLogs, 'Deleted', 'Vehicle', v ? `${v.brand} ${v.model}` : `ID ${id}`);
    setDelConf(null);
  };

  const toggleActive = async (id) => {
    const v = data.vehicles.find(vv => vv.id === id);
    if (!v) return;
    const newActive = v.is_active ? 0 : 1;
    // Optimistic update
    setData(d => ({ ...d, vehicles: d.vehicles.map(vv => vv.id === id ? { ...vv, is_active: newActive } : vv) }));
    try {
      const res = await fetch(`api/cms_vehicles.php?id=${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...getAdminAuthHdr() },
        body: JSON.stringify({ ...v, is_active: newActive })
      });
      if (!res.ok) throw new Error('Server error');
    } catch {
      // Revert optimistic update on failure
      setData(d => ({ ...d, vehicles: d.vehicles.map(vv => vv.id === id ? { ...vv, is_active: v.is_active } : vv) }));
      alert('Failed to update vehicle status. Please try again.');
      return;
    }
    logAction(auditLog.logs, auditLog.setLogs, newActive ? 'Activated' : 'Deactivated', 'Vehicle', `${v.brand} ${v.model}`);
  };

  // ── Part 15 Restore — Featured toggle ─────────────────────────
  const [featSaving, setFeatSaving] = React.useState(null); // vehicle id being toggled
  const toggleFeatured = async (id) => {
    const v = data.vehicles.find(vv=>vv.id===id);
    if (!v || featSaving === id) return;
    const newFeatured = Number(v.is_featured_home)===1 ? 0 : 1;
    // Auto-assign next order slot when featuring; 999 = unfeatured sentinel
    const nextOrder = newFeatured
      ? data.vehicles.filter(vv=>Number(vv.is_featured_home)===1).length + 1
      : 999;
    // Optimistic update — immediately reflects intent in UI
    setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, is_featured_home:newFeatured, featured_order:nextOrder} : vv)}));
    setFeatSaving(id);
    try {
      const res = await fetch(`api/cms_vehicles.php?id=${id}&action=feature`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...getAdminAuthHdr() },
        body: JSON.stringify({ is_featured_home: newFeatured }),
      });
      const json = await res.json();
      if (!res.ok || json.error) {
        // API failed — revert optimistic update so local state matches DB
        setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, is_featured_home:v.is_featured_home, featured_order:v.featured_order||0} : vv)}));
        console.error('[CeyRide CMS] toggleFeatured failed:', json.error || res.status);
      } else if (json.vehicle) {
        // Force integer cast — MySQLi can return "0" string which is TRUTHY in JS
        const synced = {
          ...json.vehicle,
          is_featured_home: Number(json.vehicle.is_featured_home),
          featured_order:   Number(json.vehicle.featured_order),
        };
        setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, ...synced} : vv)}));
      }
    } catch(e) {
      // Network error — revert optimistic update
      setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, is_featured_home:v.is_featured_home, featured_order:v.featured_order||0} : vv)}));
      console.error('[CeyRide CMS] toggleFeatured network error:', e.message);
    }
    setFeatSaving(null);
    logAction(auditLog.logs, auditLog.setLogs, newFeatured?'Featured':'Unfeatured', 'Vehicle', `${v.brand} ${v.model}`);
  };

  const TYPES = ['Car','Van','SUV','Luxury','Mini Bus','Three-Wheeler','Jeep','Bus','Wedding Hire','Lorry / Truck'];
  const FUELS = ['Full-to-Full','Owner Covers','Customer Covers'];

  // ── Insurance verification toggle ──────────────────────────
  const [insSaving, setInsSaving] = React.useState(null); // vehicle id being verified
  const verifyInsurance = async (id, currentlyVerified) => {
    if (insSaving === id) return;
    const newVerified = currentlyVerified ? 0 : 1;
    // Optimistic update
    setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, insurance_verified:newVerified} : vv)}));
    setInsSaving(id);
    try {
      const res = await fetch(`api/cms_vehicles.php?id=${id}&action=verify_insurance`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...getAdminAuthHdr() },
        body: JSON.stringify({ verified: newVerified }),
      });
      const json = await res.json();
      if (json.vehicle) {
        setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, ...json.vehicle} : vv)}));
      }
    } catch {
      // Revert on failure
      setData(d=>({...d, vehicles:d.vehicles.map(vv=>vv.id===id ? {...vv, insurance_verified:currentlyVerified} : vv)}));
    }
    setInsSaving(null);
    logAction(auditLog.logs, auditLog.setLogs, newVerified?'Verified Insurance':'Un-verified Insurance', 'Vehicle', `ID ${id}`);
  };

  // Insurance type labels for display
  const INS_LABELS = {
    'none':             'None',
    'comprehensive':    'Comprehensive',
    'third_party':      'Third-Party',
    'hire_reward':      'Hire & Reward',
    'self_drive_rental':'Self-Drive Rental',
    'driver_included':  'Driver-Included',
  };

  // ── Pending Registration: Approve ──────────────────────────
  const [approvingReg, setApprovingReg] = React.useState(null);
  const [regMsg, setRegMsg] = React.useState('');

  const approveReg = async (reg) => {
    if (approvingReg) return;
    setApprovingReg(reg.id);
    setRegMsg('');
    try {
      const res  = await fetch(`api/owner_registrations.php?action=approve&id=${reg.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...getAdminAuthHdr() },
      });
      const json = await res.json();
      if (json.success) {
        // Mark approved in local state
        setData(d => ({
          ...d,
          registrations: (d.registrations||[]).map(r => r.id===reg.id ? {...r, status:'approved'} : r),
        }));
        // Reload vehicles table to pick up the newly inserted row
        try {
          const vRes  = await fetch('api/cms_vehicles.php', { headers: getAdminAuthHdr() });
          const vJson = await vRes.json();
          if (vJson.vehicles) setData(d => ({...d, vehicles: vJson.vehicles}));
        } catch {}
        setRegMsg(`✅ Approved! ${reg.brand} ${reg.model} is now live in Vehicle Management.`);
        logAction(auditLog.logs, auditLog.setLogs, 'Approved', 'Registration', `${reg.brand} ${reg.model} (${reg.owner_name})`);
      } else {
        setRegMsg(`❌ Approval failed: ${json.error || 'Unknown error'}`);
      }
    } catch {
      setRegMsg('❌ Network error — please try again.');
    }
    setApprovingReg(null);
  };

  const rejectReg = async (reg) => {
    if (!confirm(`Reject vehicle registration for ${reg.owner_name} (${reg.brand} ${reg.model} · ${reg.reg_number})?`)) return;
    try {
      await fetch(`api/owner_registrations.php?action=reject&id=${reg.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...getAdminAuthHdr() },
      });
      setData(d => ({
        ...d,
        registrations: (d.registrations||[]).map(r => r.id===reg.id ? {...r, status:'rejected'} : r),
      }));
      setRegMsg(`✅ Registration from ${reg.owner_name} has been rejected.`);
      logAction(auditLog.logs, auditLog.setLogs, 'Rejected', 'Registration', `${reg.brand} ${reg.model} (${reg.owner_name})`);
    } catch {
      setRegMsg('❌ Network error — please try again.');
    }
  };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Vehicle Management</h2>
          <p style={{ color:'#969696', fontSize:13 }}>
            {data.vehicles.length} vehicles · {data.vehicles.filter(v=>v.is_active).length} active ·{' '}
            <span style={{ color:'#D97706', fontWeight:700 }}>⭐ {data.vehicles.filter(v=>Number(v.is_featured_home)===1).length} featured</span> ·{' '}
            <span style={{ color:'#059669', fontWeight:700 }}>🛡️ {data.vehicles.filter(v=>v.insurance_type && v.insurance_type!=='none').length} insured</span>
            {data.vehicles.filter(v=>v.insurance_type&&v.insurance_type!=='none'&&!v.insurance_verified).length > 0 && (
              <> · <span style={{ color:'#D97706', fontWeight:700 }}>⚠️ {data.vehicles.filter(v=>v.insurance_type&&v.insurance_type!=='none'&&!v.insurance_verified).length} unverified</span></>
            )}
          </p>
        </div>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          <CmsSearchBar value={search} onChange={setSearch} placeholder="Search brand, model…" />
          <button onClick={openAdd} style={{ ...BTN, background:'#E84800', color:'#fff', padding:'10px 18px' }}>+ Add Vehicle</button>
        </div>
      </div>

      <div style={{ display:'flex', gap:7, marginBottom:18, flexWrap:'wrap' }}>
        {[
          { key:'all',        label:'All' },
          { key:'active',     label:'Active' },
          { key:'inactive',   label:'Inactive' },
          { key:'pending',    label:'Pending' },
          { key:'featured',   label:'⭐ Featured' },
          { key:'insured',    label:'🛡️ Insured Only' },
          { key:'unverified', label:'⚠️ Needs Verify' },
        ].map(f=>(
          <button key={f.key} onClick={()=>setFilter(f.key)} style={{
            ...BTN,
            background: filter===f.key ? (f.key==='insured'?'#059669':f.key==='unverified'?'#D97706':'#141413') : '#fff',
            color: filter===f.key ? '#fff' : '#696969',
            border: `1.5px solid ${filter===f.key ? (f.key==='insured'?'#059669':f.key==='unverified'?'#D97706':'#141413') : 'rgba(20,20,19,0.12)'}`,
          }}>{f.label}</button>
        ))}
      </div>

      {/* ── Pending Vehicle Registrations from User Portal ─────── */}
      {(() => {
        const pendingRegs = (data.registrations||[]).filter(r => r.status === 'pending');
        const rejectedRegs = (data.registrations||[]).filter(r => r.status === 'rejected');
        const allRegs = (data.registrations||[]);
        if (allRegs.length === 0) return null;
        return (
          <div style={{ background:'#FFF7ED', border:'2px solid #F59E0B', borderRadius:14, padding:'16px 20px', marginBottom:20 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: pendingRegs.length>0 ? 14 : 0, flexWrap:'wrap', gap:8 }}>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ fontSize:20 }}>📋</span>
                <span style={{ fontWeight:800, fontSize:14, color:'#92400E' }}>Vehicle Registrations from User Portal</span>
                {pendingRegs.length > 0 && (
                  <span style={{ background:'#DC2626', color:'#fff', borderRadius:999, fontSize:11, fontWeight:700, padding:'2px 8px' }}>
                    {pendingRegs.length} Pending Approval
                  </span>
                )}
                {pendingRegs.length === 0 && (
                  <span style={{ background:'#059669', color:'#fff', borderRadius:999, fontSize:11, fontWeight:700, padding:'2px 8px' }}>
                    All Reviewed
                  </span>
                )}
              </div>
              <span style={{ fontSize:12, color:'#92400E' }}>
                {allRegs.length} total · {pendingRegs.length} pending · {(data.registrations||[]).filter(r=>r.status==='approved').length} approved · {rejectedRegs.length} rejected
              </span>
            </div>

            {regMsg && (
              <div style={{ background: regMsg.startsWith('✅') ? '#D1FAE5' : '#FEE2E2', border:`1px solid ${regMsg.startsWith('✅')?'#6EE7B7':'#FECACA'}`, borderRadius:8, padding:'9px 13px', marginBottom:12, fontSize:13, color: regMsg.startsWith('✅') ? '#065F46':'#DC2626' }}>
                {regMsg}
              </div>
            )}

            {pendingRegs.length > 0 && (
              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                {pendingRegs.map(reg => (
                  <div key={reg.id} style={{ background:'#fff', borderRadius:12, padding:'16px', border:'1px solid rgba(245,158,11,0.4)', display:'flex', flexDirection:'column', gap:12 }}>
                    {/* ── Top row: image + core info + actions ── */}
                    <div style={{ display:'flex', gap:14, alignItems:'flex-start', flexWrap:'wrap' }}>
                      {/* Vehicle image */}
                      <div style={{ width:80, height:62, borderRadius:8, background:'#F5F5F3', flexShrink:0, overflow:'hidden' }}>
                        {reg.image_1
                          ? <img src={resolveImgUrl(reg.image_1)} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>{e.target.style.display='none';}} />
                          : <div style={{ width:'100%', height:'100%', display:'flex', alignItems:'center', justifyContent:'center', fontSize:26 }}>🚗</div>
                        }
                      </div>
                      {/* Core vehicle info */}
                      <div style={{ flex:1, minWidth:200 }}>
                        <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:3 }}>
                          {reg.vehicle_type} · {reg.brand} {reg.model} {reg.year ? `(${reg.year})` : ''}
                        </div>
                        <div style={{ fontSize:12, color:'#696969', marginBottom:3 }}>
                          Reg: <strong style={{ fontFamily:'monospace' }}>{reg.reg_number}</strong>
                          {reg.seats ? ` · ${reg.seats} seats` : ''}
                          {reg.fuel_policy ? ` · ${reg.fuel_policy}` : ''}
                        </div>
                        <div style={{ fontSize:12, color:'#696969', marginBottom:3 }}>
                          Owner: <strong>{reg.owner_name}</strong> · {reg.phone} · {reg.email}
                        </div>
                        <div style={{ fontSize:11, color:'#969696' }}>
                          Submitted: {reg.created_at ? new Date(reg.created_at).toLocaleString('en-GB',{day:'numeric',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}) : '—'}
                        </div>
                      </div>
                      {/* Actions */}
                      <div style={{ display:'flex', gap:7, flexShrink:0, flexWrap:'wrap' }}>
                        <button
                          onClick={() => approveReg(reg)}
                          disabled={approvingReg === reg.id}
                          style={{ ...BTN, background:'#059669', color:'#fff', padding:'8px 16px', opacity: approvingReg===reg.id ? 0.6 : 1 }}
                        >
                          {approvingReg===reg.id ? '⏳ Approving…' : '✅ Approve'}
                        </button>
                        <button
                          onClick={() => rejectReg(reg)}
                          disabled={!!approvingReg}
                          style={{ ...BTN, background:'#FEE2E2', color:'#DC2626', padding:'8px 14px' }}
                        >
                          ✗ Reject
                        </button>
                      </div>
                    </div>

                    {/* ── Detail grid: Pricing / Availability / Insurance / Bond / Driver ── */}
                    <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(200px,1fr))', gap:8, borderTop:'1px solid #F0EEE8', paddingTop:10 }}>

                      {/* Availability & Pricing */}
                      <div style={{ background:'#F8FAF8', border:'1px solid #D1FAE5', borderRadius:8, padding:'8px 10px' }}>
                        <div style={{ fontSize:10, fontWeight:700, color:'#059669', textTransform:'uppercase', letterSpacing:0.5, marginBottom:5 }}>Availability & Pricing</div>
                        {(reg.has_self_drive||reg.self_drive) ? (
                          <div style={{ fontSize:12, color:'#141413', marginBottom:2 }}>
                            🔑 Self Drive: <strong>Rs. {Number(reg.self_drive_price||0).toLocaleString()}/day</strong>
                          </div>
                        ) : null}
                        {(reg.has_owner_driver||reg.with_driver) ? (
                          <div style={{ fontSize:12, color:'#141413', marginBottom:2 }}>
                            🧑‍✈️ With Driver: <strong>Rs. {Number(reg.owner_driver_price||0).toLocaleString()}/day</strong>
                          </div>
                        ) : null}
                        {!(reg.has_self_drive||reg.self_drive) && !(reg.has_owner_driver||reg.with_driver) && (
                          <div style={{ fontSize:12, color:'#696969' }}>Rs. {Number(reg.price_per_day||0).toLocaleString()}/day</div>
                        )}
                      </div>

                      {/* Insurance */}
                      <div style={{ background: reg.insurance_type && reg.insurance_type!=='none' ? '#EFF6FF' : '#FFF8F0', border:`1px solid ${reg.insurance_type && reg.insurance_type!=='none' ? '#BFDBFE' : '#FDE68A'}`, borderRadius:8, padding:'8px 10px' }}>
                        <div style={{ fontSize:10, fontWeight:700, color: reg.insurance_type && reg.insurance_type!=='none' ? '#1D4ED8' : '#D97706', textTransform:'uppercase', letterSpacing:0.5, marginBottom:5 }}>
                          🛡️ Insurance
                        </div>
                        {reg.insurance_type && reg.insurance_type !== 'none' ? (
                          <>
                            <div style={{ fontSize:12, color:'#141413', marginBottom:2 }}>
                              <strong>{{none:'—',comprehensive:'Comprehensive',third_party:'Third Party',hire_reward:'Hire & Reward',self_drive_rental:'Self-Drive Rental',driver_included:'Driver Included'}[reg.insurance_type] || reg.insurance_type}</strong>
                            </div>
                            {reg.insurance_provider && <div style={{ fontSize:11, color:'#696969', marginBottom:2 }}>Provider: {reg.insurance_provider}</div>}
                            {reg.insurance_expiry && <div style={{ fontSize:11, color: new Date(reg.insurance_expiry)<new Date() ? '#DC2626':'#059669' }}>
                              Expires: {new Date(reg.insurance_expiry).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}
                              {new Date(reg.insurance_expiry)<new Date() ? ' ⚠️ EXPIRED' : ''}
                            </div>}
                            {reg.insurance_doc_path && <div style={{ fontSize:11, marginTop:3 }}><a href={reg.insurance_doc_path} target="_blank" rel="noreferrer" style={{ color:'#3B82F6' }}>📄 View Document</a></div>}
                          </>
                        ) : (
                          <div style={{ fontSize:12, color:'#D97706' }}>⚠️ No insurance submitted</div>
                        )}
                      </div>

                      {/* Security Bond */}
                      <div style={{ background: Number(reg.deposit)>0 ? '#F0FDF4' : '#F9FAFB', border:`1px solid ${Number(reg.deposit)>0 ? '#86EFAC':'#E5E7EB'}`, borderRadius:8, padding:'8px 10px' }}>
                        <div style={{ fontSize:10, fontWeight:700, color: Number(reg.deposit)>0 ? '#059669':'#696969', textTransform:'uppercase', letterSpacing:0.5, marginBottom:5 }}>
                          🔒 Security Bond
                        </div>
                        {Number(reg.deposit) > 0 ? (
                          <div style={{ fontSize:13, fontWeight:700, color:'#059669' }}>Rs. {Number(reg.deposit).toLocaleString()}</div>
                        ) : (
                          <div style={{ fontSize:12, color:'#969696' }}>No bond set</div>
                        )}
                        {Number(reg.deposit) > 0 && <div style={{ fontSize:10, color:'#6B7280', marginTop:2 }}>Paid directly to owner · Refundable</div>}
                      </div>

                      {/* Driver Details (only when has driver) */}
                      {(reg.has_owner_driver||reg.with_driver) && (reg.owner_driver_name||reg.driver_name) ? (
                        <div style={{ background:'#F5F3FF', border:'1px solid #DDD6FE', borderRadius:8, padding:'8px 10px' }}>
                          <div style={{ fontSize:10, fontWeight:700, color:'#6D28D9', textTransform:'uppercase', letterSpacing:0.5, marginBottom:5 }}>🧑‍✈️ Driver Info</div>
                          <div style={{ fontSize:12, color:'#141413', marginBottom:2 }}>
                            <strong>{reg.owner_driver_name||reg.driver_name}</strong>
                          </div>
                          {reg.owner_driver_experience > 0 && <div style={{ fontSize:11, color:'#696969', marginBottom:2 }}>{reg.owner_driver_experience} yrs experience</div>}
                          {reg.owner_driver_languages && <div style={{ fontSize:11, color:'#696969' }}>Langs: {reg.owner_driver_languages}</div>}
                          {reg.driver_license && <div style={{ fontSize:11, color:'#696969', marginTop:2 }}>Lic: <span style={{ fontFamily:'monospace' }}>{reg.driver_license}</span></div>}
                        </div>
                      ) : null}

                    </div>
                  </div>
                ))}
              </div>
            )}

            {pendingRegs.length === 0 && (
              <div style={{ fontSize:13, color:'#059669', fontWeight:600 }}>
                ✅ No pending vehicle registrations — all submissions have been reviewed.
              </div>
            )}
          </div>
        );
      })()}

      {/* ── Featured Vehicles Summary Panel ─────────────────────── */}
      {(() => {
        const featuredList = [...data.vehicles]
          .filter(v=>Number(v.is_featured_home)===1 && v.is_active)
          .sort((a,b)=>(a.featured_order||99)-(b.featured_order||99));
        const MAX_SLOTS = 12;
        return (
          <div style={{ background:'#FFFBEB', border:'1.5px solid #EAB308', borderRadius:14, padding:'14px 18px', marginBottom:20 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: featuredList.length>0 ? 12 : 0, flexWrap:'wrap', gap:8 }}>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ fontSize:18 }}>⭐</span>
                <span style={{ fontWeight:800, fontSize:14, color:'#92400E' }}>Featured on Homepage</span>
                <span style={{ background: featuredList.length>=MAX_SLOTS?'#DC2626':'#EAB308', color:'#fff', borderRadius:999, fontSize:11, fontWeight:700, padding:'2px 8px' }}>
                  {featuredList.length} / {MAX_SLOTS} slots
                </span>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ fontSize:12, color:'#92400E', fontStyle:'italic' }}>These vehicles appear in the Top Vehicles section &amp; hero circles</span>
                {featuredList.length > 0 && (
                  <button
                    onClick={async () => {
                      if (!window.confirm(`Remove ALL ${featuredList.length} vehicles from featured? This cannot be undone.`)) return;
                      const API = (window.CEYRIDE_API_BASE || 'api').replace(/\/$/, '');
                      const res  = await fetch(`${API}/cms_vehicles.php?action=clear_all_featured`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json', ...getAdminAuthHdr() },
                        body: JSON.stringify({}),
                      });
                      const json = await res.json();
                      if (json.success) {
                        // Set all vehicles to unfeatured in local state
                        setData(d=>({...d, vehicles:d.vehicles.map(v=>({...v, is_featured_home:0, featured_order:999}))}));
                      }
                    }}
                    style={{ ...BTN, background:'#FEE2E2', color:'#DC2626', border:'1px solid #FCA5A5', padding:'5px 10px', fontSize:11, fontWeight:700 }}
                  >
                    🗑 Clear All Featured
                  </button>
                )}
              </div>
            </div>
            {featuredList.length === 0 ? (
              <div style={{ fontSize:13, color:'#D97706', fontStyle:'italic' }}>No featured vehicles yet — click ⭐ on any vehicle card to add it.</div>
            ) : (
              <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                {featuredList.map((v,i) => (
                  <div key={v.id} style={{ display:'flex', alignItems:'center', gap:6, background:'#fff', border:'1.5px solid #EAB308', borderRadius:10, padding:'5px 10px', fontSize:12 }}>
                    <span style={{ fontWeight:800, color:'#EAB308', minWidth:16 }}>#{v.featured_order||i+1}</span>
                    {v.image_url || v.img ? <img src={resolveImgUrl(v.image_url||v.img)} alt="" style={{ width:28, height:28, borderRadius:6, objectFit:'cover', border:'1px solid rgba(0,0,0,0.08)' }} onError={e=>{e.target.style.display='none';}} /> : null}
                    <span style={{ fontWeight:600, color:'#141413' }}>{v.brand} {v.model}</span>
                    <button onClick={()=>toggleFeatured(v.id)} title="Remove from featured" style={{ background:'none', border:'none', cursor:'pointer', color:'#DC2626', fontWeight:800, fontSize:14, lineHeight:1, padding:'0 2px' }}>×</button>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })()}

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:16 }}>
        {list.map(v => (
          <div key={v.id} style={{ background:'#fff', borderRadius:16, overflow:'hidden', boxShadow:'0 2px 8px rgba(20,20,19,0.07)', opacity:v.is_active?1:0.6 }}>
            <div style={{ height:140, overflow:'hidden', position:'relative', background:'#F5F5F3' }}>
              <img src={resolveImgUrl(v.img||v.image_url)} alt={v.model} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>{e.target.style.display='none';}} />
              <div style={{ position:'absolute', top:8, right:8 }}><CmsBadge status={v.status||'approved'} /></div>
              <div style={{ position:'absolute', top:8, left:8 }}><StatusToggle active={!!v.is_active} onChange={()=>toggleActive(v.id)} /></div>
              {Number(v.is_featured_home)===1 && (
                <div style={{ position:'absolute', bottom:8, left:8, background:'#EAB308', borderRadius:20, padding:'3px 9px', fontSize:10, fontWeight:800, color:'#fff', display:'flex', alignItems:'center', gap:4, boxShadow:'0 2px 8px rgba(0,0,0,0.15)' }}>
                  ⭐ Featured #{v.featured_order || '—'}
                </div>
              )}
            </div>
            <div style={{ padding:'14px 16px' }}>
              <div style={{ fontWeight:700, fontSize:15, color:'#141413', marginBottom:2 }}>{v.brand} {v.model}</div>
              <div style={{ fontSize:12, color:'#969696', marginBottom:6 }}>{v.type} · {v.year} · {v.seats} seats · Rs. {Number(v.price_per_day||0).toLocaleString()}/day</div>
              {/* Insurance status chip */}
              {v.insurance_type && v.insurance_type !== 'none' ? (
                <div style={{ marginBottom:8, display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
                  <span style={{
                    display:'inline-flex', alignItems:'center', gap:4,
                    padding:'2px 8px', borderRadius:999, fontSize:10, fontWeight:700,
                    background: v.insurance_verified ? '#D1FAE5' : '#FEF3C7',
                    color:      v.insurance_verified ? '#059669' : '#D97706',
                  }}>
                    {v.insurance_verified ? '✅' : '⚠️'} {INS_LABELS[v.insurance_type] || v.insurance_type}
                  </span>
                  {v.insurance_expiry && (() => {
                    const daysLeft = Math.floor((new Date(v.insurance_expiry) - new Date()) / 86400000);
                    if (daysLeft < 0) return <span style={{ fontSize:10, fontWeight:700, color:'#DC2626', background:'#FEE2E2', padding:'2px 7px', borderRadius:999 }}>🚫 Expired</span>;
                    if (daysLeft <= 30) return <span style={{ fontSize:10, fontWeight:700, color:'#D97706', background:'#FEF3C7', padding:'2px 7px', borderRadius:999 }}>⚠️ {daysLeft}d</span>;
                    return null;
                  })()}
                </div>
              ) : (
                <div style={{ marginBottom:8 }}>
                  <span style={{ display:'inline-flex', alignItems:'center', gap:4, padding:'2px 8px', borderRadius:999, fontSize:10, fontWeight:700, background:'#F3F4F6', color:'#9CA3AF' }}>
                    — No Insurance
                  </span>
                </div>
              )}
              <div style={{ display:'flex', gap:7, flexWrap:'wrap' }}>
                <button
                  onClick={()=>toggleFeatured(v.id)}
                  disabled={featSaving===v.id}
                  title={Number(v.is_featured_home)===1 ? 'Remove from homepage featured' : 'Add to homepage featured'}
                  style={{ ...BTN, padding:'7px 10px', background:Number(v.is_featured_home)===1?'#FEF3C7':'#F5F5F3', color:Number(v.is_featured_home)===1?'#92400E':'#969696', border:`1.5px solid ${Number(v.is_featured_home)===1?'#EAB308':'rgba(20,20,19,0.12)'}`, opacity:featSaving===v.id?.6:1, transition:'all 0.2s' }}
                >{featSaving===v.id ? '⏳' : Number(v.is_featured_home)===1 ? '⭐' : '☆'}</button>
                {/* Insurance verify button — shown only when vehicle has insurance */}
                {v.insurance_type && v.insurance_type !== 'none' && (
                  <button
                    onClick={()=>verifyInsurance(v.id, v.insurance_verified)}
                    disabled={insSaving===v.id}
                    title={v.insurance_verified ? 'Click to un-verify insurance' : 'Click to verify insurance'}
                    style={{ ...BTN, padding:'7px 10px', background: v.insurance_verified?'#D1FAE5':'#FEF3C7', color:v.insurance_verified?'#059669':'#D97706', border:`1.5px solid ${v.insurance_verified?'#059669':'#F59E0B'}`, opacity:insSaving===v.id?.6:1, fontSize:11, fontWeight:700 }}
                  >{insSaving===v.id ? '⏳' : v.insurance_verified ? '✅ Verified' : '🛡️ Verify'}</button>
                )}
                <button onClick={()=>openEdit(v)} style={{ ...BTN, flex:1, background:'#7C3AED', color:'#fff', padding:'7px 0' }}>✏️ Edit</button>
                <button onClick={()=>setDelConf(v.id)} style={{ ...BTN, background:'#FEE2E2', color:'#DC2626', padding:'7px 12px' }}>🗑</button>
              </div>
            </div>
          </div>
        ))}
        {list.length===0 && <div style={{ gridColumn:'1/-1', textAlign:'center', padding:'48px', color:'#969696' }}>No vehicles found</div>}
      </div>

      {/* Add/Edit Modal */}
      {modal && (
        <Modal title={modal==='add'?'Add New Vehicle':'Edit Vehicle'} onClose={()=>setModal(null)} wide>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            {[['Brand *','brand','text'],['Model *','model','text'],['Year','year','number'],['Seats','seats','number'],['Price Per Day (LKR) *','price_per_day','number'],['Location','location','text']].map(([l,k,t])=>(
              <FieldRow key={k} label={l}><input style={FL} type={t} value={form[k]||''} onChange={e=>setF(k,t==='number'?+e.target.value:e.target.value)} /></FieldRow>
            ))}
            <FieldRow label="Vehicle Type">
              <select style={FL} value={form.type||'Car'} onChange={e=>setF('type',e.target.value)}>
                {TYPES.map(t=><option key={t}>{t}</option>)}
              </select>
            </FieldRow>
            <FieldRow label="Fuel Policy">
              <select style={FL} value={form.fuel_policy||'Full-to-Full'} onChange={e=>setF('fuel_policy',e.target.value)}>
                {FUELS.map(f=><option key={f}>{f}</option>)}
              </select>
            </FieldRow>
          </div>
          <FieldRow label="Description">
            <textarea style={{ ...FL, minHeight:72, resize:'vertical' }} value={form.description||''} onChange={e=>setF('description',e.target.value)} />
          </FieldRow>
          {/* ── Driver Options Section ─────────────────────────────── */}
          <div style={{ background:'#F0FDF4', border:`1.5px solid ${(form.has_self_drive||form.has_owner_driver)?'#16A34A':'rgba(22,163,74,0.3)'}`, borderRadius:10, padding:'14px 15px', marginBottom:14 }}>
            <div style={{ fontWeight:700, fontSize:14, color:'#15803D', marginBottom:12, display:'flex', alignItems:'center', gap:8 }}>
              🚗 Driver Options
              <span style={{ fontWeight:400, fontSize:11, color:'#4ADE80', background:'#14532D', padding:'2px 8px', borderRadius:999 }}>
                {[form.has_self_drive&&'Self-Drive', form.has_owner_driver&&'Owner Driver'].filter(Boolean).join(' + ') || 'None selected'}
              </span>
            </div>

            {/* ── Self-Drive block ── */}
            <div style={{ background:'#fff', borderRadius:8, padding:'12px 14px', marginBottom:10, border:'1.5px solid rgba(22,163,74,0.2)' }}>
              <label style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer', fontSize:14, fontWeight:700, color:'#15803D' }}>
                <input type="checkbox" checked={!!form.has_self_drive}
                  onChange={e=>{ const v=e.target.checked?1:0; setF('has_self_drive',v); setF('self_drive',v); }}
                  style={{ accentColor:'#16A34A', width:16, height:16 }} />
                🔑 Self-Drive Available
              </label>
              <div style={{ fontSize:12, color:'#6B7280', marginTop:4, marginLeft:24 }}>Customer drives the vehicle themselves. Driving licence required.</div>
              {!!form.has_self_drive && (
                <div style={{ marginTop:10, marginLeft:24 }}>
                  <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>
                    Self-Drive Price (LKR / day)
                    <span style={{ fontWeight:400, color:'#6B7280', marginLeft:6 }}>— leave blank to use the main price above</span>
                  </label>
                  <input
                    style={{ ...FL, maxWidth:200, border:'1.5px solid #BBF7D0' }}
                    type="number" min="0"
                    placeholder={`Default: ${form.price_per_day||'same as above'}`}
                    value={form.self_drive_price||''}
                    onChange={e=>setF('self_drive_price',+e.target.value||'')}
                  />
                </div>
              )}
            </div>

            {/* ── Owner Driver block ── */}
            <div style={{ background:'#fff', borderRadius:8, padding:'12px 14px', border:'1.5px solid rgba(22,163,74,0.2)' }}>
              <label style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer', fontSize:14, fontWeight:700, color:'#15803D' }}>
                <input type="checkbox" checked={!!form.has_owner_driver}
                  onChange={e=>{ const v=e.target.checked?1:0; setF('has_owner_driver',v); setF('with_driver',v); }}
                  style={{ accentColor:'#16A34A', width:16, height:16 }} />
                👨‍✈️ Owner's Driver Included
              </label>
              <div style={{ fontSize:12, color:'#6B7280', marginTop:4, marginLeft:24 }}>Vehicle owner provides a driver. Customer cannot remove this driver. Price must include driver.</div>

              {!!form.has_owner_driver && (
                <div style={{ marginTop:14, marginLeft:24, display:'flex', flexDirection:'column', gap:12 }}>
                  {/* All-in price */}
                  <div>
                    <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>
                      Price WITH Driver Included (LKR / day) *
                      <span style={{ fontWeight:400, color:'#6B7280', marginLeft:6 }}>— this is the all-in rate shown to customers</span>
                    </label>
                    <input
                      style={{ ...FL, maxWidth:220, border:'1.5px solid #BBF7D0' }}
                      type="number" min="0"
                      placeholder="e.g. 12000"
                      value={form.owner_driver_price||''}
                      onChange={e=>setF('owner_driver_price',+e.target.value||'')}
                    />
                  </div>
                  {/* Driver name + experience row */}
                  <div style={{ display:'grid', gridTemplateColumns:'1fr 120px', gap:10 }}>
                    <div>
                      <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>Driver Full Name *</label>
                      <input style={{ ...FL, border:'1.5px solid #BBF7D0' }} type="text" placeholder="e.g. Nuwan Perera"
                        value={form.owner_driver_name||''} onChange={e=>setF('owner_driver_name',e.target.value)} />
                    </div>
                    <div>
                      <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>Experience (yrs)</label>
                      <input style={{ ...FL, border:'1.5px solid #BBF7D0' }} type="number" min="0" max="50" placeholder="0"
                        value={form.owner_driver_experience||0} onChange={e=>setF('owner_driver_experience',+e.target.value)} />
                    </div>
                  </div>
                  {/* Contact */}
                  <div>
                    <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>Driver Contact (internal — not shown to customers)</label>
                    <input style={{ ...FL, border:'1.5px solid #BBF7D0' }} type="text" placeholder="+94 7X XXX XXXX"
                      value={form.owner_driver_contact||''} onChange={e=>setF('owner_driver_contact',e.target.value)} />
                  </div>
                  {/* Languages */}
                  <div>
                    <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>Languages (comma-separated)</label>
                    <input style={{ ...FL, border:'1.5px solid #BBF7D0' }} type="text" placeholder="e.g. Sinhala, English, Tamil"
                      value={Array.isArray(form.owner_driver_languages) ? form.owner_driver_languages.join(', ') : (form.owner_driver_languages||'')}
                      onChange={e=>setF('owner_driver_languages',e.target.value)} />
                  </div>
                  {/* Photo URL */}
                  <div>
                    <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#15803D', marginBottom:5 }}>Driver Photo URL</label>
                    <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                      <input style={{ ...FL, border:'1.5px solid #BBF7D0', flex:1 }} type="text" placeholder="Upload or paste photo URL"
                        value={form.owner_driver_photo||''} onChange={e=>setF('owner_driver_photo',e.target.value)} />
                      <ImageUploadBtn onUpload={url=>setF('owner_driver_photo',url)} current={form.owner_driver_photo} label="📷 Photo" />
                    </div>
                    {form.owner_driver_photo && (
                      <div style={{ marginTop:6, display:'flex', alignItems:'center', gap:8 }}>
                        <img src={form.owner_driver_photo} alt="Driver" style={{ width:36, height:36, borderRadius:'50%', objectFit:'cover', border:'2px solid #BBF7D0' }} onError={e=>e.target.style.display='none'} />
                        <span style={{ fontSize:11, color:'#059669' }}>✅ Photo set</span>
                      </div>
                    )}
                  </div>
                  {/* Validation hint */}
                  {(!form.owner_driver_name || !form.owner_driver_price) && (
                    <div style={{ background:'#FEF3C7', border:'1.5px solid #F59E0B', borderRadius:8, padding:'8px 12px', fontSize:12, color:'#92400E' }}>
                      ⚠️ Driver name and all-in price are required when Owner Driver is enabled.
                    </div>
                  )}
                </div>
              )}
            </div>

            {!form.has_self_drive && !form.has_owner_driver && (
              <div style={{ marginTop:10, background:'#FEE2E2', borderRadius:8, padding:'8px 12px', fontSize:12, color:'#DC2626', fontWeight:600 }}>
                ⚠️ At least one driver option must be selected for the vehicle to be bookable.
              </div>
            )}
          </div>

          {/* ── Homepage Featured Section ─────────────────────── */}
          <div style={{ background:'#FFFBEB', border:`1.5px solid ${form.is_featured_home?'#EAB308':'rgba(234,179,8,0.35)'}`, borderRadius:10, padding:'13px 15px', marginBottom:14, transition:'border-color 0.2s' }}>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom: form.is_featured_home ? 12 : 0 }}>
              <label style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer', fontSize:14, fontWeight:700, color:'#92400E', flex:1 }}>
                <input
                  type="checkbox"
                  checked={!!form.is_featured_home}
                  onChange={e=>{ setF('is_featured_home',e.target.checked?1:0); if(!e.target.checked) setF('featured_order',0); }}
                  style={{ accentColor:'#EAB308', width:16, height:16 }}
                />
                ⭐ Feature on Homepage (Top Vehicles)
              </label>
              {!!form.is_featured_home && (
                <div style={{ display:'flex', alignItems:'center', gap:6, flexShrink:0 }}>
                  <span style={{ fontSize:12, fontWeight:600, color:'#92400E' }}>Order:</span>
                  <input
                    type="number" min="1" max="20"
                    value={form.featured_order||''}
                    placeholder="Auto"
                    onChange={e=>setF('featured_order',+e.target.value||0)}
                    style={{ ...FL, width:70, padding:'6px 10px', fontSize:13 }}
                  />
                </div>
              )}
            </div>
            {!!form.is_featured_home && (
              <div style={{ fontSize:11, color:'#D97706', fontStyle:'italic' }}>
                This vehicle will appear in the homepage Top Vehicles grid and hero circles. Leave Order blank to auto-assign.
              </div>
            )}
            {!form.is_featured_home && (
              <div style={{ fontSize:11, color:'#92400E', opacity:0.6 }}>Check to show this vehicle prominently on the homepage.</div>
            )}
          </div>

          {/* ── Insurance Coverage Section ───────────────────────── */}
          <div style={{ background:'#EFF6FF', border:`1.5px solid ${form.insurance_type && form.insurance_type!=='none' ? '#3B82F6' : 'rgba(59,130,246,0.3)'}`, borderRadius:10, padding:'13px 15px', marginBottom:14, transition:'border-color 0.2s' }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
              <span style={{ fontSize:16 }}>🛡️</span>
              <span style={{ fontWeight:700, fontSize:14, color:'#1E40AF' }}>Insurance Coverage</span>
              {modal==='edit' && form.insurance_verified ? (
                <span style={{ marginLeft:'auto', background:'#D1FAE5', color:'#059669', fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:999 }}>✅ Admin Verified</span>
              ) : modal==='edit' && form.insurance_type && form.insurance_type!=='none' ? (
                <span style={{ marginLeft:'auto', background:'#FEF3C7', color:'#D97706', fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:999 }}>⚠️ Pending Verification</span>
              ) : null}
            </div>

            {/* Insurance Type */}
            <div style={{ marginBottom:12 }}>
              <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#1E40AF', marginBottom:6 }}>Insurance Type</label>
              <select
                style={{ ...FL, border:'1.5px solid #BFDBFE' }}
                value={form.insurance_type||'none'}
                onChange={e=>setF('insurance_type',e.target.value)}
              >
                <option value="none">— No Insurance</option>
                <option value="comprehensive">Full Insurance (Comprehensive)</option>
                <option value="third_party">Third-Party Insurance</option>
                <option value="hire_reward">Hire &amp; Reward Insurance (Commercial)</option>
                <option value="self_drive_rental">Self-Drive Rental Insurance</option>
                <option value="driver_included">Driver-Included Rental Coverage</option>
              </select>
            </div>

            {/* Conditional fields — shown only when type is set */}
            {form.insurance_type && form.insurance_type !== 'none' && (
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
                {/* Provider */}
                <div>
                  <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#1E40AF', marginBottom:6 }}>Insurance Provider</label>
                  <input
                    style={{ ...FL, border:'1.5px solid #BFDBFE' }}
                    type="text"
                    placeholder="e.g. Ceylinco General Insurance"
                    value={form.insurance_provider||''}
                    onChange={e=>setF('insurance_provider',e.target.value)}
                  />
                </div>

                {/* Expiry Date */}
                <div>
                  <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#1E40AF', marginBottom:6 }}>Policy Expiry Date</label>
                  <input
                    style={{ ...FL, border:`1.5px solid ${form.insurance_expiry && new Date(form.insurance_expiry)<new Date() ? '#FCA5A5' : '#BFDBFE'}` }}
                    type="date"
                    min={new Date().toISOString().split('T')[0]}
                    value={form.insurance_expiry||''}
                    onChange={e=>setF('insurance_expiry',e.target.value)}
                  />
                  {form.insurance_expiry && new Date(form.insurance_expiry)<new Date() && (
                    <div style={{ fontSize:10, color:'#DC2626', marginTop:3 }}>⚠️ This date is in the past — policy may be expired.</div>
                  )}
                </div>

                {/* Policy Number */}
                <div style={{ gridColumn:'1/-1' }}>
                  <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#1E40AF', marginBottom:6 }}>
                    Policy Number
                    <span style={{ fontWeight:400, color:'#6B7280', marginLeft:6 }}>(stored securely — public API shows last 4 digits only)</span>
                  </label>
                  <input
                    style={{ ...FL, border:'1.5px solid #BFDBFE', fontFamily:'monospace', letterSpacing:'0.05em' }}
                    type="text"
                    placeholder="e.g. CGI-2025-00123456"
                    value={form.insurance_policy_number||''}
                    onChange={e=>setF('insurance_policy_number',e.target.value)}
                  />
                </div>

                {/* Insurance Document Path / URL */}
                <div style={{ gridColumn:'1/-1' }}>
                  <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#1E40AF', marginBottom:6 }}>Insurance Certificate Document</label>
                  <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                    <input
                      style={{ ...FL, border:'1.5px solid #BFDBFE', flex:1 }}
                      type="text"
                      placeholder="Upload or paste document URL"
                      value={form.insurance_doc_path||''}
                      onChange={e=>setF('insurance_doc_path',e.target.value)}
                    />
                    <ImageUploadBtn
                      onUpload={url=>setF('insurance_doc_path',url)}
                      current={form.insurance_doc_path}
                      label="📄 Upload Doc"
                    />
                  </div>
                  {form.insurance_doc_path && (
                    <div style={{ marginTop:6, fontSize:11, color:'#059669' }}>
                      ✅ Document on file —{' '}
                      <a href={form.insurance_doc_path} target="_blank" rel="noreferrer" style={{ color:'#3B82F6', textDecoration:'underline' }}>Preview</a>
                    </div>
                  )}
                </div>
              </div>
            )}

            <div style={{ marginTop:10, fontSize:11, color:'#3B82F6', fontStyle:'italic', opacity:0.8 }}>
              ℹ️ CeyRide currently does not provide insurance — all coverage is arranged independently by the vehicle owner.
            </div>
          </div>

          <FieldRow label="Vehicle Image">
            <ImageUploadBtn onUpload={url=>setF('image_url',url)} current={form.img||form.image_url} label="Upload Vehicle Photo" />
          </FieldRow>
          <div style={{ display:'flex', gap:10, marginTop:6 }}>
            <button onClick={()=>setModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={save} style={{ ...BTN, flex:2, background:'#E84800', color:'#fff', padding:'12px 0', fontSize:14 }}>
              {modal==='add'?'✓ Add Vehicle':'✓ Save Changes'}
            </button>
          </div>
        </Modal>
      )}

      {/* Delete confirm */}
      {delConf && (
        <Modal title="Confirm Delete" onClose={()=>setDelConf(null)}>
          <p style={{ color:'#696969', marginBottom:20 }}>Are you sure you want to delete this vehicle? This cannot be undone.</p>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={()=>setDelConf(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={()=>del(delConf)} style={{ ...BTN, flex:1, background:'#DC2626', color:'#fff', padding:'12px 0' }}>Delete</button>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ─── CMS: DRIVERS MANAGEMENT ──────────────────────────────────
function DriversCMS({ data, setData, auditLog }) {
  const [search, setSearch] = React.useState('');
  const [modal,  setModal]  = React.useState(null);
  const [delConf,setDelConf]= React.useState(null);
  const [form,   setForm]   = React.useState({});
  const setF = (k,v) => setForm(f=>({...f,[k]:v}));
  const empty = { name:'', phone:'', email:'', license_number:'', experience:3, daily_rate:3500, languages:['English'], location:'Colombo', about:'', is_active:1, photo_path:'' };
  const LANGS = ['English','Sinhala','Tamil','French','German','Chinese','Japanese'];

  const list = data.drivers.filter(d => {
    const q = search.toLowerCase();
    return !q || d.name.toLowerCase().includes(q) || (d.location||'').toLowerCase().includes(q);
  });

  const save = async () => {
    if(!form.name||!form.phone) { alert('Name and Phone required.'); return; }
    try {
      const method = modal==='add'?'POST':'PUT';
      const res = await fetch(`api/cms_drivers.php${modal==='edit'?`?id=${form.id}`:''}`,{method,headers:{'Content-Type':'application/json',...getAdminAuthHdr()},body:JSON.stringify(form)});
      const json = await res.json();
      if(modal==='add') setData(d=>({...d, drivers:[{...form,id:json.id||Date.now(),trips:0,rating:4.5},...d.drivers]}));
      else setData(d=>({...d, drivers:d.drivers.map(dr=>dr.id===form.id?{...dr,...form}:dr)}));
    } catch {
      if(modal==='add') setData(d=>({...d, drivers:[{...form,id:Date.now(),trips:0,rating:4.5},...d.drivers]}));
      else setData(d=>({...d, drivers:d.drivers.map(dr=>dr.id===form.id?{...dr,...form}:dr)}));
    }
    logAction(auditLog.logs,auditLog.setLogs,modal==='add'?'Created':'Updated','Driver',form.name);
    setModal(null);
  };

  const del = (id) => {
    const d = data.drivers.find(d=>d.id===id);
    setData(dt=>({...dt,drivers:dt.drivers.filter(dr=>dr.id!==id)}));
    logAction(auditLog.logs,auditLog.setLogs,'Deleted','Driver',d?.name||`ID ${id}`);
    setDelConf(null);
  };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Driver Management</h2>
          <p style={{ color:'#969696', fontSize:13 }}>{data.drivers.length} drivers · {data.drivers.filter(d=>d.is_active!==0).length} active</p>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <CmsSearchBar value={search} onChange={setSearch} placeholder="Search name…" />
          <button onClick={()=>{setForm({...empty});setModal('add');}} style={{ ...BTN, background:'#0066CC', color:'#fff', padding:'10px 18px' }}>+ Add Driver</button>
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(260px,1fr))', gap:14 }}>
        {list.map(d => (
          <div key={d.id} style={{ background:'#fff', borderRadius:14, padding:'18px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)', display:'flex', gap:14, alignItems:'flex-start' }}>
            <div style={{ width:52, height:52, borderRadius:12, background:'#0066CC18', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:22, color:'#0066CC', flexShrink:0, overflow:'hidden' }}>
              {d.photo_path ? <img src={resolveImgUrl(d.photo_path)} style={{ width:'100%',height:'100%',objectFit:'cover' }} onError={e=>{e.target.style.display='none';}} /> : (d.name||'?')[0]}
            </div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:2 }}>{d.name}</div>
              <div style={{ fontSize:11, color:'#969696', marginBottom:4 }}>{d.location} · {d.experience} yrs · Rs.{(d.daily_rate||0).toLocaleString()}/day</div>
              <div style={{ fontSize:11, color:'#F59E0B', marginBottom:8 }}>★ {d.rating||'4.5'} · {d.trips||0} trips</div>
              <div style={{ display:'flex', gap:6 }}>
                <button onClick={()=>{setForm({...d,languages:Array.isArray(d.languages)?d.languages:[]});setModal('edit');}} style={{ ...BTN, flex:1, background:'#7C3AED', color:'#fff', padding:'6px 0', fontSize:11 }}>✏️ Edit</button>
                <button onClick={()=>setDelConf(d.id)} style={{ ...BTN, background:'#FEE2E2', color:'#DC2626', padding:'6px 10px', fontSize:11 }}>🗑</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {modal && (
        <Modal title={modal==='add'?'Add Driver':'Edit Driver'} onClose={()=>setModal(null)} wide>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            {[['Full Name *','name','text'],['Phone *','phone','text'],['Email','email','email'],['License Number','license_number','text'],['Experience (years)','experience','number'],['Daily Rate (LKR)','daily_rate','number'],['Location','location','text']].map(([l,k,t])=>(
              <FieldRow key={k} label={l}><input style={FL} type={t} value={form[k]||''} onChange={e=>setF(k,t==='number'?+e.target.value:e.target.value)} /></FieldRow>
            ))}
          </div>
          <FieldRow label="Languages">
            <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
              {LANGS.map(l => (
                <label key={l} style={{ display:'flex', gap:6, alignItems:'center', cursor:'pointer', fontSize:13, fontWeight:600, padding:'5px 10px', borderRadius:8, background:(form.languages||[]).includes(l)?'#0066CC10':'#F5F5F3', border:`1px solid ${(form.languages||[]).includes(l)?'#0066CC':'transparent'}` }}>
                  <input type="checkbox" checked={(form.languages||[]).includes(l)} onChange={e=>setF('languages',e.target.checked?[...(form.languages||[]),l]:(form.languages||[]).filter(x=>x!==l))} style={{ accentColor:'#0066CC' }} />
                  {l}
                </label>
              ))}
            </div>
          </FieldRow>
          <FieldRow label="About"><textarea style={{ ...FL, minHeight:60, resize:'vertical' }} value={form.about||''} onChange={e=>setF('about',e.target.value)} /></FieldRow>
          <FieldRow label="Profile Photo"><ImageUploadBtn onUpload={url=>setF('photo_path',url)} current={form.photo_path} label="Upload Driver Photo" /></FieldRow>
          <div style={{ display:'flex', gap:10, marginTop:6 }}>
            <button onClick={()=>setModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={save} style={{ ...BTN, flex:2, background:'#0066CC', color:'#fff', padding:'12px 0', fontSize:14 }}>
              {modal==='add'?'✓ Add Driver':'✓ Save Changes'}
            </button>
          </div>
        </Modal>
      )}
      {delConf && <Modal title="Confirm Delete" onClose={()=>setDelConf(null)}><p style={{ color:'#696969', marginBottom:20 }}>Delete this driver permanently?</p><div style={{ display:'flex', gap:10 }}><button onClick={()=>setDelConf(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button><button onClick={()=>del(delConf)} style={{ ...BTN, flex:1, background:'#DC2626', color:'#fff', padding:'12px 0' }}>Delete</button></div></Modal>}
    </div>
  );
}

// ─── CMS: GUIDES MANAGEMENT ───────────────────────────────────
function GuidesCMS({ data, setData, auditLog }) {
  const [search, setSearch] = React.useState('');
  const [modal,  setModal]  = React.useState(null);
  const [delConf,setDelConf]= React.useState(null);
  const [form,   setForm]   = React.useState({});
  const setF = (k,v) => setForm(f=>({...f,[k]:v}));
  const AREAS = ['Cultural Triangle','Hill Country','South Coast','East Coast','Wildlife','Ancient Cities','Tea Country'];
  const LANGS = ['English','Sinhala','Tamil','French','German','Chinese','Japanese'];

  const list = (data.guides||[]).filter(g => {
    const q = search.toLowerCase();
    return !q || g.name.toLowerCase().includes(q);
  });

  const save = async () => {
    if(!form.name||!form.phone) { alert('Name and Phone required.'); return; }
    try {
      const method = modal==='add'?'POST':'PUT';
      await fetch(`api/cms_guides.php${modal==='edit'?`?id=${form.id}`:''}`,{method,headers:{'Content-Type':'application/json',...getAdminAuthHdr()},body:JSON.stringify(form)});
    } catch {}
    if(modal==='add') setData(d=>({...d, guides:[{...form,id:Date.now(),trip_count:0,rating:0,status:'approved'},...(d.guides||[])]}));
    else setData(d=>({...d, guides:(d.guides||[]).map(g=>g.id===form.id?{...g,...form}:g)}));
    logAction(auditLog.logs,auditLog.setLogs,modal==='add'?'Created':'Updated','Guide',form.name);
    setModal(null);
  };

  const del = async id => {
    const g = (data.guides||[]).find(g=>g.id===id);
    try { await fetch(`api/cms_guides.php?id=${id}`, { method: 'DELETE', headers: getAdminAuthHdr() }); } catch {}
    setData(d=>({...d, guides:(d.guides||[]).filter(g=>g.id!==id)}));
    logAction(auditLog.logs,auditLog.setLogs,'Deleted','Guide',g?.name||`ID ${id}`);
    setDelConf(null);
  };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Tour Guide Management</h2>
          <p style={{ color:'#969696', fontSize:13 }}>{list.length} guides</p>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <CmsSearchBar value={search} onChange={setSearch} placeholder="Search guides…" />
          <button onClick={()=>{setForm({name:'',phone:'',email:'',guide_license_no:'',experience:'',languages:[],special_areas:[],about:'',photo_path:'',status:'approved'});setModal('add');}} style={{ ...BTN, background:'#7C3AED', color:'#fff', padding:'10px 18px' }}>+ Add Guide</button>
        </div>
      </div>

      <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(20,20,19,0.06)', overflow:'hidden' }}>
        <div style={{ overflowX:'auto' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, minWidth:500 }}>
            <thead><tr style={{ background:'#FAFAF9', borderBottom:'1px solid rgba(20,20,19,0.08)' }}>
              {['Name','License No.','Experience','Languages','Rating','Status','Actions'].map(h=><th key={h} style={{ padding:'11px 14px', textAlign:'left', fontWeight:700, fontSize:11, textTransform:'uppercase', color:'#696969', whiteSpace:'nowrap' }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {list.map((g,i) => (
                <tr key={g.id} style={{ borderBottom:'1px solid rgba(20,20,19,0.05)' }}>
                  <td style={{ padding:'11px 14px', fontWeight:600, color:'#141413' }}>{g.name}</td>
                  <td style={{ padding:'11px 14px', fontFamily:'monospace', fontSize:12 }}>{g.license||g.guide_license_no||'—'}</td>
                  <td style={{ padding:'11px 14px', color:'#696969' }}>{g.experience||'—'}</td>
                  <td style={{ padding:'11px 14px', color:'#696969' }}>{Array.isArray(g.languages)?g.languages.slice(0,2).join(', '):g.languages||'—'}</td>
                  <td style={{ padding:'11px 14px', color:'#F59E0B', fontWeight:700 }}>★ {g.rating||'—'}</td>
                  <td style={{ padding:'11px 14px' }}><CmsBadge status={g.status||'approved'} /></td>
                  <td style={{ padding:'11px 14px' }}>
                    <div style={{ display:'flex', gap:6 }}>
                      <button onClick={()=>{setForm({...g,languages:Array.isArray(g.languages)?g.languages:[],special_areas:Array.isArray(g.special_areas)?g.special_areas:[]});setModal('edit');}} style={{ ...BTN, background:'#7C3AED', color:'#fff', padding:'5px 10px', fontSize:11 }}>✏️</button>
                      <button onClick={()=>setDelConf(g.id)} style={{ ...BTN, background:'#FEE2E2', color:'#DC2626', padding:'5px 10px', fontSize:11 }}>🗑</button>
                    </div>
                  </td>
                </tr>
              ))}
              {list.length===0 && <tr><td colSpan={7} style={{ textAlign:'center', padding:'40px', color:'#969696' }}>No guides found</td></tr>}
            </tbody>
          </table>
        </div>
      </div>

      {modal && (
        <Modal title={modal==='add'?'Add Tour Guide':'Edit Tour Guide'} onClose={()=>setModal(null)} wide>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            {[['Full Name *','name','text'],['Phone *','phone','text'],['Email','email','email'],['Guide License No.','guide_license_no','text'],['Experience','experience','text']].map(([l,k,t])=>(
              <FieldRow key={k} label={l}><input style={FL} type={t} value={form[k]||''} onChange={e=>setF(k,e.target.value)} /></FieldRow>
            ))}
          </div>
          <FieldRow label="Languages">
            <div style={{ display:'flex', flexWrap:'wrap', gap:7 }}>
              {LANGS.map(l=>(
                <label key={l} style={{ display:'flex', gap:5, alignItems:'center', cursor:'pointer', fontSize:12, fontWeight:600, padding:'4px 9px', borderRadius:8, background:(form.languages||[]).includes(l)?'#7C3AED10':'#F5F5F3', border:`1px solid ${(form.languages||[]).includes(l)?'#7C3AED':'transparent'}` }}>
                  <input type="checkbox" checked={(form.languages||[]).includes(l)} onChange={e=>setF('languages',e.target.checked?[...(form.languages||[]),l]:(form.languages||[]).filter(x=>x!==l))} style={{ accentColor:'#7C3AED' }} /> {l}
                </label>
              ))}
            </div>
          </FieldRow>
          <FieldRow label="Special Areas">
            <div style={{ display:'flex', flexWrap:'wrap', gap:7 }}>
              {AREAS.map(a=>(
                <label key={a} style={{ display:'flex', gap:5, alignItems:'center', cursor:'pointer', fontSize:12, fontWeight:600, padding:'4px 9px', borderRadius:8, background:(form.special_areas||[]).includes(a)?'#E8480010':'#F5F5F3', border:`1px solid ${(form.special_areas||[]).includes(a)?'#E84800':'transparent'}` }}>
                  <input type="checkbox" checked={(form.special_areas||[]).includes(a)} onChange={e=>setF('special_areas',e.target.checked?[...(form.special_areas||[]),a]:(form.special_areas||[]).filter(x=>x!==a))} style={{ accentColor:'#E84800' }} /> {a}
                </label>
              ))}
            </div>
          </FieldRow>
          <FieldRow label="About"><textarea style={{ ...FL, minHeight:60, resize:'vertical' }} value={form.about||''} onChange={e=>setF('about',e.target.value)} /></FieldRow>
          <FieldRow label="Profile Photo"><ImageUploadBtn onUpload={url=>setF('photo_path',url)} current={form.photo_path} /></FieldRow>
          <div style={{ display:'flex', gap:10, marginTop:6 }}>
            <button onClick={()=>setModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={save} style={{ ...BTN, flex:2, background:'#7C3AED', color:'#fff', padding:'12px 0', fontSize:14 }}>{modal==='add'?'✓ Add Guide':'✓ Save Changes'}</button>
          </div>
        </Modal>
      )}
      {delConf && <Modal title="Confirm Delete" onClose={()=>setDelConf(null)}><p style={{ color:'#696969', marginBottom:20 }}>Delete this guide permanently?</p><div style={{ display:'flex', gap:10 }}><button onClick={()=>setDelConf(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button><button onClick={()=>del(delConf)} style={{ ...BTN, flex:1, background:'#DC2626', color:'#fff', padding:'12px 0' }}>Delete</button></div></Modal>}
    </div>
  );
}

// ─── CMS: PACKAGES MANAGEMENT ─────────────────────────────────
function PackagesCMS({ data, setData, auditLog }) {
  const [search, setSearch] = React.useState('');
  const [modal,  setModal]  = React.useState(null);
  const [delConf,setDelConf]= React.useState(null);
  const [form,   setForm]   = React.useState({});
  const setF = (k,v) => setForm(f=>({...f,[k]:v}));
  const CATS = ['transfer','cultural','scenic','roundtrip','adventure','wildlife'];

  const list = (data.packages||[]).filter(p => !search || p.name.toLowerCase().includes(search.toLowerCase()));

  const save = async () => {
    if(!form.name||!form.price) { alert('Name and Price required.'); return; }
    try {
      const method = modal==='add'?'POST':'PUT';
      const formToSend = {
        ...form,
        price_lkr: form.price,
        // Convert comma-separated string entered in the textarea to an array so
        // the backend pkgList() (which splits on \n) receives a proper array.
        locations: typeof form.locations === 'string'
          ? form.locations.split(',').map(s => s.trim()).filter(Boolean)
          : (form.locations || []),
      };
      await fetch(`api/cms_packages.php${modal==='edit'?`?id=${form.id}`:''}`,{method,headers:{'Content-Type':'application/json',...getAdminAuthHdr()},body:JSON.stringify(formToSend)});
    } catch {}
    if(modal==='add') setData(d=>({...d, packages:[{...form,id:Date.now(),price_lkr:form.price,bookings:0,status:'approved'},...(d.packages||[])]}));
    else setData(d=>({...d, packages:(d.packages||[]).map(p=>p.id===form.id?{...p,...form,price_lkr:form.price}:p)}));
    logAction(auditLog.logs,auditLog.setLogs,modal==='add'?'Created':'Updated','Package',form.name);
    setModal(null);
  };

  const del = async id => {
    const p = (data.packages||[]).find(p=>p.id===id);
    try { await fetch(`api/cms_packages.php?id=${id}`, { method: 'DELETE', headers: getAdminAuthHdr() }); } catch {}
    setData(d=>({...d, packages:(d.packages||[]).filter(p=>p.id!==id)}));
    logAction(auditLog.logs,auditLog.setLogs,'Deleted','Package',p?.name||`ID ${id}`);
    setDelConf(null);
  };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Tour Package Management</h2>
          <p style={{ color:'#969696', fontSize:13 }}>{list.length} packages</p>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <CmsSearchBar value={search} onChange={setSearch} placeholder="Search packages…" />
          <button onClick={()=>{setForm({name:'',category:'cultural',duration:'',price:'',locations:'',description:'',highlights:'',inclusions:'',exclusions:'',max_pax:6,image_path:'',status:'approved',is_active:1,driver_included:1,vehicle_included:1});setModal('add');}} style={{ ...BTN, background:'#D97706', color:'#fff', padding:'10px 18px' }}>+ Add Package</button>
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:16 }}>
        {list.map(p => (
          <div key={p.id} style={{ background:'#fff', borderRadius:16, overflow:'hidden', boxShadow:'0 2px 8px rgba(20,20,19,0.07)' }}>
            <div style={{ height:120, overflow:'hidden', background:'#F5F5F3', position:'relative' }}>
              <img src={resolveImgUrl(p.image_path||p.image)} alt={p.name} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>e.target.style.display='none'} />
              <div style={{ position:'absolute', top:8, right:8 }}><CmsBadge status={p.status||'approved'} /></div>
            </div>
            <div style={{ padding:'14px 16px' }}>
              <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:2 }}>{p.name}</div>
              <div style={{ fontSize:12, color:'#969696', marginBottom:2 }}>{p.duration} · Rs. {Number(p.price_lkr||p.price||0).toLocaleString()}</div>
              <div style={{ fontSize:11, color:'#7C3AED', marginBottom:8 }}>{p.category}</div>
              <div style={{ display:'flex', gap:7 }}>
                <button onClick={()=>{setForm({...p,price:p.price_lkr||p.price,locations:Array.isArray(p.locations)?p.locations.join(', '):p.locations,highlights:Array.isArray(p.highlights)?p.highlights.join('\n'):p.highlights||''});setModal('edit');}} style={{ ...BTN, flex:1, background:'#D97706', color:'#fff', padding:'7px 0' }}>✏️ Edit</button>
                <button onClick={()=>setDelConf(p.id)} style={{ ...BTN, background:'#FEE2E2', color:'#DC2626', padding:'7px 12px' }}>🗑</button>
              </div>
            </div>
          </div>
        ))}
        {list.length===0 && <div style={{ gridColumn:'1/-1', textAlign:'center', padding:'48px', color:'#969696' }}>No packages found</div>}
      </div>

      {modal && (
        <Modal title={modal==='add'?'Add Tour Package':'Edit Tour Package'} onClose={()=>setModal(null)} wide>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            {[['Package Name *','name','text'],['Duration','duration','text'],['Price (LKR) *','price','number'],['Max Passengers','max_pax','number']].map(([l,k,t])=>(
              <FieldRow key={k} label={l}><input style={FL} type={t} value={form[k]||''} onChange={e=>setF(k,t==='number'?+e.target.value:e.target.value)} /></FieldRow>
            ))}
            <FieldRow label="Category">
              <select style={FL} value={form.category||'cultural'} onChange={e=>setF('category',e.target.value)}>
                {CATS.map(c=><option key={c}>{c}</option>)}
              </select>
            </FieldRow>
          </div>
          <FieldRow label="Locations (comma separated)">
            <input style={FL} value={form.locations||''} onChange={e=>setF('locations',e.target.value)} placeholder="Kandy, Sigiriya, Ella" />
          </FieldRow>
          <FieldRow label="Description"><textarea style={{ ...FL, minHeight:72, resize:'vertical' }} value={form.description||''} onChange={e=>setF('description',e.target.value)} /></FieldRow>
          <FieldRow label="Highlights (one per line)"><textarea style={{ ...FL, minHeight:60, resize:'vertical' }} value={form.highlights||''} onChange={e=>setF('highlights',e.target.value)} placeholder="UNESCO sites&#10;Expert guide&#10;All entrance fees" /></FieldRow>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <FieldRow label="Inclusions (one per line)"><textarea style={{ ...FL, minHeight:60, resize:'vertical' }} value={form.inclusions||''} onChange={e=>setF('inclusions',e.target.value)} /></FieldRow>
            <FieldRow label="Exclusions (one per line)"><textarea style={{ ...FL, minHeight:60, resize:'vertical' }} value={form.exclusions||''} onChange={e=>setF('exclusions',e.target.value)} /></FieldRow>
          </div>
          <div style={{ display:'flex', gap:14, marginBottom:14 }}>
            {[['driver_included','Driver Included'],['vehicle_included','Vehicle Included']].map(([k,l])=>(
              <label key={k} style={{ display:'flex', gap:8, alignItems:'center', cursor:'pointer', fontSize:14, fontWeight:600 }}>
                <input type="checkbox" checked={!!form[k]} onChange={e=>setF(k,e.target.checked?1:0)} style={{ accentColor:'#D97706', width:16, height:16 }} /> {l}
              </label>
            ))}
          </div>
          <FieldRow label="Package Image"><ImageUploadBtn onUpload={url=>setF('image_path',url)} current={form.image_path||form.image} label="Upload Package Photo" /></FieldRow>
          <div style={{ display:'flex', gap:10, marginTop:6 }}>
            <button onClick={()=>setModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={save} style={{ ...BTN, flex:2, background:'#D97706', color:'#fff', padding:'12px 0', fontSize:14 }}>{modal==='add'?'✓ Add Package':'✓ Save Changes'}</button>
          </div>
        </Modal>
      )}
      {delConf && <Modal title="Confirm Delete" onClose={()=>setDelConf(null)}><p style={{ color:'#696969', marginBottom:20 }}>Delete this package permanently?</p><div style={{ display:'flex', gap:10 }}><button onClick={()=>setDelConf(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button><button onClick={()=>del(delConf)} style={{ ...BTN, flex:1, background:'#DC2626', color:'#fff', padding:'12px 0' }}>Delete</button></div></Modal>}
    </div>
  );
}

// ─── CMS: BOOKINGS MANAGEMENT ─────────────────────────────────
function BookingsCMS({ data, setData, auditLog }) {
  const [serviceType, setServiceType] = React.useState('vehicle'); // 'vehicle' | 'driver' | 'all'
  const [search,      setSearch]      = React.useState('');
  const [filter,      setFilter]      = React.useState('all');
  const [showFlagged, setShowFlagged] = React.useState(false);
  const [detail,      setDetail]      = React.useState(null);
  const [detailDocs,  setDetailDocs]  = React.useState([]);
  const [loadingDetail, setLoadingDetail] = React.useState(false);
  const [editing,     setEditing]     = React.useState(null);
  const [rejectModal, setRejectModal] = React.useState(null); // booking to reject
  const [rejectReason,setRejectReason]= React.useState('');
  const [approveNote, setApproveNote] = React.useState('');
  const [actionLoading, setActionLoading] = React.useState(null); // booking id being actioned
  const [flagModal,   setFlagModal]   = React.useState(null);  // flagged booking for moderation
  const [cleanedNote, setCleanedNote] = React.useState('');
  const setE = (k,v) => setEditing(e=>({...e,[k]:v}));

  // ── Unified source by service type ──────────────────────
  const vehicleBookings = (data.bookings       || []).map(b => ({ ...b, _btype: 'vehicle' }));
  const driverBookings  = (data.driverBookings || []).map(b => ({ ...b, _btype: 'driver'  }));
  const tourBookings    = (data.tourInquiries  || []).map(b => ({ ...b, _btype: 'tour',
    booking_ref: b.inquiry_ref || b.booking_ref,
    full_name:   b.full_name,
    total:       b.package_price || 0,
    pickup_date: b.start_date, return_date: b.start_date,
    days: 1,
  }));
  const sourceBookings  = serviceType === 'all'    ? [...vehicleBookings, ...driverBookings, ...tourBookings]
                        : serviceType === 'driver' ? driverBookings
                        : serviceType === 'tour'   ? tourBookings
                        : vehicleBookings;

  // ── Derived list ──────────────────────────────────────────
  const list = sourceBookings.filter(b => {
    const q    = search.toLowerCase();
    const sOk  = filter === 'all' || b.status === filter;
    const fOk  = !showFlagged || (b.content_status === 'flagged');
    const name = (b.customer || b.full_name || '').toLowerCase();
    const ref  = (b.ref || b.booking_ref || '').toLowerCase();
    const tOk  = !q || name.includes(q) || ref.includes(q) || (b.email||'').toLowerCase().includes(q);
    return sOk && fOk && tOk;
  });

  const counts = {
    all:       sourceBookings.length,
    pending:   sourceBookings.filter(b=>b.status==='pending').length,
    new:       sourceBookings.filter(b=>b.status==='new').length,
    confirmed: sourceBookings.filter(b=>b.status==='confirmed').length,
    active:    sourceBookings.filter(b=>b.status==='active').length,
    completed: sourceBookings.filter(b=>b.status==='completed').length,
    cancelled: sourceBookings.filter(b=>b.status==='cancelled').length,
    flagged:   sourceBookings.filter(b=>b.content_status==='flagged').length,
  };

  // ── Fetch full detail (including documents) ───────────────
  // Auth header helper — reads token from localStorage
  const authH = () => {
    try { const s=JSON.parse(localStorage.getItem('cr_admin')||'{}'); return s.token ? {'Authorization':`Bearer ${s.token}`} : {}; }
    catch { return {}; }
  };

  const openDetail = async (b) => {
    setDetail(b);
    setDetailDocs([]);
    // Tour inquiries and driver bookings carry full data — no extra fetch needed
    if (b._btype === 'tour' || b._btype === 'driver') { return; }
    // Vehicle bookings: fetch full record from CMS API
    setLoadingDetail(true);
    try {
      const res  = await fetch(`api/cms_bookings.php?id=${b.id}`, { headers: authH() });
      const json = await res.json();
      if (json.booking) {
        setDetail(json.booking);
        setDetailDocs(json.booking.documents || []);
      }
    } catch {}
    setLoadingDetail(false);
  };

  // ── Approve booking ───────────────────────────────────────
  const approveBooking = async (b) => {
    setActionLoading(b.id);
    try {
      const res  = await fetch(`api/cms_bookings.php?id=${b.id}`, {
        method:'PUT', headers:{'Content-Type':'application/json', ...authH()},
        body: JSON.stringify({ action:'approve', admin_note: approveNote })
      });
      const json = await res.json();
      if (json.success) {
        setData(d=>({...d, bookings: d.bookings.map(bk =>
          bk.id===b.id ? {...bk, status:'confirmed', approved_at: json.approved_at} : bk
        )}));
        logAction(auditLog.logs, auditLog.setLogs, 'Approved', 'Booking', b.ref||b.booking_ref||`ID ${b.id}`);
        if (detail?.id === b.id) setDetail(prev=>({...prev, status:'confirmed', approved_at: json.approved_at}));
      }
    } catch {}
    setActionLoading(null);
    setApproveNote('');
  };

  // ── Reject booking ────────────────────────────────────────
  const rejectBooking = async () => {
    if (!rejectModal || !rejectReason.trim()) return;
    const b = rejectModal;
    setActionLoading(b.id);
    try {
      const res  = await fetch(`api/cms_bookings.php?id=${b.id}`, {
        method:'PUT', headers:{'Content-Type':'application/json', ...authH()},
        body: JSON.stringify({ action:'reject', rejection_reason: rejectReason.trim() })
      });
      const json = await res.json();
      if (json.success) {
        setData(d=>({...d, bookings: d.bookings.map(bk =>
          bk.id===b.id ? {...bk, status:'cancelled', rejected_at: json.rejected_at, rejection_reason: rejectReason} : bk
        )}));
        logAction(auditLog.logs, auditLog.setLogs, 'Rejected', 'Booking', b.ref||b.booking_ref||`ID ${b.id}`);
        if (detail?.id === b.id) setDetail(prev=>({...prev, status:'cancelled', rejection_reason: rejectReason}));
      }
    } catch {}
    setActionLoading(null);
    setRejectModal(null);
    setRejectReason('');
  };

  // ── Clear flagged content ─────────────────────────────────
  const clearFlag = async () => {
    if (!flagModal) return;
    try {
      await fetch(`api/cms_bookings.php?id=${flagModal.id}`, {
        method:'PUT', headers:{'Content-Type':'application/json', ...authH()},
        body: JSON.stringify({ action:'clear_flag', cleaned_note: cleanedNote })
      });
      setData(d=>({...d, bookings: d.bookings.map(b =>
        b.id===flagModal.id ? {...b, content_status:'cleared', notes: cleanedNote} : b
      )}));
      logAction(auditLog.logs, auditLog.setLogs, 'Updated', 'Booking', `Flagged content cleared on ${flagModal.booking_ref||`ID ${flagModal.id}`}`);
    } catch {}
    setFlagModal(null);
    setCleanedNote('');
  };

  // ── Full edit save ────────────────────────────────────────
  const saveBooking = async () => {
    try {
      let endpoint, payload;
      if (editing._btype === 'tour') {
        endpoint = `api/cms_tour_inquiries.php?id=${editing.id}`;
        payload  = { status: editing.status, pax: editing.pax, start_date: editing.start_date, notes: editing.notes || '' };
      } else {
        endpoint = `api/cms_bookings.php?id=${editing.id}`;
        payload  = editing;
      }
      const res  = await fetch(endpoint, {
        method:'PUT', headers:{'Content-Type':'application/json', ...authH()},
        body: JSON.stringify(payload)
      });
      const json = await res.json();
      if (json.flagged) {
        alert(`⚠️ Contact information was detected and automatically masked in the notes field.\nTypes: ${json.flagged_types.join(', ')}`);
        setEditing(e=>({...e, notes: json.masked_note, content_status:'flagged'}));
        return;
      }
    } catch {}
    setData(d=>({...d, bookings: d.bookings.map(b => b.id===editing.id ? {...b,...editing} : b)}));
    logAction(auditLog.logs, auditLog.setLogs, 'Updated', 'Booking', editing.ref||editing.booking_ref||`ID ${editing.id}`);
    setEditing(null);
  };

  // ── Row background: highlight flagged & pending ───────────
  const rowBg = (b) => {
    if (b.content_status === 'flagged') return 'rgba(254,226,226,0.35)';
    if (b.status === 'pending')         return 'rgba(254,243,199,0.25)';
    return 'transparent';
  };

  // ── Shared detail row helper ──────────────────────────────
  const DR = ({label, value, highlight}) => (
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', padding:'8px 0', borderBottom:'1px solid rgba(20,20,19,0.06)', fontSize:13, gap:12 }}>
      <span style={{ color:'#696969', minWidth:130, flexShrink:0 }}>{label}</span>
      <span style={{ fontWeight:600, color: highlight||'#141413', textAlign:'right', wordBreak:'break-word' }}>{value||'—'}</span>
    </div>
  );

  return (
    <div>
      {/* ── Header ────────────────────────────────────────── */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Booking Management</h2>
          <p style={{ color:'#969696', fontSize:13 }}>
            {counts.all} total · <span style={{ color:'#F59E0B', fontWeight:600 }}>{serviceType === 'tour' ? (counts.new + ' new') : (counts.pending + ' pending')}</span>
            {counts.flagged > 0 && <span style={{ color:'#DC2626', fontWeight:700, marginLeft:8 }}>· ⚠️ {counts.flagged} flagged</span>}
          </p>
        </div>
        <div style={{ display:'flex', gap:8, alignItems:'center', flexWrap:'wrap' }}>
          <CmsSearchBar value={search} onChange={setSearch} placeholder="Search customer, ref, email…" />
          {counts.flagged > 0 && (
            <button onClick={()=>setShowFlagged(f=>!f)} style={{ ...BTN, background: showFlagged?'#DC2626':'#FEE2E2', color: showFlagged?'#fff':'#DC2626', border:'1.5px solid #DC2626', padding:'8px 14px', fontSize:12, fontWeight:700 }}>
              {showFlagged ? '✕ Clear Filter' : `⚠️ ${counts.flagged} Flagged`}
            </button>
          )}
        </div>
      </div>

      {/* ── Service type toggle ─────────────────────────── */}
      <div style={{ display:'flex', gap:6, marginBottom:12, background:'#F5F5F3', borderRadius:10, padding:'6px', width:'fit-content' }}>
        {[['vehicle','🚗 Vehicle Bookings'],['driver','🚘 Driver Bookings'],['tour','🎯 Tour Inquiries'],['all','📋 All Bookings']].map(([t,label])=>(
          <button key={t} onClick={()=>{setServiceType(t);setFilter('all');}} style={{ ...BTN, background:serviceType===t?'#141413':'transparent', color:serviceType===t?'#fff':'#696969', border:'none', padding:'7px 14px', fontWeight:700, borderRadius:8 }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── Status filter tabs ───────────────────────────── */}
      <div style={{ display:'flex', gap:7, marginBottom:16, flexWrap:'wrap' }}>
        {(serviceType === 'tour'
          ? [['all','All'],['new','New'],['contacted','Contacted'],['confirmed','Confirmed'],['cancelled','Cancelled']]
          : [['all','All'],['pending','Pending'],['confirmed','Confirmed'],['active','Active'],['completed','Completed'],['cancelled','Cancelled']]
        ).map(([f,label])=>(
          <button key={f} onClick={()=>setFilter(f)} style={{ ...BTN, background:filter===f?'#141413':'#fff', color:filter===f?'#fff':'#696969', border:`1.5px solid ${filter===f?'#141413':'rgba(20,20,19,0.12)'}` }}>
            {label} ({counts[f]||0})
          </button>
        ))}
      </div>

      {/* ── Workflow guide ───────────────────────────────── */}
      <div style={{ display:'flex', alignItems:'center', gap:0, marginBottom:16, background:'#F5F5F3', borderRadius:10, padding:'10px 16px', fontSize:12, color:'#696969', flexWrap:'wrap', gap:6 }}>
        <span style={{ fontWeight:700, color:'#141413', marginRight:4 }}>Booking flow:</span>
        {(serviceType === 'tour'
          ? [['📋 New','#6B7280'],['📞 Contacted','#0066CC'],['✅ Confirmed','#059669'],['❌ Cancelled','#DC2626']]
          : [['⏳ Pending','#F59E0B'],['✅ Confirmed','#059669'],['🚗 Active','#0066CC'],['🏁 Completed','#7C3AED'],['❌ Cancelled','#DC2626']]
        ).map(([label,color],i,arr)=>(
          <React.Fragment key={label}>
            <span style={{ background:`${color}18`, color, padding:'2px 10px', borderRadius:20, fontWeight:700, fontSize:11 }}>{label}</span>
            {i<arr.length-1 && <span style={{ color:'#D1D5DB', margin:'0 2px' }}>→</span>}
          </React.Fragment>
        ))}
      </div>

      {/* ── Bookings table ───────────────────────────────── */}
      <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(20,20,19,0.06)', overflow:'hidden' }}>
        <div style={{ overflowX:'auto', WebkitOverflowScrolling:'touch' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, minWidth:700 }}>
            <thead>
              <tr style={{ background:'#FAFAF9', borderBottom:'1px solid rgba(20,20,19,0.08)' }}>
                {(['Ref','Customer', serviceType!=='vehicle'?'Type/Vehicle':'Vehicle', 'Dates','Total','Status','Actions']).map(h=>(
                  <th key={h} style={{ padding:'11px 14px', textAlign:'left', fontWeight:700, fontSize:11, textTransform:'uppercase', color:'#696969', whiteSpace:'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {list.map(b => {
                const isDriverBkg = b._btype === 'driver';
                const isTourBkg   = b._btype === 'tour';
                const ref      = b.ref || b.booking_ref || b.inquiry_ref;
                const customer = b.customer || b.full_name;
                const vehicle  = isTourBkg
                  ? (b.package_title || b.item_name || 'Tour Package')
                  : isDriverBkg
                  ? (b.driver_name ? `Driver: ${b.driver_name}` : 'Driver Booking')
                  : (b.vehicle || (b.brand ? `${b.brand} ${b.model}` : `Vehicle #${b.vehicle_id}`));
                const dates    = isTourBkg
                  ? (b.start_date || '—')
                  : isDriverBkg
                  ? (b.start_date ? `${b.start_date} – ${b.end_date}` : '—')
                  : (b.dates || (b.pickup_date ? `${b.pickup_date} – ${b.return_date}` : '—'));
                const totalAmt = isTourBkg   ? Number(b.package_price || b.total || 0)
                               : isDriverBkg ? Number(b.subtotal || 0)
                               : Number(b.total || 0);
                const isFlagged  = b.content_status === 'flagged';
                const isPending  = b.status === 'pending';
                const isLoading  = actionLoading === b.id;
                return (
                  <tr key={b.id} style={{ borderBottom:'1px solid rgba(20,20,19,0.05)', background: rowBg(b) }}>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ fontWeight:700, color:'#7C3AED', fontFamily:'monospace', fontSize:12 }}>{ref}</div>
                      <div style={{ fontSize:11, color:'#969696', marginTop:2 }}>{new Date(b.created_at||b.created||Date.now()).toLocaleDateString('en-GB')}</div>
                    </td>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ fontWeight:600, color:'#141413' }}>{customer}</div>
                      <div style={{ fontSize:11, color:'#969696' }}>{b.email||''}</div>
                    </td>
                    <td style={{ padding:'11px 14px', color:'#696969' }}>
                      {serviceType !== 'vehicle' && <div style={{ fontSize:10, fontWeight:700, background:isTourBkg?'#FEF3C7':isDriverBkg?'#EFF6FF':'#F0FDF4', color:isTourBkg?'#92400E':isDriverBkg?'#1D4ED8':'#166534', padding:'2px 7px', borderRadius:20, display:'inline-block', marginBottom:3 }}>{isTourBkg?'🎯 Tour':isDriverBkg?'🚘 Driver':'🚗 Vehicle'}</div>}
                      <div>{vehicle}</div>
                    </td>
                    <td style={{ padding:'11px 14px', color:'#696969', whiteSpace:'nowrap' }}>
                      <div>{dates}</div>
                      <div style={{ fontSize:11, color:'#969696' }}>{b.days||''}d{!isDriverBkg && !isTourBkg && ` · ${b.driver_option==='with'?'With driver':'Self-drive'}`}</div>
                    </td>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ fontWeight:700 }}>Rs. {totalAmt.toLocaleString()}</div>
                      {!isDriverBkg && !isTourBkg && <div style={{ fontSize:11, color:'#059669' }}>Adv: Rs. {Number(b.advance_paid||b.advance||0).toLocaleString()}</div>}
                      {isDriverBkg  && b.amount_paid > 0 && <div style={{ fontSize:11, color:'#059669' }}>Paid: Rs. {Number(b.amount_paid||0).toLocaleString()}</div>}
                    </td>
                    <td style={{ padding:'11px 14px' }}>
                      <CmsBadge status={b.status} />
                      {isFlagged && <div style={{ marginTop:4, fontSize:10, fontWeight:700, color:'#DC2626' }}>⚠️ FLAGGED</div>}
                      {b.approved_at && <div style={{ fontSize:10, color:'#059669', marginTop:2 }}>✓ {new Date(b.approved_at).toLocaleDateString('en-GB')}</div>}
                      {b.rejected_at && <div style={{ fontSize:10, color:'#DC2626', marginTop:2 }}>✕ {new Date(b.rejected_at).toLocaleDateString('en-GB')}</div>}
                    </td>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ display:'flex', gap:5, flexWrap:'wrap', alignItems:'center' }}>
                        {/* View — all booking types */}
                        <button onClick={()=>openDetail(b)} title="View full detail"
                          style={{ ...BTN, background:'#F5F5F3', color:'#141413', padding:'5px 9px', fontSize:12 }}>👁 View</button>
                        {/* Approve/Reject — vehicle bookings only */}
                        {isPending && !isDriverBkg && !isTourBkg && (
                          <button onClick={()=>approveBooking(b)} disabled={isLoading} title="Approve booking"
                            style={{ ...BTN, background:'#059669', color:'#fff', padding:'5px 10px', fontSize:11, fontWeight:700, opacity:isLoading?0.6:1 }}>
                            {isLoading ? '…' : '✓ Approve'}
                          </button>
                        )}
                        {isPending && !isDriverBkg && !isTourBkg && (
                          <button onClick={()=>{setRejectModal(b);setRejectReason('');}} disabled={isLoading} title="Reject booking"
                            style={{ ...BTN, background:'#DC2626', color:'#fff', padding:'5px 10px', fontSize:11, fontWeight:700, opacity:isLoading?0.6:1 }}>
                            ✕ Reject
                          </button>
                        )}
                        {/* Edit — vehicle + tour bookings */}
                        {!isDriverBkg && <button onClick={()=>setEditing({...b})} title="Edit booking"
                          style={{ ...BTN, background:'#7C3AED', color:'#fff', padding:'5px 9px', fontSize:12 }}>✏️ Edit</button>}
                        {/* Flag moderation */}
                        {isFlagged && (
                          <button onClick={()=>{setFlagModal(b);setCleanedNote(b.notes||'');}} title="Moderate flagged content"
                            style={{ ...BTN, background:'#FEF3C7', color:'#92400E', border:'1.5px solid #F59E0B', padding:'5px 9px', fontSize:11, fontWeight:700 }}>⚠️ Review</button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
              {list.length===0 && (
                <tr><td colSpan={7} style={{ textAlign:'center', padding:'48px', color:'#969696' }}>
                  No bookings found
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* ══════════════════════════════════════════════════════
          FULL DETAIL MODAL
      ══════════════════════════════════════════════════════ */}
      {detail && (
        <Modal title={`Booking ${detail.ref||detail.booking_ref}`} onClose={()=>{setDetail(null);setDetailDocs([]);}} wide>
          {loadingDetail && <div style={{ textAlign:'center', padding:'20px', color:'#7C3AED' }}>Loading full data…</div>}

          {/* Status banner */}
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:16, flexWrap:'wrap' }}>
            <CmsBadge status={detail.status} />
            {detail.content_status==='flagged' && (
              <span style={{ background:'#FEE2E2', color:'#DC2626', fontWeight:700, fontSize:11, padding:'3px 10px', borderRadius:20 }}>⚠️ CONTACT INFO FLAGGED</span>
            )}
            {detail.content_status==='cleared' && (
              <span style={{ background:'#D1FAE5', color:'#065F46', fontWeight:700, fontSize:11, padding:'3px 10px', borderRadius:20 }}>✓ Content Cleared</span>
            )}
          </div>

          {/* Status timeline */}
          <div style={{ background:'#F5F5F3', borderRadius:10, padding:'12px 16px', marginBottom:16 }}>
            <div style={{ fontWeight:700, fontSize:12, color:'#141413', marginBottom:8, textTransform:'uppercase', letterSpacing:'0.05em' }}>Status Timeline</div>
            <div style={{ display:'flex', gap:16, flexWrap:'wrap' }}>
              <div><div style={{ fontSize:11, color:'#969696' }}>Requested</div><div style={{ fontWeight:600, fontSize:12, color:'#141413' }}>{detail.created_at ? new Date(detail.created_at).toLocaleString('en-GB') : (detail.created||'—')}</div></div>
              {detail.approved_at && <div><div style={{ fontSize:11, color:'#059669' }}>✓ Approved</div><div style={{ fontWeight:600, fontSize:12, color:'#059669' }}>{new Date(detail.approved_at).toLocaleString('en-GB')}</div></div>}
              {detail.rejected_at && <div><div style={{ fontSize:11, color:'#DC2626' }}>✕ Rejected</div><div style={{ fontWeight:600, fontSize:12, color:'#DC2626' }}>{new Date(detail.rejected_at).toLocaleString('en-GB')}</div></div>}
              {detail.rejection_reason && <div><div style={{ fontSize:11, color:'#DC2626' }}>Reason</div><div style={{ fontWeight:600, fontSize:12, color:'#DC2626' }}>{detail.rejection_reason}</div></div>}
            </div>
          </div>

          {/* ── TOUR INQUIRY VIEW ── */}
          {detail._btype === 'tour' && (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))', gap:18 }}>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#7C3AED', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>👤 Customer</div>
                <DR label="Full Name"  value={detail.full_name} />
                <DR label="Email"      value={detail.email} />
                <DR label="WhatsApp"   value={detail.whatsapp} />
              </div>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#059669', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>🎯 Tour Inquiry</div>
                <DR label="Reference"     value={detail.inquiry_ref||detail.booking_ref} />
                <DR label="Package"       value={detail.package_title||detail.package_name||`#${detail.package_id}`} />
                <DR label="Start Date"    value={detail.start_date} />
                <DR label="Participants"  value={detail.pax} />
                <DR label="Package Price" value={detail.package_price ? `Rs. ${Number(detail.package_price).toLocaleString()}` : '—'} />
                <DR label="Submitted"     value={detail.created_at ? new Date(detail.created_at).toLocaleDateString('en-GB') : '—'} />
              </div>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#0066CC', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>📝 Notes</div>
                <div style={{ fontSize:13, color:'#141413', lineHeight:1.6 }}>{detail.notes || <span style={{ color:'#969696' }}>No notes</span>}</div>
              </div>
            </div>
          )}

          {/* ── DRIVER BOOKING VIEW ── */}
          {detail._btype === 'driver' && (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))', gap:18 }}>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#7C3AED', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>👤 Customer</div>
                <DR label="Full Name"  value={detail.full_name} />
                <DR label="Email"      value={detail.email} />
                <DR label="WhatsApp"   value={detail.whatsapp||detail.contact_number} />
              </div>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#E84800', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>🧑‍✈️ Driver & Trip</div>
                <DR label="Driver"        value={detail.assigned_driver_name||detail.driver_name} />
                <DR label="Driver Phone"  value={detail.assigned_driver_phone||detail.driver_phone} />
                <DR label="Start Date"    value={detail.pickup_date||detail.start_date} />
                <DR label="End Date"      value={detail.return_date||detail.end_date} />
                <DR label="Days"          value={detail.days} />
                <DR label="Pickup"        value={detail.pickup_location} />
                <DR label="Arrival Time"  value={detail.start_time} />
              </div>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#059669', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>💰 Financials</div>
                <DR label="Daily Rate"    value={detail.daily_rate ? `Rs. ${Number(detail.daily_rate).toLocaleString()}` : '—'} />
                <DR label="Total"         value={`Rs. ${Number(detail.subtotal||detail.total||0).toLocaleString()}`} highlight="#059669" />
                <DR label="Commission"    value={`${detail.platform_commission_pct||0}%`} />
                <DR label="Driver Payout" value={detail.driver_payout_total ? `Rs. ${Number(detail.driver_payout_total).toLocaleString()}` : '—'} />
                <DR label="Payment"       value={detail.payment_status==='paid' ? '✅ Paid' : '⏳ Unpaid'} />
              </div>
            </div>
          )}

          {/* ── VEHICLE BOOKING VIEW ── */}
          {(!detail._btype || detail._btype === 'vehicle') && (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))', gap:18 }}>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#7C3AED', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>👤 Customer</div>
                <DR label="Full Name"   value={detail.full_name||detail.customer} />
                <DR label="Email"       value={detail.email} />
                <DR label="WhatsApp"    value={detail.whatsapp} />
                <DR label="Nationality" value={detail.nationality} />
              </div>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#059669', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>🚗 Booking</div>
                <DR label="Reference"     value={detail.ref||detail.booking_ref} />
                <DR label="Vehicle"       value={detail.brand ? `${detail.brand} ${detail.model}` : `#${detail.vehicle_id}`} />
                <DR label="Pickup Date"   value={detail.pickup_date} />
                <DR label="Return Date"   value={detail.return_date} />
                <DR label="Days"          value={detail.days} />
                <DR label="Driver Option" value={detail.driver_option==='with'?'With Driver':detail.driver_option==='added'?'Added Driver':'Self-Drive'} />
                <DR label="Passengers"    value={detail.passengers} />
                <DR label="Pickup Loc."   value={detail.pickup_location||detail.pickup} />
                <DR label="Drop Loc."     value={detail.drop_location||detail.drop} />
              </div>
              <div style={{ background:'#FAFAF9', borderRadius:10, padding:'14px 16px' }}>
                <div style={{ fontWeight:700, fontSize:12, color:'#0066CC', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>💰 Financials</div>
                <DR label="Subtotal"      value={`Rs. ${Number(detail.subtotal||0).toLocaleString()}`} />
                <DR label="Driver Cost"   value={`Rs. ${Number(detail.driver_cost||0).toLocaleString()}`} />
                {Number(detail.food_cost||0) > 0 && <DR label="Food Cost" value={`Rs. ${Number(detail.food_cost).toLocaleString()}`} />}
                {Number(detail.accommodation_cost||0) > 0 && <DR label="Accom. Cost" value={`Rs. ${Number(detail.accommodation_cost).toLocaleString()}`} />}
                <DR label="Total"         value={`Rs. ${Number(detail.total||0).toLocaleString()}`} highlight="#059669" />
                <DR label="Advance Paid"  value={`Rs. ${Number(detail.advance_paid||0).toLocaleString()}`} />
                <DR label="Balance Due"   value={`Rs. ${Number(detail.balance_due||0).toLocaleString()}`} highlight="#DC2626" />
                <DR label="Deposit"       value={`Rs. ${Number(detail.deposit_amount||0).toLocaleString()}`} />
              </div>
            </div>
          )}

          {/* Driver assigned */}
          {(detail.driver_name||detail.assigned_driver_id) && (
            <div style={{ background:'#EEF2FF', borderRadius:10, padding:'14px 16px', marginTop:14 }}>
              <div style={{ fontWeight:700, fontSize:12, color:'#4F46E5', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:10 }}>🧑‍✈️ Assigned Driver</div>
              <div style={{ display:'flex', gap:24, flexWrap:'wrap', fontSize:13 }}>
                <span><span style={{ color:'#696969' }}>Name: </span><strong>{detail.driver_name||'—'}</strong></span>
                <span><span style={{ color:'#696969' }}>Phone: </span><strong>{detail.driver_phone||'—'}</strong></span>
                <span><span style={{ color:'#696969' }}>License: </span><strong>{detail.driver_license||'—'}</strong></span>
              </div>
            </div>
          )}

          {/* Notes */}
          <div style={{ marginTop:14 }}>
            <div style={{ fontWeight:700, fontSize:12, color:'#141413', marginBottom:6, display:'flex', alignItems:'center', gap:8 }}>
              Notes
              {detail.content_status==='flagged' && <span style={{ background:'#FEE2E2', color:'#DC2626', fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:20 }}>⚠️ CONTACT INFO DETECTED</span>}
            </div>
            <div style={{ background:'#F5F5F3', borderRadius:8, padding:'12px 14px', fontSize:13, color:'#141413', lineHeight:1.6, minHeight:40 }}>
              {detail.notes||<span style={{ color:'#969696' }}>No notes</span>}
            </div>
          </div>

          {/* Documents */}
          {detailDocs.length > 0 && (
            <div style={{ marginTop:14 }}>
              <div style={{ fontWeight:700, fontSize:12, color:'#141413', marginBottom:8, textTransform:'uppercase', letterSpacing:'0.05em' }}>📎 Documents ({detailDocs.length})</div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {detailDocs.map(doc => (
                  <div key={doc.id} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', background:'#F5F5F3', borderRadius:8, padding:'10px 14px', flexWrap:'wrap', gap:8 }}>
                    <div>
                      <div style={{ fontWeight:600, fontSize:13, color:'#141413' }}>{doc.doc_type?.replace(/_/g,' ').toUpperCase()}</div>
                      <div style={{ fontSize:11, color:'#969696' }}>{doc.file_name||doc.file_path} · {doc.uploaded_at ? new Date(doc.uploaded_at).toLocaleDateString('en-GB') : ''}</div>
                      {doc.admin_note && <div style={{ fontSize:11, color:'#F59E0B', marginTop:2 }}>{doc.admin_note}</div>}
                    </div>
                    <div style={{ display:'flex', gap:6, alignItems:'center' }}>
                      <CmsBadge status={doc.doc_status||'pending'} />
                      <a href={doc.file_path} target="_blank" rel="noreferrer"
                        style={{ ...BTN, background:'#7C3AED', color:'#fff', padding:'5px 10px', fontSize:11, textDecoration:'none' }}>View</a>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
          {!loadingDetail && detailDocs.length===0 && (
            <div style={{ marginTop:12, fontSize:12, color:'#969696' }}>No documents uploaded for this booking.</div>
          )}

          {/* Admin note */}
          {detail.admin_note && (
            <div style={{ marginTop:14, background:'#EEF2FF', borderRadius:8, padding:'10px 14px', fontSize:13 }}>
              <span style={{ fontWeight:700, color:'#4F46E5' }}>Admin Note: </span>{detail.admin_note}
            </div>
          )}

          {/* Quick approve/reject from detail view */}
          {detail.status==='pending' && (
            <div style={{ marginTop:18, display:'flex', gap:10, flexWrap:'wrap' }}>
              <input placeholder="Approval note (optional)" value={approveNote} onChange={e=>setApproveNote(e.target.value)}
                style={{ ...FL, flex:2, minWidth:200 }} />
              <button onClick={()=>approveBooking(detail)} disabled={actionLoading===detail.id}
                style={{ ...BTN, background:'#059669', color:'#fff', padding:'10px 20px', fontWeight:700, flex:1, minWidth:120 }}>
                ✓ Approve
              </button>
              <button onClick={()=>{setRejectModal(detail);setRejectReason('');}}
                style={{ ...BTN, background:'#DC2626', color:'#fff', padding:'10px 20px', fontWeight:700, flex:1, minWidth:120 }}>
                ✕ Reject
              </button>
            </div>
          )}
        </Modal>
      )}

      {/* ══════════════════════════════════════════════════════
          REJECT MODAL
      ══════════════════════════════════════════════════════ */}
      {rejectModal && (
        <Modal title={`Reject Booking ${rejectModal.ref||rejectModal.booking_ref}`} onClose={()=>setRejectModal(null)}>
          <p style={{ color:'#696969', fontSize:14, marginBottom:16 }}>
            You are rejecting booking for <strong>{rejectModal.full_name||rejectModal.customer}</strong>.
            Please provide a reason — this will be logged and displayed to the admin team.
          </p>
          <FieldRow label="Rejection Reason *">
            <textarea style={{ ...FL, minHeight:80, resize:'vertical' }}
              placeholder="e.g. Vehicle no longer available on these dates, documents incomplete…"
              value={rejectReason} onChange={e=>setRejectReason(e.target.value)} />
          </FieldRow>
          <div style={{ display:'flex', gap:10, marginTop:6 }}>
            <button onClick={()=>setRejectModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={rejectBooking} disabled={!rejectReason.trim()}
              style={{ ...BTN, flex:2, background:'#DC2626', color:'#fff', padding:'12px 0', fontSize:14, opacity:rejectReason.trim()?1:0.5 }}>
              ✕ Confirm Rejection
            </button>
          </div>
        </Modal>
      )}

      {/* ══════════════════════════════════════════════════════
          CONTENT MODERATION MODAL
      ══════════════════════════════════════════════════════ */}
      {flagModal && (
        <Modal title={`⚠️ Content Moderation — ${flagModal.ref||flagModal.booking_ref}`} onClose={()=>setFlagModal(null)} wide>
          <div style={{ background:'#FEF3C7', border:'1.5px solid #F59E0B', borderRadius:10, padding:'12px 16px', marginBottom:16, fontSize:13 }}>
            <strong>⚠️ Contact information was detected in this booking's notes.</strong> This violates the platform policy — all communication must go through CeyRide. Edit the notes below to remove the violation, then click Save.
          </div>
          <div style={{ marginBottom:10 }}>
            <div style={{ fontWeight:700, fontSize:12, color:'#DC2626', marginBottom:4 }}>Flagged Types: {(()=>{try{const f=JSON.parse(flagModal.flagged_fields||'{}');return(f.types||[]).join(', ');}catch{return'Contact info';}})()}</div>
          </div>
          <FieldRow label="Cleaned Notes (remove all contact info)">
            <textarea style={{ ...FL, minHeight:100, resize:'vertical', border:'2px solid #F59E0B' }}
              value={cleanedNote} onChange={e=>setCleanedNote(e.target.value)} />
          </FieldRow>
          <div style={{ display:'flex', gap:10, marginTop:6 }}>
            <button onClick={()=>setFlagModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={clearFlag} style={{ ...BTN, flex:2, background:'#059669', color:'#fff', padding:'12px 0', fontSize:14 }}>✓ Save Cleaned Notes & Clear Flag</button>
          </div>
        </Modal>
      )}

      {/* ══════════════════════════════════════════════════════
          EDIT MODAL
      ══════════════════════════════════════════════════════ */}
      {editing && (
        <Modal title={`Edit ${editing._btype==='tour'?'Inquiry':editing._btype==='driver'?'Driver Booking':'Booking'} — ${editing.booking_ref||editing.inquiry_ref||editing.ref}`} onClose={()=>setEditing(null)} wide>
          <div style={{ fontSize:11, background:'#F5F5F3', borderRadius:8, padding:'8px 12px', marginBottom:14, color:'#696969' }}>
            Type: <strong>{editing._btype==='tour'?'Tour Inquiry':editing._btype==='driver'?'Driver Booking':'Vehicle Booking'}</strong>
            &nbsp;·&nbsp; Customer: <strong>{editing.full_name||editing.customer||'—'}</strong>
            &nbsp;·&nbsp; Email: <strong>{editing.email||'—'}</strong>
          </div>

          {/* ── STATUS — all types ── */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:4 }}>
            <FieldRow label="Status">
              <select style={FL} value={editing.status||''} onChange={e=>setE('status',e.target.value)}>
                {(editing._btype === 'tour'
                  ? ['new','contacted','confirmed','cancelled']
                  : ['pending','confirmed','active','completed','cancelled']
                ).map(s=><option key={s} value={s}>{s.charAt(0).toUpperCase()+s.slice(1)}</option>)}
              </select>
            </FieldRow>

            {/* ── VEHICLE BOOKING FIELDS ── */}
            {(!editing._btype || editing._btype === 'vehicle') && (
              <FieldRow label="Assign Driver">
                <select style={FL} value={editing.assigned_driver_id||''} onChange={e=>setE('assigned_driver_id',+e.target.value)}>
                  <option value="">— No driver —</option>
                  {(data.drivers||[]).map(d=><option key={d.id} value={d.id}>{d.name}</option>)}
                </select>
              </FieldRow>
            )}

            {/* ── TOUR INQUIRY FIELDS ── */}
            {editing._btype === 'tour' && (
              <>
                <FieldRow label="Start Date">
                  <input type="date" style={FL} value={editing.start_date||''} onChange={e=>setE('start_date',e.target.value)} />
                </FieldRow>
                <FieldRow label="Participants (pax)">
                  <input type="number" min="1" max="30" style={FL} value={editing.pax||1} onChange={e=>setE('pax',+e.target.value)} />
                </FieldRow>
                <div style={{ gridColumn:'1 / -1', fontSize:11, color:'#969696', padding:'4px 0' }}>
                  Package: <strong>{editing.package_title||editing.package_name||`#${editing.package_id}`}</strong>
                  &nbsp;·&nbsp; Price: <strong>{editing.package_price ? `Rs. ${Number(editing.package_price).toLocaleString()}` : '—'}</strong>
                </div>
              </>
            )}
          </div>

          {/* ── VEHICLE BOOKING EXTRA FIELDS ── */}
          {(!editing._btype || editing._btype === 'vehicle') && (
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:4 }}>
              <FieldRow label="Pickup Location">
                <input style={FL} value={editing.pickup_location||editing.pickup||''} onChange={e=>setE('pickup_location',e.target.value)} />
              </FieldRow>
              <FieldRow label="Drop Location">
                <input style={FL} value={editing.drop_location||editing.drop||''} onChange={e=>setE('drop_location',e.target.value)} />
              </FieldRow>
              <FieldRow label="Pickup Date">
                <input type="date" style={FL} value={editing.pickup_date||''} onChange={e=>setE('pickup_date',e.target.value)} />
              </FieldRow>
              <FieldRow label="Return Date">
                <input type="date" style={FL} value={editing.return_date||''} onChange={e=>setE('return_date',e.target.value)} />
              </FieldRow>
              <FieldRow label="Passengers">
                <input type="number" min="1" max="20" style={FL} value={editing.passengers||1} onChange={e=>setE('passengers',+e.target.value)} />
              </FieldRow>
              <FieldRow label="Nationality">
                <input style={FL} value={editing.nationality||''} onChange={e=>setE('nationality',e.target.value)} />
              </FieldRow>
            </div>
          )}

          {/* ── NOTES — all types ── */}
          <FieldRow label={editing._btype==='tour' ? 'Admin Notes' : 'Notes (visible to customer)'}>
            <textarea style={{ ...FL, minHeight:70, resize:'vertical' }} value={editing.notes||''} onChange={e=>setE('notes',e.target.value)} placeholder="Add notes…" />
          </FieldRow>
          {(!editing._btype || editing._btype === 'vehicle') && (
            <FieldRow label="Admin Note (internal only)">
              <input style={FL} value={editing.admin_note||''} onChange={e=>setE('admin_note',e.target.value)} placeholder="Internal — not visible to customer" />
            </FieldRow>
          )}

          <div style={{ display:'flex', gap:10, marginTop:12 }}>
            <button onClick={()=>setEditing(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={saveBooking} style={{ ...BTN, flex:2, background:'#059669', color:'#fff', padding:'12px 0', fontSize:14, fontWeight:700 }}>✓ Save Changes</button>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ─── AUDIT LOG MODULE ─────────────────────────────────────────
function AuditLogModule({ logs }) {
  const colorMap = { Created:'#059669', Updated:'#0066CC', Deleted:'#DC2626', Approved:'#7C3AED', Deactivated:'#F59E0B', Activated:'#059669' };
  return (
    <div>
      <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:6 }}>Audit Log</h2>
      <p style={{ color:'#969696', fontSize:13, marginBottom:20 }}>Last 50 admin actions</p>
      {logs.length === 0 && <div style={{ textAlign:'center', padding:'48px', color:'#969696' }}>No actions logged yet</div>}
      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        {logs.map(l => (
          <div key={l.id} style={{ background:'#fff', borderRadius:12, padding:'12px 16px', boxShadow:'0 1px 4px rgba(20,20,19,0.06)', display:'flex', gap:12, alignItems:'center', flexWrap:'wrap' }}>
            <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:6, background:`${colorMap[l.action]||'#969696'}18`, color:colorMap[l.action]||'#969696' }}>{l.action}</span>
            <span style={{ fontSize:12, fontWeight:600, color:'#7C3AED' }}>{l.module}</span>
            <span style={{ fontSize:13, color:'#141413', flex:1 }}>{l.detail}</span>
            <span style={{ fontSize:11, color:'#969696', whiteSpace:'nowrap' }}>{l.by} · {l.time}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── GENERIC APPROVAL TABLE ───────────────────────────────────
function ApprovalTable({ title, rows, columns, onApprove, onReject, onView, onImageUpdate }) {
  const [filter, setFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [uploading, setUploading] = React.useState(null);

  const filtered = rows.filter(r => {
    const s = filter==='all'||r.status===filter;
    const q = search.trim().toLowerCase();
    const t = !q||Object.values(r).some(v=>String(v).toLowerCase().includes(q));
    return s&&t;
  });
  const counts = { all:rows.length, pending:rows.filter(r=>r.status==='pending').length, approved:rows.filter(r=>r.status==='approved').length, rejected:rows.filter(r=>r.status==='rejected').length };

  const handleImageUpload = (row) => {
    if (!onImageUpdate) return;
    const el = document.createElement('input');
    el.type = 'file';
    el.accept = 'image/jpeg,image/jpg,image/png,image/webp';
    el.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      if (file.size > 5*1024*1024) { alert('File too large — max 5MB'); return; }
      setUploading(row.id);
      try {
        const fd = new FormData();
        fd.append('image', file);
        fd.append('image_key', `vehicle_${row.id}`);
        const res  = await fetch('api/upload_image.php', { method:'POST', body:fd });
        const json = await res.json();
        if (json.success) {
          onImageUpdate(row.id, json.path + '?t=' + Date.now());
        } else {
          // Fallback: use local reference with cache buster
          onImageUpdate(row.id, `images/vehicles/${file.name}?t=${Date.now()}`);
        }
      } catch {
        onImageUpdate(row.id, `images/vehicles/${file.name}?t=${Date.now()}`);
      }
      setUploading(null);
    };
    el.click();
  };

  return (
    <div>
      <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', marginBottom:18, flexWrap:'wrap', gap:10 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>{title}</h2>
          <p style={{ color:'#969696', fontSize:13 }}>{counts.all} total · <span style={{ color:'#F59E0B', fontWeight:600 }}>{counts.pending} pending</span></p>
        </div>
        <input style={{ ...INP, width:200 }} placeholder="Search…" value={search} onChange={e=>setSearch(e.target.value)} />
      </div>
      <div style={{ display:'flex', gap:7, marginBottom:16, flexWrap:'wrap' }}>
        {['all','pending','approved','rejected'].map(s=>(
          <button key={s} onClick={()=>setFilter(s)} style={{ ...BTN, background:filter===s?'#141413':'#fff', color:filter===s?'#fff':'#696969', border:`1.5px solid ${filter===s?'#141413':'rgba(20,20,19,0.12)'}` }}>
            {s.charAt(0).toUpperCase()+s.slice(1)} ({counts[s]||0})
          </button>
        ))}
      </div>
      <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(20,20,19,0.06)', overflow:'hidden' }}>
        <div style={{ overflowX:'auto', WebkitOverflowScrolling:'touch' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, minWidth:480 }}>
            <thead>
              <tr style={{ background:'#FAFAF9', borderBottom:'1px solid rgba(20,20,19,0.08)' }}>
                {/* Vehicle thumbnail col if images exist */}
                {rows[0]?.img && <th style={{ padding:'11px 14px', width:60 }}></th>}
                {columns.map(c=><th key={c} style={{ padding:'11px 14px', textAlign:'left', fontWeight:700, fontSize:11, textTransform:'uppercase', letterSpacing:'0.05em', color:'#696969', whiteSpace:'nowrap' }}>{c}</th>)}
                <th style={{ padding:'11px 14px', textAlign:'left', fontWeight:700, fontSize:11, textTransform:'uppercase', letterSpacing:'0.05em', color:'#696969' }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r,i) => (
                <tr key={r.id||i} style={{ borderBottom:'1px solid rgba(20,20,19,0.05)' }}>
                  {/* Vehicle thumbnail */}
                  {rows[0]?.img && (
                    <td style={{ padding:'8px 14px' }}>
                      <div style={{ position:'relative', width:48, height:36 }}>
                        <img src={resolveImgUrl(r.img)} alt="" style={{ width:48, height:36, borderRadius:6, objectFit:'cover', display:'block' }} onError={e=>{e.target.style.opacity='.3';}} />
                        {onImageUpdate && (
                          <div onClick={()=>handleImageUpload(r)} title="Replace image" style={{ position:'absolute', inset:0, background:'rgba(0,0,0,0.45)', borderRadius:6, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', opacity:0, transition:'opacity 0.2s', fontSize:14 }}
                            onMouseEnter={e=>e.currentTarget.style.opacity=1}
                            onMouseLeave={e=>e.currentTarget.style.opacity=0}>
                            {uploading===r.id ? '⏳' : '📷'}
                          </div>
                        )}
                      </div>
                    </td>
                  )}
                  {columns.map(c => {
                    const key = c.toLowerCase().replace(/ /g,'_').replace(/[^a-z_]/g,'');
                    const fieldMap = { '#':i+1, name:r.name||r.owner, vehicle:`${r.brand||''} ${r.model||''}`.trim(), status:<CmsBadge status={r.status}/>, date:r.date||r.created, price:r.price?`Rs.${r.price.toLocaleString()}`:'—', license:r.license||r.licenseNumber||r.guideLicenseNo||'—', experience:r.exp||r.experience||'—', daily:r.daily?`Rs.${r.daily.toLocaleString()}`:'—', guide:r.guide||'—', duration:r.duration||'—', ref:r.ref||'—', customer:r.customer||'—', total:r.total?`Rs.${r.total.toLocaleString()}`:'—', email:r.email||'—' };
                    const val = fieldMap[key] ?? r[key] ?? '—';
                    return <td key={c} style={{ padding:'11px 14px', color:'#141413', fontWeight:c==='Name'||c==='Customer'?600:400, whiteSpace:'nowrap' }}>{val}</td>;
                  })}
                  <td style={{ padding:'11px 14px' }}>
                    <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                      {onView && <button onClick={()=>onView(r)} style={{ ...BTN, background:'#F5F5F3', color:'#141413', padding:'5px 10px' }}>View</button>}
                      {r.status==='pending' && onApprove && <button onClick={()=>onApprove(r.id)} style={{ ...BTN, background:'#059669', color:'#fff', padding:'5px 10px' }}>✓</button>}
                      {r.status==='pending' && onReject  && <button onClick={()=>onReject(r.id)}  style={{ ...BTN, background:'#DC2626', color:'#fff', padding:'5px 10px' }}>✕</button>}
                    </div>
                  </td>
                </tr>
              ))}
              {filtered.length===0 && <tr><td colSpan={columns.length+2} style={{ textAlign:'center', padding:'40px', color:'#969696' }}>No records found</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── FINANCE ─────────────────────────────────────────────────
function Finance({ data }) {
  // Combine vehicle, driver, and tour bookings for a unified finance view
  const allBookings = [
    ...(data.bookings      || []).map(b => ({ ...b, _type: 'vehicle' })),
    ...(data.driverBookings|| []).map(b => ({ ...b, _type: 'driver'  })),
    ...(data.tourInquiries || []).map(b => ({ ...b, _type: 'tour', total: b.package_price || 0 })),
  ];
  const conf = allBookings.filter(b => b.status === 'confirmed' || b.status === 'approved' || b.status === 'completed');
  const rev  = conf.reduce((s, b) => s + Number(b.total || 0), 0);
  const comm = Math.round(rev * 0.15);

  // Pending payouts = 85% of balance_due on confirmed bookings (what owners are still owed)
  const pendingPayout = conf.reduce((s, b) => {
    const bal = Number(b.balance_due || 0);
    return s + (bal > 0 ? Math.round(bal * 0.85) : 0);
  }, 0);

  // Last 7 days daily revenue from real booking created_at dates
  const days7   = [];
  const labels7 = [];
  for (let i = 6; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    const key = d.toISOString().slice(0, 10); // 'YYYY-MM-DD'
    labels7.push(d.toLocaleDateString('en-GB', { weekday: 'short' }));
    const dayTotal = conf
      .filter(b => (b.created_at || '').startsWith(key))
      .reduce((s, b) => s + Number(b.total || 0), 0);
    days7.push(dayTotal);
  }
  const hasChartData = days7.some(v => v > 0);

  // ── CSV Export ───────────────────────────────────────────────
  const exportCSV = () => {
    const header = ['Ref','Customer','Type','Total (LKR)','Commission (LKR)','Payout (LKR)','Status','Date'];
    const rows   = conf.map(b => {
      const ref      = b.ref || b.booking_ref || `#${b.id}`;
      const customer = b.customer || b.full_name || '—';
      const total    = Number(b.total || 0);
      return [
        ref, customer,
        b._type === 'driver' ? 'Driver Booking' : 'Vehicle Booking',
        total,
        Math.round(total * 0.15),
        Math.round(total * 0.85),
        b.status,
        (b.created_at || '').slice(0, 10),
      ];
    });
    const csv  = [header, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g,'""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href = url;
    a.download = `ceyride-finance-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20, flexWrap:'wrap', gap:10 }}>
        <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', margin:0 }}>Finance & Revenue</h2>
        <div style={{ display:'flex', gap:8 }}>
          <button onClick={exportCSV} style={{ background:'#059669', color:'#fff', border:'none', borderRadius:10, padding:'9px 16px', fontWeight:700, fontSize:13, cursor:'pointer' }}>⬇ Export CSV</button>
          <button onClick={()=>window.print()} style={{ background:'#7C3AED', color:'#fff', border:'none', borderRadius:10, padding:'9px 16px', fontWeight:700, fontSize:13, cursor:'pointer' }}>🖨 Print / PDF</button>
        </div>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(150px,1fr))', gap:12, marginBottom:24 }}>
        <Stat icon="💰" label="Total Revenue"    value={rev > 0 ? `Rs. ${Math.round(rev).toLocaleString()}` : 'Rs. 0'}               color="#059669" />
        <Stat icon="🏦" label="Commission (15%)" value={comm > 0 ? `Rs. ${Math.round(comm).toLocaleString()}` : 'Rs. 0'}             color="#7C3AED" />
        <Stat icon="📋" label="Confirmed Trips"  value={conf.length}                                                      color="#0066CC" />
        <Stat icon="⏳" label="Pending Payouts"  value={pendingPayout > 0 ? `Rs. ${Math.round(pendingPayout).toLocaleString()}` : 'Rs. 0'} color="#F59E0B" />
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(280px,1fr))', gap:18, marginBottom:20 }}>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)' }}>
          <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:16 }}>Daily Revenue — Last 7 Days (LKR)</div>
          <Bar data={hasChartData ? days7 : [1,1,1,1,1,1,1]} labels={labels7} color="#059669" h={90} />
          {!hasChartData && <div style={{ fontSize:11, color:'#969696', marginTop:6, textAlign:'center' }}>No confirmed bookings in the last 7 days</div>}
        </div>
      </div>
      <div style={{ background:'#fff', borderRadius:14, padding:'20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)' }}>
        <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:14 }}>Confirmed Bookings</div>
        {conf.length === 0 ? (
          <div style={{ textAlign:'center', padding:'32px 0', color:'#969696', fontSize:13 }}>No confirmed bookings yet.</div>
        ) : (
          <div style={{ overflowX:'auto' }}>
            <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, minWidth:580 }}>
              <thead>
                <tr style={{ borderBottom:'1px solid rgba(20,20,19,0.08)' }}>
                  {['Ref','Customer','Type','Total','Commission','Payout'].map(h => (
                    <th key={h} style={{ padding:'9px 12px', textAlign:'left', fontWeight:700, fontSize:11, textTransform:'uppercase', color:'#969696' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {conf.map(b => {
                  const ref      = b.ref || b.booking_ref || `#${b.id}`;
                  const customer = b.customer || b.full_name || '—';
                  const total    = Number(b.total || 0);
                  return (
                    <tr key={`${b._type}-${b.id}`} style={{ borderBottom:'1px solid rgba(20,20,19,0.05)' }}>
                      <td style={{ padding:'10px 12px', fontWeight:700, color:'#7C3AED', fontFamily:'monospace', fontSize:12 }}>{ref}</td>
                      <td style={{ padding:'10px 12px', fontWeight:600, color:'#141413' }}>{customer}</td>
                      <td style={{ padding:'10px 12px', color:'#969696', fontSize:12 }}>{b._type === 'driver' ? '🚘 Driver' : '🚗 Vehicle'}</td>
                      <td style={{ padding:'10px 12px', fontWeight:700 }}>Rs. {total.toLocaleString()}</td>
                      <td style={{ padding:'10px 12px', color:'#7C3AED', fontWeight:600 }}>Rs. {Math.round(total * 0.15).toLocaleString()}</td>
                      <td style={{ padding:'10px 12px', color:'#059669', fontWeight:600 }}>Rs. {Math.round(total * 0.85).toLocaleString()}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── UI IMAGE MANAGER ────────────────────────────────────────
function ImageManager({ data, setData }) {
  const [section, setSection]     = React.useState('All');
  const [preview, setPreview]     = React.useState(null);
  const [editing, setEditing]     = React.useState(null);
  const [newPath, setNewPath]     = React.useState('');
  const [saved, setSaved]         = React.useState(false);
  const [uploading, setUploading] = React.useState(null);
  const [uploadErr, setUploadErr] = React.useState('');

  const sections = ['All', ...new Set(data.uiImages.map(i=>i.section))];
  const list = section==='All' ? data.uiImages : data.uiImages.filter(i=>i.section===section);

  const saveImagePath = async (id, path) => {
    // Update local state immediately for fast UI feedback
    setData(d=>({ ...d, uiImages: d.uiImages.map(img=>img.id===id?{...img,src:path}:img) }));
    setEditing(null); setNewPath('');
    // Persist to homepage_config table in DB so user portal reflects the change
    const img = data.uiImages.find(i => i.id === id);
    if (img && img.key) {
      try {
        const s = JSON.parse(localStorage.getItem('cr_admin') || '{}');
        await fetch('api/admin.php?action=save_homepage_config', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', ...(s.token ? { 'Authorization': `Bearer ${s.token}` } : {}) },
          body: JSON.stringify({ configs: { [img.key]: path } }),
        });
      } catch { /* fail silently — local state already updated */ }
    }
    setSaved(true); setTimeout(()=>setSaved(false), 3000);
  };

  const uploadFile = (img) => {
    setUploadErr('');
    const el = document.createElement('input');
    el.type = 'file';
    el.accept = 'image/jpeg,image/jpg,image/png,image/webp,.jpg,.jpeg,.png,.webp';
    el.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      if (file.size > 5*1024*1024) { setUploadErr('File too large — max 5MB.'); return; }
      const allowed = ['image/jpeg','image/jpg','image/png','image/webp'];
      if (!allowed.includes(file.type)) { setUploadErr(`"${file.type}" not supported. Use JPG, PNG, or WebP.`); return; }
      setUploading(img.id);
      try {
        const fd = new FormData();
        fd.append('image', file);
        fd.append('image_key', img.key);
        fd.append('image_dir', 'ui'); // UI Images manager always saves to images/ui/
        const s   = JSON.parse(localStorage.getItem('cr_admin') || '{}');
        if (s.token) fd.append('_token', s.token); // fallback for Hostinger multipart header stripping
        const res = await fetch('api/upload_image.php', {
          method:  'POST',
          body:    fd,
          headers: s.token ? { 'Authorization': `Bearer ${s.token}` } : {},
        });
        const json = await res.json();
        if (json.success) {
          saveImagePath(img.id, json.path);
        } else {
          setUploadErr(json.error || 'Upload failed.');
        }
      } catch {
        // PHP API not available — update path reference only
        saveImagePath(img.id, `images/ui/${file.name}`);
        setUploadErr('Note: Path reference updated. Copy the file to images/ui/ folder on your server.');
      }
      setUploading(null);
    };
    el.click();
  };

  return (
    <div>
      <div style={{ marginBottom:14 }}>
        <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Website UI Image Manager</h2>
        <p style={{ color:'#969696', fontSize:13 }}>Replace any website content image — no code editing required.</p>
      </div>
      <div style={{ background:'#EFF6FF', border:'1px solid #BFDBFE', borderRadius:12, padding:'11px 14px', marginBottom:14, fontSize:13, color:'#1E40AF', display:'flex', gap:8, alignItems:'flex-start', flexWrap:'wrap' }}>
        <span style={{ flexShrink:0 }}>ℹ️</span>
        <div>
          <strong>Supported:</strong> JPG, JPEG, PNG, WebP &nbsp;·&nbsp; <strong>Max size:</strong> 5MB
          <br />After uploading, the image is saved to <code style={{ background:'#DBEAFE', padding:'1px 5px', borderRadius:4, fontSize:11 }}>public_html/devstaging/images/ui/</code> on your Hostinger server automatically.
        </div>
      </div>
      {saved    && <div style={{ background:'#D1FAE5', border:'1px solid #6EE7B7', borderRadius:10, padding:'10px 14px', marginBottom:12, fontSize:13, color:'#065F46', fontWeight:600 }}>✅ Image path updated!</div>}
      {uploadErr && <div style={{ background:'#FEF3C7', border:'1px solid #FDE68A', borderRadius:10, padding:'10px 14px', marginBottom:12, fontSize:13, color:'#92400E', display:'flex', justifyContent:'space-between' }}>
        ⚠️ {uploadErr} <span onClick={()=>setUploadErr('')} style={{ cursor:'pointer', fontWeight:700, marginLeft:8 }}>×</span>
      </div>}
      <div style={{ display:'flex', gap:7, marginBottom:18, flexWrap:'wrap' }}>
        {sections.map(s=>(
          <button key={s} onClick={()=>setSection(s)} style={{ ...BTN, background:section===s?'#141413':'#fff', color:section===s?'#fff':'#696969', border:`1.5px solid ${section===s?'#141413':'rgba(20,20,19,0.12)'}` }}>{s}</button>
        ))}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(240px,1fr))', gap:16 }}>
        {list.map(img=>(
          <div key={img.id} style={{ background:'#fff', borderRadius:14, overflow:'hidden', boxShadow:'0 2px 8px rgba(20,20,19,0.06)', border:'1.5px solid rgba(20,20,19,0.06)', opacity:uploading===img.id?.6:1 }}>
            <div style={{ height:150, overflow:'hidden', position:'relative', background:'#F5F5F3' }}>
              <img src={resolveImgUrl(img.src)} alt={img.label} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>{e.target.style.display='none';}} />
              {uploading===img.id && <div style={{ position:'absolute', inset:0, background:'rgba(20,20,19,0.55)', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:700, fontSize:13 }}>⏳ Uploading…</div>}
              <div style={{ position:'absolute', inset:0, background:'linear-gradient(to bottom,transparent 55%,rgba(20,20,19,0.7))', display:'flex', alignItems:'flex-end', padding:10 }}>
                <span style={{ fontSize:11, fontWeight:700, color:'#fff', background:'rgba(0,0,0,0.5)', padding:'2px 8px', borderRadius:20 }}>{img.section}</span>
              </div>
              <button onClick={()=>setPreview(img)} style={{ position:'absolute', top:8, right:8, background:'rgba(255,255,255,0.92)', border:'none', borderRadius:8, padding:'4px 8px', fontSize:11, fontWeight:700, cursor:'pointer' }}>🔍</button>
            </div>
            <div style={{ padding:'12px 14px' }}>
              <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:2 }}>{img.label}</div>
              <div style={{ fontSize:10, color:'#969696', fontFamily:'monospace', marginBottom:4, background:'#F5F5F3', padding:'2px 6px', borderRadius:4, display:'inline-block' }}>{img.key}</div>
              <div style={{ fontSize:11, color:'#969696', marginBottom:10 }}>{img.used}</div>
              {editing===img.id ? (
                <div>
                  <input style={{ ...INP, fontSize:12, marginBottom:8 }} value={newPath} onChange={e=>setNewPath(e.target.value)} placeholder="images/ui/myimage.png" />
                  <div style={{ display:'flex', gap:6 }}>
                    <button onClick={()=>saveImagePath(img.id, newPath)} style={{ ...BTN, flex:1, background:'#059669', color:'#fff', padding:'7px 0', fontSize:12 }}>Save</button>
                    <button onClick={()=>{setEditing(null);setNewPath('');}} style={{ ...BTN, background:'#F5F5F3', color:'#141413', padding:'7px 10px', fontSize:12 }}>Cancel</button>
                  </div>
                </div>
              ) : (
                <div style={{ display:'flex', gap:6 }}>
                  <button onClick={()=>uploadFile(img)} disabled={!!uploading} style={{ ...BTN, flex:1, background:'#7C3AED', color:'#fff', padding:'8px 0', fontSize:12, opacity:uploading?.6:1 }}>
                    📤 Upload PNG/JPG
                  </button>
                  <button onClick={()=>{setEditing(img.id);setNewPath(img.src);}} style={{ ...BTN, background:'#F5F5F3', color:'#141413', padding:'8px 10px', fontSize:12 }}>✏️</button>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
      {preview && (
        <Modal title={preview.label} onClose={()=>setPreview(null)} wide>
          <div style={{ background:'#F5F5F3', borderRadius:12, overflow:'hidden', marginBottom:14, minHeight:100, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <img src={resolveImgUrl(preview.src)} alt={preview.label} style={{ maxWidth:'100%', maxHeight:280, objectFit:'contain', display:'block' }} onError={e=>{e.target.style.display='none';}} />
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, fontSize:13, marginBottom:16 }}>
            {[['Section',preview.section],['Key',preview.key],['Used in',preview.used],['Path',preview.src]].map(([k,v])=>(
              <div key={k} style={{ background:'#FBF8F5', borderRadius:8, padding:'10px 12px' }}>
                <div style={{ fontWeight:700, color:'#969696', fontSize:11, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:3 }}>{k}</div>
                <div style={{ color:'#141413', fontFamily:k==='Key'||k==='Path'?'monospace':'inherit', fontSize:11, wordBreak:'break-all' }}>{v}</div>
              </div>
            ))}
          </div>
          <button onClick={()=>{uploadFile(preview);setPreview(null);}} style={{ ...BTN, width:'100%', padding:'12px 0', background:'#7C3AED', color:'#fff', fontSize:14 }}>
            📤 Replace This Image (PNG / JPG / WebP)
          </button>
        </Modal>
      )}
    </div>
  );
}

// ─── NOTIFICATIONS ───────────────────────────────────────────
function Notifs({ data, setData }) {
  const markAll = () => setData(d=>({...d, notifications:d.notifications.map(n=>({...n,read:true}))}));
  const mark    = id => setData(d=>({...d, notifications:d.notifications.map(n=>n.id===id?{...n,read:true}:n)}));
  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>Notifications</h2>
          <p style={{ color:'#969696', fontSize:13 }}>{data.notifications.filter(n=>!n.read).length} unread</p>
        </div>
        <button onClick={markAll} style={{ ...BTN, background:'#F5F5F3', color:'#141413' }}>Mark all read</button>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {data.notifications.map(n=>(
          <div key={n.id} style={{ background:n.read?'#fff':'#7C3AED08', borderRadius:14, padding:'14px 16px', boxShadow:'0 2px 6px rgba(20,20,19,0.05)', display:'flex', gap:12, alignItems:'flex-start', border:`1.5px solid ${n.read?'rgba(20,20,19,0.06)':'#7C3AED30'}` }}>
            <div style={{ width:40, height:40, borderRadius:10, background:'#7C3AED18', display:'flex', alignItems:'center', justifyContent:'center', fontSize:18, flexShrink:0 }}>{n.icon}</div>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:n.read?600:800, fontSize:14, color:'#141413', marginBottom:2 }}>{n.title}</div>
              <div style={{ fontSize:13, color:'#696969' }}>{n.body}</div>
              <div style={{ fontSize:11, color:'#969696', marginTop:5 }}>{n.time}</div>
            </div>
            {!n.read && <button onClick={()=>mark(n.id)} style={{ ...BTN, padding:'5px 10px', background:'#7C3AED', color:'#fff', fontSize:11, flexShrink:0 }}>Read</button>}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── CONTENT MANAGER ─────────────────────────────────────────
// ── FIXED: Content() now persists to & loads from homepage_config via DB ──
// Root cause was: save() was a pure UI no-op — no API call was made.
function Content() {
  // Default copy shown while DB load is in flight (or if DB unreachable)
  const DEFAULTS = {
    hero_headline: 'Your Perfect Ride, Anywhere in Sri Lanka',
    hero_sub:      '200+ verified vehicles. Professional drivers. Island-wide coverage.',
    about:         'CeyRide was founded in 2024 by Sri Lankan technology professionals who saw a broken rental market.',
    contact:       'Reach us via WhatsApp (+94 77 000 0000) or email (info@ceyride.com).',
    terms:         'By using CeyRide, you agree to these Terms in full.',
    privacy:       'CeyRide collects name, email, phone, NIC/passport, and payment information.',
    faqs:          'How do I book? Browse vehicles, select your preferred vehicle, choose dates, then complete the booking form.',
  };

  const [blocks,   setBlocks]   = React.useState(DEFAULTS);
  const [active,   setActive]   = React.useState('hero_headline');
  const [saved,    setSaved]    = React.useState(false);
  const [saveErr,  setSaveErr]  = React.useState('');
  const [saving,   setSaving]   = React.useState(false);
  const [loading,  setLoading]  = React.useState(true);

  const tabs = [
    ['hero_headline','Hero Headline'],['hero_sub','Hero Subtitle'],
    ['about','About Us'],['contact','Contact'],
    ['terms','Terms'],['privacy','Privacy'],['faqs','FAQs'],
  ];

  // ── Load existing content from DB on mount ──────────────────
  React.useEffect(() => {
    const adminToken = (() => {
      try { return JSON.parse(localStorage.getItem('cr_admin') || '{}').token || ''; } catch { return ''; }
    })();
    fetch('api/admin.php?action=get_homepage_config', {
      headers: adminToken ? { 'Authorization': `Bearer ${adminToken}` } : {},
    })
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(json => {
        if (json && typeof json.config === 'object') {
          // Merge DB values over defaults — only overwrite keys that exist in our tab list
          const merged = { ...DEFAULTS };
          tabs.forEach(([k]) => { if (json.config[k] !== undefined && json.config[k] !== '') merged[k] = json.config[k]; });
          setBlocks(merged);
        }
      })
      .catch(() => {/* keep defaults */})
      .finally(() => setLoading(false));
  }, []);

  // ── Persist all blocks (or just the active tab) to DB ───────
  const save = async () => {
    if (saving) return;
    setSaving(true);
    setSaveErr('');
    const adminToken = (() => {
      try { return JSON.parse(localStorage.getItem('cr_admin') || '{}').token || ''; } catch { return ''; }
    })();
    try {
      const res  = await fetch('api/admin.php?action=save_homepage_config', {
        method:  'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(adminToken ? { 'Authorization': `Bearer ${adminToken}` } : {}),
        },
        // Send ALL content blocks so DB stays in full sync, not just active tab
        body: JSON.stringify({ configs: blocks }),
      });
      const json = await res.json();
      if (!res.ok || json.error) throw new Error(json.error || 'Save failed');
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      setSaveErr(err.message || 'Could not reach server — check your Hostinger deployment and config.php credentials.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:6 }}>Content Manager</h2>
      <p style={{ color:'#969696', fontSize:13, marginBottom:4 }}>
        Edit website text content — changes are saved to the database and reflected on the live site immediately.
      </p>
      <div style={{ background:'#EFF6FF', border:'1px solid #BFDBFE', borderRadius:10, padding:'9px 13px', marginBottom:18, fontSize:12, color:'#1E40AF' }}>
        ℹ️ <strong>Hero Headline</strong> and <strong>Hero Subtitle</strong> update the homepage hero section.
        All other tabs update their respective pages. Click <strong>Save Content</strong> to persist to DB.
      </div>

      {saved   && <div style={{ background:'#D1FAE5', borderRadius:10, padding:'10px 14px', marginBottom:14, fontSize:13, color:'#065F46', fontWeight:600 }}>✅ Content saved to database — frontend will reflect changes on next page load.</div>}
      {saveErr && <div style={{ background:'#FEE2E2', borderRadius:10, padding:'10px 14px', marginBottom:14, fontSize:13, color:'#DC2626' }}>❌ {saveErr}</div>}
      {loading && <div style={{ background:'#FEF3C7', borderRadius:10, padding:'10px 14px', marginBottom:14, fontSize:13, color:'#92400E' }}>⏳ Loading saved content from database…</div>}

      <div style={{ display:'flex', gap:7, marginBottom:18, flexWrap:'wrap' }}>
        {tabs.map(([k,l]) => (
          <button key={k} onClick={() => setActive(k)} style={{ ...BTN, background:active===k?'#141413':'#fff', color:active===k?'#fff':'#696969', border:`1.5px solid ${active===k?'#141413':'rgba(20,20,19,0.12)'}` }}>{l}</button>
        ))}
      </div>

      <div style={{ background:'#fff', borderRadius:14, padding:'20px', boxShadow:'0 2px 8px rgba(20,20,19,0.06)' }}>
        <div style={{ fontWeight:700, fontSize:14, color:'#141413', marginBottom:4 }}>
          Editing: {tabs.find(t => t[0] === active)?.[1]}
        </div>
        <div style={{ fontSize:12, color:'#969696', marginBottom:12 }}>
          Key: <code style={{ background:'#F5F5F3', padding:'1px 6px', borderRadius:4 }}>{active}</code>
          {' '}— used as <code style={{ background:'#F5F5F3', padding:'1px 6px', borderRadius:4 }}>siteConfig.{active}</code> on frontend
        </div>
        <textarea
          value={blocks[active] || ''}
          onChange={e => setBlocks(b => ({ ...b, [active]: e.target.value }))}
          style={{ ...INP, minHeight:180, resize:'vertical', lineHeight:1.7 }}
          placeholder={`Enter ${tabs.find(t=>t[0]===active)?.[1] || active} content…`}
        />
        <div style={{ display:'flex', gap:10, marginTop:12, alignItems:'center', flexWrap:'wrap' }}>
          <button
            onClick={save}
            disabled={saving}
            style={{ ...BTN, background:'#7C3AED', color:'#fff', padding:'11px 24px', fontSize:14, opacity:saving?0.65:1 }}
          >
            {saving ? '⏳ Saving…' : '💾 Save Content'}
          </button>
          <span style={{ fontSize:12, color:'#969696' }}>
            Saves all tabs to DB. Frontend reads on next load.
          </span>
        </div>
      </div>
    </div>
  );
}

// ─── USERS ───────────────────────────────────────────────────
function Users({ data, setData }) {
  const [search,      setSearch]      = React.useState('');
  const [roleFilter,  setRoleFilter]  = React.useState('all');
  const [statusFilt,  setStatusFilt]  = React.useState('all');
  const [viewUser,    setViewUser]    = React.useState(null);   // user object for detail modal
  const [viewDetail,  setViewDetail]  = React.useState(null);   // full detail from API
  const [delConf,     setDelConf]     = React.useState(null);   // user id to delete
  const [loading,     setLoading]     = React.useState(false);
  const [actionMsg,   setActionMsg]   = React.useState('');
  // Create user modal state
  const [createOpen,  setCreateOpen]  = React.useState(false);
  const [createForm,  setCreateForm]  = React.useState({ name:'', email:'', password:'', role:'renter', phone:'' });
  const [createErr,   setCreateErr]   = React.useState('');
  const [createLoading, setCreateLoading] = React.useState(false);
  // Role change modal
  const [roleModal,   setRoleModal]   = React.useState(null);  // { user, newRole }
  const setCF = (k,v) => setCreateForm(f => ({ ...f, [k]: v }));

  const authHdr = () => {
    try {
      const s = JSON.parse(localStorage.getItem('cr_admin') || '{}');
      return s.token ? { 'Authorization': `Bearer ${s.token}` } : {};
    } catch { return {}; }
  };

  // Reload users from API
  const reloadUsers = async () => {
    try {
      const res  = await fetch('api/admin.php?action=get_users', { headers: authHdr() });
      const json = await res.json();
      if (json.users) setData(d => ({ ...d, users: json.users }));
    } catch {}
  };

  // Open user detail modal — fetches full record including bookings
  const openDetail = async (u) => {
    setViewUser(u);
    setViewDetail(null);
    setActionMsg('');
    try {
      const res  = await fetch(`api/admin.php?action=get_user_detail&user_id=${u.id}`, { headers: authHdr() });
      const json = await res.json();
      if (json.user) setViewDetail(json.user);
    } catch { setViewDetail(u); }
  };

  // Toggle active/blocked
  const toggleStatus = async (u) => {
    const newActive = u.is_active === 1 ? 0 : 1;
    try {
      const res  = await fetch('api/admin.php?action=update_user_status', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', ...authHdr() },
        body:    JSON.stringify({ action: 'update_user_status', user_id: u.id, is_active: newActive }),
      });
      const json = await res.json();
      if (json.success) {
        setData(d => ({ ...d, users: d.users.map(x => x.id === u.id ? { ...x, is_active: newActive, status: newActive ? 'active' : 'blocked' } : x) }));
        if (viewDetail && viewDetail.id === u.id) setViewDetail(vd => ({ ...vd, is_active: newActive }));
        setActionMsg(newActive ? '✅ User activated.' : '✅ User blocked.');
      } else { setActionMsg('❌ ' + (json.error || 'Failed')); }
    } catch { setActionMsg('❌ Network error'); }
  };

  // Delete user with confirmation
  const deleteUser = async (id) => {
    setLoading(true);
    try {
      const res  = await fetch('api/admin.php?action=delete_user', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', ...authHdr() },
        body:    JSON.stringify({ action: 'delete_user', user_id: id }),
      });
      const json = await res.json();
      if (json.success) {
        setData(d => ({ ...d, users: d.users.filter(u => u.id !== id) }));
        setDelConf(null);
        setViewUser(null);
        setViewDetail(null);
        setActionMsg('✅ User deleted.');
      } else { setActionMsg('❌ ' + (json.error || 'Delete failed')); setDelConf(null); }
    } catch { setActionMsg('❌ Network error'); setDelConf(null); }
    setLoading(false);
  };

  // Create user from CMS
  const createUser = async () => {
    setCreateErr('');
    if (!createForm.name || !createForm.email || !createForm.password) {
      setCreateErr('Name, email, and password are required.'); return;
    }
    if (createForm.password.length < 8) {
      setCreateErr('Password must be at least 8 characters.'); return;
    }
    setCreateLoading(true);
    try {
      const res  = await fetch('api/admin.php?action=create_user', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', ...authHdr() },
        body:    JSON.stringify(createForm),
      });
      const json = await res.json();
      if (json.success) {
        setCreateOpen(false);
        setCreateForm({ name:'', email:'', password:'', role:'renter', phone:'' });
        setActionMsg('✅ User created successfully.');
        await reloadUsers();
      } else {
        setCreateErr(json.error || 'Failed to create user.');
      }
    } catch { setCreateErr('Network error. Please try again.'); }
    setCreateLoading(false);
  };

  // Update user role
  const updateRole = async (userId, newRole) => {
    try {
      const res  = await fetch('api/admin.php?action=update_user_role', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', ...authHdr() },
        body:    JSON.stringify({ user_id: userId, role: newRole }),
      });
      const json = await res.json();
      if (json.success) {
        setData(d => ({ ...d, users: d.users.map(u => u.id === userId ? { ...u, role: newRole } : u) }));
        setRoleModal(null);
        setActionMsg('✅ Role updated.');
      } else { setActionMsg('❌ ' + (json.error || 'Role update failed.')); }
    } catch { setActionMsg('❌ Network error'); }
  };

  const ROLE_COLORS = {
    renter:      { bg: '#E8480018', color: '#E84800' },
    owner:       { bg: '#7C3AED18', color: '#7C3AED' },
    admin:       { bg: '#0066CC18', color: '#0066CC' },
    super_admin: { bg: '#14141318', color: '#141413' },
  };

  const filteredUsers = (data.users || []).filter(u => {
    const q = search.toLowerCase();
    const matchSearch = !q || (u.name||'').toLowerCase().includes(q) || (u.email||'').toLowerCase().includes(q);
    const matchRole   = roleFilter === 'all' || u.role === roleFilter;
    const uStatus     = (u.is_active !== undefined ? (u.is_active ? 'active' : 'blocked') : u.status) || 'active';
    const matchStatus = statusFilt === 'all' || uStatus === statusFilt;
    return matchSearch && matchRole && matchStatus;
  });

  const fmtDate = d => d ? new Date(d).toLocaleDateString('en-GB', { day:'numeric', month:'short', year:'numeric' }) : '—';

  return (
    <div>
      {/* Header */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18, flexWrap:'wrap', gap:12 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:20, color:'#141413', marginBottom:3 }}>User Management</h2>
          <p style={{ color:'#969696', fontSize:13 }}>
            {(data.users||[]).length} total ·{' '}
            {(data.users||[]).filter(u=>u.is_active!==0&&u.status!=='blocked').length} active ·{' '}
            {(data.users||[]).filter(u=>u.is_active===0||u.status==='blocked').length} blocked
          </p>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <CmsSearchBar value={search} onChange={setSearch} placeholder="Search name or email…" />
          <button onClick={()=>{setCreateOpen(true);setCreateErr('');}} style={{ ...BTN, background:'#059669', color:'#fff', padding:'10px 16px', fontWeight:700 }}>+ Create User</button>
          <button onClick={reloadUsers} style={{ ...BTN, background:'#141413', color:'#fff', padding:'10px 14px' }}>↻ Refresh</button>
        </div>
      </div>

      {/* Filters */}
      <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:18 }}>
        <div style={{ display:'flex', gap:6 }}>
          {['all','renter','owner','admin'].map(r => (
            <button key={r} onClick={()=>setRoleFilter(r)} style={{ ...BTN, fontSize:12, padding:'7px 12px', background:roleFilter===r?'#141413':'#fff', color:roleFilter===r?'#fff':'#696969', border:`1.5px solid ${roleFilter===r?'#141413':'rgba(20,20,19,0.12)'}` }}>
              {r==='all'?'All Roles':r.charAt(0).toUpperCase()+r.slice(1)}
            </button>
          ))}
        </div>
        <div style={{ display:'flex', gap:6 }}>
          {['all','active','blocked'].map(s => (
            <button key={s} onClick={()=>setStatusFilt(s)} style={{ ...BTN, fontSize:12, padding:'7px 12px', background:statusFilt===s?(s==='blocked'?'#DC2626':'#059669'):'#fff', color:statusFilt===s?'#fff':'#696969', border:`1.5px solid ${statusFilt===s?(s==='blocked'?'#DC2626':'#059669'):'rgba(20,20,19,0.12)'}` }}>
              {s==='all'?'All Status':s.charAt(0).toUpperCase()+s.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {actionMsg && (
        <div style={{ background: actionMsg.startsWith('✅') ? '#D1FAE5' : '#FEE2E2', border:`1px solid ${actionMsg.startsWith('✅')?'#6EE7B7':'#FECACA'}`, borderRadius:10, padding:'10px 14px', marginBottom:14, fontSize:13, color: actionMsg.startsWith('✅') ? '#065F46':'#DC2626' }}>
          {actionMsg}
        </div>
      )}

      {/* User Table */}
      <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(20,20,19,0.06)', overflow:'hidden' }}>
        <div style={{ overflowX:'auto' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, minWidth:600 }}>
            <thead>
              <tr style={{ background:'#FAFAF9', borderBottom:'1px solid rgba(20,20,19,0.08)' }}>
                {['User','Email','Role','Bookings','Joined','Status','Actions'].map(h => (
                  <th key={h} style={{ padding:'11px 14px', textAlign:'left', fontWeight:700, fontSize:11, textTransform:'uppercase', color:'#696969', whiteSpace:'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filteredUsers.map((u, i) => {
                const rc = ROLE_COLORS[u.role] || { bg:'#F3F4F6', color:'#374151' };
                const uActive = u.is_active !== 0 && u.status !== 'blocked';
                return (
                  <tr key={u.id} style={{ borderBottom:'1px solid rgba(20,20,19,0.05)', background: i%2===0 ? '#fff' : '#FAFAF9' }}>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ display:'flex', alignItems:'center', gap:9 }}>
                        <div style={{ width:34, height:34, borderRadius:'50%', background:rc.bg, border:`2px solid ${rc.color}`, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:14, color:rc.color, flexShrink:0 }}>
                          {(u.name||'?')[0].toUpperCase()}
                        </div>
                        <div style={{ fontWeight:600, color:'#141413', whiteSpace:'nowrap' }}>{u.name || '—'}</div>
                      </div>
                    </td>
                    <td style={{ padding:'11px 14px', color:'#696969', maxWidth:180, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{u.email}</td>
                    <td style={{ padding:'11px 14px' }}>
                      <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:999, background:rc.bg, color:rc.color }}>{u.role}</span>
                    </td>
                    <td style={{ padding:'11px 14px', color:'#696969', textAlign:'center' }}>{u.booking_count || 0}</td>
                    <td style={{ padding:'11px 14px', color:'#969696', whiteSpace:'nowrap' }}>{fmtDate(u.created_at || u.joined)}</td>
                    <td style={{ padding:'11px 14px' }}><CmsBadge status={uActive ? 'active' : 'blocked'} /></td>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ display:'flex', gap:5 }}>
                        <button onClick={()=>openDetail(u)} title="View full profile" style={{ ...BTN, padding:'5px 9px', background:'#EFF6FF', color:'#0066CC', fontSize:11 }}>👁 View</button>
                        <button onClick={()=>setRoleModal({ user: u, newRole: u.role })} title="Change role" style={{ ...BTN, padding:'5px 9px', background:'#F5F5F3', color:'#141413', fontSize:11 }}>🔑 Role</button>
                        <button onClick={()=>toggleStatus(u)} title={uActive?'Block user':'Unblock user'} style={{ ...BTN, padding:'5px 9px', background:uActive?'#FEF3C7':'#D1FAE5', color:uActive?'#92400E':'#065F46', fontSize:11 }}>
                          {uActive ? '🚫 Block' : '✅ Unblock'}
                        </button>
                        <button onClick={()=>setDelConf(u.id)} title="Delete user permanently" style={{ ...BTN, padding:'5px 9px', background:'#FEE2E2', color:'#DC2626', fontSize:11 }}>🗑</button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {filteredUsers.length === 0 && (
                <tr><td colSpan={7} style={{ textAlign:'center', padding:'48px', color:'#969696' }}>No users found</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* ── User Detail Modal ── */}
      {viewUser && (
        <Modal title={`User Profile — ${viewUser.name}`} onClose={()=>{setViewUser(null);setViewDetail(null);setActionMsg('');}} wide>
          {!viewDetail ? (
            <div style={{ textAlign:'center', padding:'32px 0', color:'#969696' }}>⏳ Loading full profile…</div>
          ) : (
            <div>
              {/* Profile header */}
              <div style={{ display:'flex', alignItems:'center', gap:14, marginBottom:20, padding:'16px', background:'#FAFAF9', borderRadius:12 }}>
                {(() => { const rc = ROLE_COLORS[viewDetail.role]||{bg:'#F3F4F6',color:'#374151'}; return (
                  <div style={{ width:52, height:52, borderRadius:'50%', background:rc.bg, border:`2px solid ${rc.color}`, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:22, color:rc.color, flexShrink:0 }}>
                    {(viewDetail.name||'?')[0].toUpperCase()}
                  </div>
                ); })()}
                <div>
                  <div style={{ fontWeight:700, fontSize:16, color:'#141413' }}>{viewDetail.name}</div>
                  <div style={{ fontSize:12, color:'#969696' }}>{viewDetail.email}</div>
                  <div style={{ display:'flex', gap:6, marginTop:6 }}>
                    {(() => { const rc=ROLE_COLORS[viewDetail.role]||{bg:'#F3F4F6',color:'#374151'}; return <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:999, background:rc.bg, color:rc.color }}>{viewDetail.role}</span>; })()}
                    <CmsBadge status={viewDetail.is_active !== 0 ? 'active' : 'blocked'} />
                    {viewDetail.auth_provider && <span style={{ fontSize:11, fontWeight:600, padding:'2px 8px', borderRadius:999, background:'#F3F4F6', color:'#374151' }}>{viewDetail.auth_provider}</span>}
                  </div>
                </div>
              </div>

              {/* Detail rows */}
              <div style={{ marginBottom:20 }}>
                {[
                  ['ID',            '#' + viewDetail.id],
                  ['Phone',         viewDetail.phone    || '—'],
                  ['WhatsApp',      viewDetail.whatsapp || '—'],
                  ['Auth Provider', viewDetail.auth_provider || 'local'],
                  ['Registered',    fmtDate(viewDetail.created_at)],
                ].map(([label, val]) => (
                  <div key={label} style={{ display:'flex', justifyContent:'space-between', padding:'9px 0', borderBottom:'1px solid rgba(20,20,19,0.06)', fontSize:13 }}>
                    <span style={{ color:'#696969' }}>{label}</span>
                    <span style={{ fontWeight:600, color:'#141413' }}>{val}</span>
                  </div>
                ))}
              </div>

              {/* Recent bookings */}
              {Array.isArray(viewDetail.bookings) && viewDetail.bookings.length > 0 && (
                <div style={{ marginBottom:20 }}>
                  <div style={{ fontWeight:700, fontSize:13, color:'#141413', marginBottom:10 }}>Recent Bookings</div>
                  <div style={{ background:'#FAFAF9', borderRadius:10, overflow:'hidden' }}>
                    {viewDetail.bookings.slice(0,5).map((b, i) => (
                      <div key={b.id} style={{ display:'flex', justifyContent:'space-between', padding:'9px 12px', borderBottom: i < Math.min(viewDetail.bookings.length,5)-1 ? '1px solid rgba(20,20,19,0.06)' : 'none', fontSize:12 }}>
                        <span style={{ fontFamily:'monospace', color:'#E84800', fontWeight:700 }}>{b.booking_ref}</span>
                        <CmsBadge status={b.status} />
                        <span style={{ color:'#696969' }}>Rs. {Number(b.total||0).toLocaleString()}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {Array.isArray(viewDetail.bookings) && viewDetail.bookings.length === 0 && (
                <div style={{ color:'#969696', fontSize:13, marginBottom:20 }}>No bookings on record.</div>
              )}

              {actionMsg && (
                <div style={{ background: actionMsg.startsWith('✅') ? '#D1FAE5' : '#FEE2E2', borderRadius:8, padding:'8px 12px', fontSize:12, marginBottom:12, color: actionMsg.startsWith('✅') ? '#065F46':'#DC2626' }}>{actionMsg}</div>
              )}

              {/* Action buttons */}
              <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
                <button onClick={()=>toggleStatus(viewDetail)} style={{ ...BTN, flex:1, padding:'11px 0', background: viewDetail.is_active !== 0 ? '#FEF3C7' : '#D1FAE5', color: viewDetail.is_active !== 0 ? '#92400E' : '#065F46' }}>
                  {viewDetail.is_active !== 0 ? '🚫 Block User' : '✅ Unblock User'}
                </button>
                <button onClick={()=>setDelConf(viewDetail.id)} style={{ ...BTN, flex:1, padding:'11px 0', background:'#FEE2E2', color:'#DC2626' }}>
                  🗑️ Delete User
                </button>
              </div>
            </div>
          )}
        </Modal>
      )}

      {/* ── Create User Modal ── */}
      {createOpen && (
        <Modal title="Create New User" onClose={()=>{setCreateOpen(false);setCreateErr('');}}>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {createErr && <div style={{ background:'#FEE2E2', border:'1px solid #FECACA', borderRadius:8, padding:'10px 14px', color:'#DC2626', fontSize:13 }}>❌ {createErr}</div>}
            <div>
              <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#696969', marginBottom:5, textTransform:'uppercase', letterSpacing:'0.05em' }}>Full Name *</label>
              <input value={createForm.name} onChange={e=>setCF('name',e.target.value)} placeholder="e.g. Kasun Perera"
                style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.15)', fontSize:14, fontFamily:'inherit', outline:'none' }} />
            </div>
            <div>
              <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#696969', marginBottom:5, textTransform:'uppercase', letterSpacing:'0.05em' }}>Email Address *</label>
              <input type="email" value={createForm.email} onChange={e=>setCF('email',e.target.value)} placeholder="e.g. kasun@example.com"
                style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.15)', fontSize:14, fontFamily:'inherit', outline:'none' }} />
            </div>
            <div>
              <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#696969', marginBottom:5, textTransform:'uppercase', letterSpacing:'0.05em' }}>Password * (min 8 chars)</label>
              <input type="password" value={createForm.password} onChange={e=>setCF('password',e.target.value)} placeholder="Enter a strong password"
                style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.15)', fontSize:14, fontFamily:'inherit', outline:'none' }} />
            </div>
            <div>
              <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#696969', marginBottom:5, textTransform:'uppercase', letterSpacing:'0.05em' }}>Role</label>
              <select value={createForm.role} onChange={e=>setCF('role',e.target.value)}
                style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.15)', fontSize:14, fontFamily:'inherit', background:'#fff', outline:'none' }}>
                <option value="renter">Renter — standard customer account</option>
                <option value="owner">Owner — vehicle owner account</option>
                <option value="admin">Admin — CMS access</option>
              </select>
            </div>
            <div>
              <label style={{ display:'block', fontSize:12, fontWeight:700, color:'#696969', marginBottom:5, textTransform:'uppercase', letterSpacing:'0.05em' }}>Phone (optional)</label>
              <input value={createForm.phone} onChange={e=>setCF('phone',e.target.value)} placeholder="e.g. +94771234567"
                style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.15)', fontSize:14, fontFamily:'inherit', outline:'none' }} />
            </div>
            <div style={{ display:'flex', gap:10, marginTop:6 }}>
              <button onClick={()=>{setCreateOpen(false);setCreateErr('');}} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
              <button onClick={createUser} disabled={createLoading} style={{ ...BTN, flex:2, background:'#059669', color:'#fff', padding:'12px 0', opacity:createLoading?0.6:1 }}>
                {createLoading ? '⏳ Creating…' : '✅ Create User'}
              </button>
            </div>
          </div>
        </Modal>
      )}

      {/* ── Role Change Modal ── */}
      {roleModal && (
        <Modal title="Change User Role" onClose={()=>setRoleModal(null)}>
          <p style={{ color:'#696969', fontSize:14, marginBottom:16 }}>
            Changing role for <strong style={{ color:'#141413' }}>{roleModal.user.name}</strong>
          </p>
          <select value={roleModal.newRole} onChange={e=>setRoleModal(rm=>({...rm,newRole:e.target.value}))}
            style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid rgba(20,20,19,0.15)', fontSize:14, fontFamily:'inherit', background:'#fff', marginBottom:18, outline:'none' }}>
            <option value="renter">Renter — standard customer</option>
            <option value="owner">Owner — vehicle owner</option>
            <option value="admin">Admin — CMS access</option>
          </select>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={()=>setRoleModal(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={()=>updateRole(roleModal.user.id, roleModal.newRole)} style={{ ...BTN, flex:1, background:'#0066CC', color:'#fff', padding:'12px 0' }}>✅ Update Role</button>
          </div>
        </Modal>
      )}

      {/* ── Delete Confirmation Modal ── */}
      {delConf && (
        <Modal title="Confirm Delete User" onClose={()=>setDelConf(null)}>
          <div style={{ textAlign:'center', padding:'8px 0 16px' }}>
            <div style={{ fontSize:40, marginBottom:12 }}>⚠️</div>
            <p style={{ color:'#696969', fontSize:14, marginBottom:6, lineHeight:1.6 }}>
              This will permanently delete the user account.
            </p>
            <p style={{ color:'#DC2626', fontSize:13, fontWeight:600, marginBottom:20 }}>
              Booking history will be preserved (user_id will be cleared).
            </p>
          </div>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={()=>setDelConf(null)} style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'12px 0' }}>Cancel</button>
            <button onClick={()=>deleteUser(delConf)} disabled={loading} style={{ ...BTN, flex:1, background:'#DC2626', color:'#fff', padding:'12px 0', opacity:loading?0.6:1 }}>
              {loading ? '⏳ Deleting…' : '🗑️ Delete Permanently'}
            </button>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ─── DRIVER BOOKINGS CMS ─────────────────────────────────────
function DriverBookingsCMS({ data, setData, admin }) {
  const bookings     = data.driverBookings || [];
  const [filter,     setFilter]     = React.useState('all');
  const [search,     setSearch]     = React.useState('');
  const [selected,   setSelected]   = React.useState(null);
  const [loading,    setLoading]    = React.useState(false);
  const [actionMsg,  setActionMsg]  = React.useState('');
  const [rejReason,  setRejReason]  = React.useState('');
  const [adminNote,  setAdminNote]  = React.useState('');
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const [settings,   setSettings]   = React.useState([]);
  const [settingsSaving, setSettingsSaving] = React.useState(false);

  const authHdr = admin?.token ? { 'Authorization': `Bearer ${admin.token}` } : {};

  // Re-fetch list
  const reload = async () => {
    setLoading(true);
    try {
      const res = await fetch('api/cms_driver_bookings.php', { headers: authHdr });
      const json = await res.json();
      if (json.bookings) setData(prev => ({ ...prev, driverBookings: json.bookings, dbStatusCounts: json.status_counts || {} }));
    } catch(e) {}
    setLoading(false);
  };

  const loadSettings = async () => {
    const res = await fetch('api/cms_driver_bookings.php?settings=1', { headers: authHdr });
    const json = await res.json();
    if (json.settings) setSettings(json.settings);
    setSettingsOpen(true);
  };

  // Action call helper
  const doAction = async (bookingId, payload, successMsg) => {
    setActionMsg('');
    try {
      const res  = await fetch(`api/cms_driver_bookings.php?id=${bookingId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...authHdr },
        body: JSON.stringify(payload),
      });
      const json = await res.json();
      if (!res.ok || json.error) { setActionMsg('❌ ' + (json.error || 'Action failed')); return false; }
      setActionMsg('✅ ' + successMsg);
      // Update local selected state
      if (selected?.id === bookingId) {
        setSelected(prev => ({ ...prev, status: json.status || prev.status, ...json }));
      }
      reload();
      return true;
    } catch(e) { setActionMsg('❌ Network error'); return false; }
  };

  const STATUS_LABELS = {
    all: 'All', pending: 'Pending', under_review: 'Under Review',
    confirmed: 'Confirmed', active: 'Active', completed: 'Completed', cancelled: 'Cancelled',
  };
  const STATUS_COLORS = {
    pending:      { bg:'#FEF3C7', color:'#92400E' },
    under_review: { bg:'#EFF6FF', color:'#1D4ED8' },
    confirmed:    { bg:'#D1FAE5', color:'#065F46' },
    active:       { bg:'#DCFCE7', color:'#166534' },
    completed:    { bg:'#F0FDF4', color:'#14532D' },
    cancelled:    { bg:'#FEE2E2', color:'#991B1B' },
  };
  const SChip = ({ status }) => {
    const s = STATUS_COLORS[status] || { bg:'#F3F4F6', color:'#374151' };
    return <span style={{ background:s.bg, color:s.color, fontWeight:700, fontSize:11, padding:'3px 10px', borderRadius:20, textTransform:'uppercase', letterSpacing:'0.04em', whiteSpace:'nowrap' }}>{STATUS_LABELS[status] || status}</span>;
  };

  const filtered = React.useMemo(() => {
    return bookings.filter(b => {
      const matchStatus = filter === 'all' || b.status === filter;
      const q = search.toLowerCase();
      const matchSearch = !q ||
        (b.full_name || '').toLowerCase().includes(q) ||
        (b.email || '').toLowerCase().includes(q) ||
        (b.booking_ref || '').toLowerCase().includes(q) ||
        (b.driver_name || '').toLowerCase().includes(q);
      return matchStatus && matchSearch;
    });
  }, [bookings, filter, search]);

  const counts = data.dbStatusCounts || {};

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:12, marginBottom:24 }}>
        <div>
          <h2 style={{ fontWeight:800, fontSize:'clamp(18px,3vw,24px)', color:'#141413', letterSpacing:'-0.03em', margin:0 }}>Driver Bookings</h2>
          <div style={{ fontSize:13, color:'#969696', marginTop:3 }}>Manage hire requests, approvals, and payouts</div>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <button onClick={loadSettings} style={{ ...BTN, background:'#7C3AED', color:'#fff' }}>⚙️ Pricing Settings</button>
          <button onClick={reload} style={{ ...BTN, background:'#141413', color:'#fff' }}>↻ Refresh</button>
        </div>
      </div>

      {/* Status summary chips */}
      <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:20 }}>
        {Object.entries(STATUS_LABELS).map(([k, lbl]) => (
          <button key={k} onClick={() => setFilter(k)} style={{
            ...BTN, padding:'6px 14px', fontSize:12,
            background: filter === k ? '#141413' : '#fff',
            color:      filter === k ? '#fff'    : '#696969',
            border: `1.5px solid ${filter === k ? '#141413' : 'rgba(20,20,19,0.12)'}`,
          }}>
            {lbl}
            {k !== 'all' && counts[k] ? <span style={{ marginLeft:5, background: filter===k ? 'rgba(255,255,255,0.25)' : '#F3F4F6', borderRadius:10, padding:'1px 6px', fontSize:11 }}>{counts[k]}</span> : null}
          </button>
        ))}
      </div>

      {/* Search */}
      <input
        type="text" placeholder="Search by name, email, ref, driver…"
        value={search} onChange={e => setSearch(e.target.value)}
        style={{ ...INP, marginBottom:18, maxWidth:380 }}
      />

      {loading && <div style={{ textAlign:'center', padding:48, color:'#969696' }}>⏳ Loading…</div>}

      {/* Table */}
      {!loading && (
        <div style={{ overflowX:'auto', background:'#fff', borderRadius:16, boxShadow:'0 2px 10px rgba(20,20,19,0.06)' }}>
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, minWidth:700 }}>
            <thead>
              <tr style={{ borderBottom:'2px solid rgba(20,20,19,0.08)', textAlign:'left' }}>
                {['Ref', 'Customer', 'Driver', 'Dates', 'Total', 'Status', 'Payment', 'Actions'].map(h => (
                  <th key={h} style={{ padding:'12px 14px', fontWeight:700, color:'#696969', textTransform:'uppercase', fontSize:11, letterSpacing:'0.05em', whiteSpace:'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 && (
                <tr><td colSpan={8} style={{ textAlign:'center', padding:'40px 20px', color:'#969696' }}>No bookings found.</td></tr>
              )}
              {filtered.map(b => (
                <tr key={b.id} style={{ borderBottom:'1px solid rgba(20,20,19,0.05)', cursor:'pointer' }}
                  onClick={() => { setSelected(b); setActionMsg(''); setRejReason(''); setAdminNote(b.admin_note || ''); }}>
                  <td style={{ padding:'12px 14px', fontWeight:700, color:'#E84800', whiteSpace:'nowrap' }}>{b.booking_ref}</td>
                  <td style={{ padding:'12px 14px' }}>
                    <div style={{ fontWeight:600, color:'#141413' }}>{b.full_name}</div>
                    <div style={{ fontSize:11, color:'#969696' }}>{b.email}</div>
                  </td>
                  <td style={{ padding:'12px 14px' }}>
                    <div style={{ fontWeight:600, color:'#141413' }}>{b.driver_name}</div>
                    <div style={{ fontSize:11, color:'#969696' }}>{b.driver_location}</div>
                  </td>
                  <td style={{ padding:'12px 14px', whiteSpace:'nowrap' }}>
                    <div style={{ fontWeight:500 }}>{b.start_date} → {b.end_date}</div>
                    <div style={{ fontSize:11, color:'#969696' }}>{b.days} day{b.days !== 1 ? 's' : ''}</div>
                  </td>
                  <td style={{ padding:'12px 14px', fontWeight:700, whiteSpace:'nowrap' }}>Rs. {(parseInt(b.subtotal)||0).toLocaleString()}</td>
                  <td style={{ padding:'12px 14px' }}><SChip status={b.status} /></td>
                  <td style={{ padding:'12px 14px' }}>
                    <span style={{ fontSize:11, fontWeight:600, color: b.payment_status==='paid' ? '#059669' : '#969696' }}>
                      {b.payment_status === 'paid' ? '✅ Paid' : '⏳ Unpaid'}
                    </span>
                  </td>
                  <td style={{ padding:'12px 14px' }}>
                    <button onClick={e => { e.stopPropagation(); setSelected(b); setActionMsg(''); setRejReason(''); setAdminNote(b.admin_note || ''); }}
                      style={{ ...BTN, background:'#141413', color:'#fff', padding:'6px 12px', fontSize:12 }}>View</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* ── Detail Modal ─────────��─────────────────────────────── */}
      {selected && (
        <div onClick={() => setSelected(null)} style={{ position:'fixed', inset:0, background:'rgba(20,20,19,0.55)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:3000, padding:16 }}>
          <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:20, width:'100%', maxWidth:680, maxHeight:'92vh', display:'flex', flexDirection:'column', boxShadow:'0 20px 60px rgba(20,20,19,0.2)' }}>
            {/* Modal header */}
            <div style={{ padding:'18px 22px 14px', borderBottom:'1px solid rgba(20,20,19,0.08)', display:'flex', justifyContent:'space-between', alignItems:'center', flexShrink:0 }}>
              <div>
                <div style={{ fontWeight:800, fontSize:16, color:'#141413' }}>Booking {selected.booking_ref}</div>
                <div style={{ marginTop:4 }}><SChip status={selected.status} /></div>
              </div>
              <button onClick={() => setSelected(null)} style={{ background:'none', border:'none', fontSize:24, cursor:'pointer', color:'#969696' }}>×</button>
            </div>

            {/* Modal body */}
            <div style={{ padding:'18px 22px', overflowY:'auto', flex:1 }}>

              {actionMsg && (
                <div style={{ background: actionMsg.startsWith('✅') ? '#D1FAE5' : '#FEE2E2', borderRadius:10, padding:'10px 14px', marginBottom:14, fontSize:13, fontWeight:600, color: actionMsg.startsWith('✅') ? '#065F46' : '#DC2626' }}>
                  {actionMsg}
                </div>
              )}

              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>

                {/* Driver */}
                <div style={{ background:'#FBF8F5', borderRadius:14, padding:16 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#E84800', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:10 }}>Driver</div>
                  {[
                    ['Name',     selected.driver_name],
                    ['Phone',    selected.driver_phone],
                    ['Email',    selected.driver_email],
                    ['License',  selected.driver_license],
                    ['Location', selected.driver_location],
                  ].map(([k,v]) => v && (
                    <div key={k} style={{ display:'flex', justifyContent:'space-between', marginBottom:6, fontSize:12, gap:8 }}>
                      <span style={{ color:'#969696', flexShrink:0 }}>{k}</span>
                      <span style={{ fontWeight:600, color:'#141413', textAlign:'right', wordBreak:'break-word' }}>{v}</span>
                    </div>
                  ))}
                </div>

                {/* Customer */}
                <div style={{ background:'#FBF8F5', borderRadius:14, padding:16 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#0066CC', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:10 }}>Customer</div>
                  {[
                    ['Name',    selected.full_name],
                    ['Contact', selected.contact_number],
                    ['Email',   selected.email],
                  ].map(([k,v]) => v && (
                    <div key={k} style={{ display:'flex', justifyContent:'space-between', marginBottom:6, fontSize:12, gap:8 }}>
                      <span style={{ color:'#969696', flexShrink:0 }}>{k}</span>
                      <span style={{ fontWeight:600, color:'#141413', textAlign:'right', wordBreak:'break-word' }}>{v}</span>
                    </div>
                  ))}
                </div>

                {/* Trip Details */}
                <div style={{ background:'#FBF8F5', borderRadius:14, padding:16 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#059669', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:10 }}>Trip Details</div>
                  {[
                    ['Start Date',   selected.start_date],
                    ['End Date',     selected.end_date],
                    ['Duration',     `${selected.days} day${selected.days !== 1 ? 's' : ''}`],
                    ['Arrival Time', selected.start_time],
                    ['Pickup',       selected.pickup_location],
                    ['Food',         selected.food_provided ? '✅ Provided' : '❌ Not provided'],
                    ['Accom.',       selected.accommodation_provided ? '✅ Provided' : '❌ Not provided'],
                  ].map(([k,v]) => v && (
                    <div key={k} style={{ display:'flex', justifyContent:'space-between', marginBottom:6, fontSize:12, gap:8 }}>
                      <span style={{ color:'#969696', flexShrink:0 }}>{k}</span>
                      <span style={{ fontWeight:600, color:'#141413', textAlign:'right', wordBreak:'break-all' }}>{v}</span>
                    </div>
                  ))}
                  {selected.notes && <div style={{ fontSize:11, color:'#696969', marginTop:6, fontStyle:'italic' }}>"{selected.notes}"</div>}
                </div>

                {/* Pricing & Payout */}
                <div style={{ background:'#FBF8F5', borderRadius:14, padding:16 }}>
                  <div style={{ fontSize:11, fontWeight:700, color:'#7C3AED', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:10 }}>Pricing & Payout</div>
                  {[
                    ['Daily Rate',   `Rs. ${(parseInt(selected.daily_rate)||0).toLocaleString()}`],
                    ['Base Cost',    `Rs. ${(parseInt(selected.base_cost)||0).toLocaleString()}`],
                    ...(parseInt(selected.food_extra_total) > 0 ? [['Food Extra', `Rs. ${(parseInt(selected.food_extra_total)).toLocaleString()}`]] : []),
                    ...(parseInt(selected.accommodation_extra_total) > 0 ? [['Accom Extra', `Rs. ${(parseInt(selected.accommodation_extra_total)).toLocaleString()}`]] : []),
                    ['Total (Customer)', `Rs. ${(parseInt(selected.subtotal)||0).toLocaleString()}`],
                    ['Commission',   `${selected.platform_commission_pct}% = Rs. ${(parseInt(selected.platform_commission_amount)||0).toLocaleString()}`],
                    ['Driver Payout', `Rs. ${(parseInt(selected.driver_payout_total)||0).toLocaleString()}`],
                  ].map(([k,v]) => (
                    <div key={k} style={{ display:'flex', justifyContent:'space-between', marginBottom:6, fontSize:12, gap:8 }}>
                      <span style={{ color:'#969696', flexShrink:0 }}>{k}</span>
                      <span style={{ fontWeight:700, color: k === 'Total (Customer)' ? '#E84800' : k === 'Driver Payout' ? '#059669' : '#141413', textAlign:'right' }}>{v}</span>
                    </div>
                  ))}

                  {/* Payout status */}
                  <div style={{ borderTop:'1px solid rgba(20,20,19,0.1)', paddingTop:8, marginTop:8 }}>
                    <div style={{ fontSize:11, color: selected.payout_50_released ? '#059669' : '#969696', fontWeight:600, marginBottom:3 }}>
                      {selected.payout_50_released ? `✅ 50% released: Rs. ${(parseInt(selected.payout_50_amount)||0).toLocaleString()}` : '⏳ 50% payout not yet released'}
                    </div>
                    <div style={{ fontSize:11, color: selected.payout_remaining_released ? '#059669' : '#969696', fontWeight:600 }}>
                      {selected.payout_remaining_released ? `✅ Final payout released: Rs. ${(parseInt(selected.payout_remaining_amount)||0).toLocaleString()}` : '⏳ Final payout pending'}
                    </div>
                  </div>
                </div>
              </div>

              {/* ── Action controls ────────────────────────────── */}
              <div style={{ background:'#F5F5F3', borderRadius:14, padding:16 }}>
                <div style={{ fontSize:11, fontWeight:700, color:'#141413', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:14 }}>Admin Actions</div>

                {/* Status change */}
                <div style={{ marginBottom:14 }}>
                  <div style={{ fontSize:12, fontWeight:600, color:'#696969', marginBottom:8 }}>Change Status</div>
                  <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                    {['pending','under_review','confirmed','active','completed','cancelled'].map(s => (
                      <button key={s} onClick={() => doAction(selected.id, { action:'set_status', status:s }, `Status → ${s}`)}
                        disabled={selected.status === s}
                        style={{ ...BTN, fontSize:11, padding:'6px 12px',
                          background: selected.status === s ? '#E84800' : '#fff',
                          color:      selected.status === s ? '#fff'    : '#696969',
                          border: `1.5px solid ${selected.status === s ? '#E84800' : 'rgba(20,20,19,0.15)'}`,
                          opacity: selected.status === s ? 1 : 0.85,
                          textTransform:'capitalize'
                        }}>{s.replace('_',' ')}</button>
                    ))}
                  </div>
                </div>

                {/* Quick approve / reject */}
                {(selected.status === 'pending' || selected.status === 'under_review') && (
                  <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:14 }}>
                    <button onClick={() => doAction(selected.id, { action:'approve', admin_note: adminNote }, 'Booking confirmed!')}
                      style={{ ...BTN, background:'#059669', color:'#fff', flex:1, padding:'10px 0' }}>✅ Approve & Confirm</button>
                    <div style={{ flex:1, display:'flex', gap:6 }}>
                      <input value={rejReason} onChange={e=>setRejReason(e.target.value)} placeholder="Rejection reason…" style={{ ...INP, flex:1, fontSize:12 }} />
                      <button onClick={() => rejReason.trim() && doAction(selected.id, { action:'reject', rejection_reason: rejReason }, 'Booking rejected.')}
                        disabled={!rejReason.trim()} style={{ ...BTN, background:'#DC2626', color:'#fff', opacity: rejReason.trim() ? 1 : 0.5 }}>Reject</button>
                    </div>
                  </div>
                )}

                {/* Payment */}
                {selected.payment_status !== 'paid' && selected.status === 'confirmed' && (
                  <div style={{ marginBottom:14 }}>
                    <div style={{ fontSize:12, fontWeight:600, color:'#696969', marginBottom:8 }}>Mark Payment Received</div>
                    <button onClick={() => doAction(selected.id, { action:'mark_paid', payment_method:'admin_manual' }, 'Payment marked as received.')}
                      style={{ ...BTN, background:'#7C3AED', color:'#fff', padding:'8px 16px' }}>💳 Mark as Paid</button>
                  </div>
                )}

                {/* Payouts */}
                {selected.payment_status === 'paid' && (
                  <div style={{ marginBottom:14 }}>
                    <div style={{ fontSize:12, fontWeight:600, color:'#696969', marginBottom:8 }}>Driver Payout</div>
                    <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                      {!selected.payout_50_released && (
                        <button onClick={() => doAction(selected.id, { action:'release_50_payout' }, '50% payout released to driver!')}
                          style={{ ...BTN, background:'#E84800', color:'#fff', padding:'8px 16px', fontSize:12 }}>
                          🚀 Release 50% (Trip Start) — Rs. {Math.round((parseInt(selected.driver_payout_total)||0)*0.5).toLocaleString()}
                        </button>
                      )}
                      {selected.payout_50_released && !selected.payout_remaining_released && (
                        <button onClick={() => doAction(selected.id, { action:'release_remaining_payout' }, 'Final payout released! Booking completed.')}
                          style={{ ...BTN, background:'#059669', color:'#fff', padding:'8px 16px', fontSize:12 }}>
                          ✅ Release Final 50% (Trip Complete)
                        </button>
                      )}
                      {selected.payout_remaining_released && (
                        <div style={{ fontSize:12, fontWeight:700, color:'#059669', padding:'8px 12px', background:'#D1FAE5', borderRadius:8 }}>
                          ✅ Full payout complete — Rs. {(parseInt(selected.driver_payout_total)||0).toLocaleString()} paid to driver
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Admin note */}
                <div>
                  <div style={{ fontSize:12, fontWeight:600, color:'#696969', marginBottom:6 }}>Admin Note</div>
                  <div style={{ display:'flex', gap:8 }}>
                    <textarea value={adminNote} onChange={e=>setAdminNote(e.target.value)}
                      style={{ ...INP, flex:1, minHeight:60, resize:'vertical', fontSize:12 }}
                      placeholder="Internal note visible only to admins…" />
                    <button onClick={() => doAction(selected.id, { action:'update_note', admin_note: adminNote }, 'Note saved.')}
                      style={{ ...BTN, background:'#141413', color:'#fff', alignSelf:'flex-start' }}>Save</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Settings Modal ─────────��───────────────────────────── */}
      {settingsOpen && (
        <div onClick={() => setSettingsOpen(false)} style={{ position:'fixed', inset:0, background:'rgba(20,20,19,0.55)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:3000, padding:16 }}>
          <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:20, width:'100%', maxWidth:440, padding:'24px', boxShadow:'0 20px 60px rgba(20,20,19,0.2)' }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
              <div style={{ fontWeight:800, fontSize:16, color:'#141413' }}>⚙️ Pricing Settings</div>
              <button onClick={() => setSettingsOpen(false)} style={{ background:'none', border:'none', fontSize:24, cursor:'pointer', color:'#969696' }}>×</button>
            </div>
            {settings.map((s, i) => (
              <div key={s.setting_key} style={{ marginBottom:16 }}>
                <label style={{ fontSize:12, fontWeight:700, color:'#696969', textTransform:'uppercase', letterSpacing:'0.05em', display:'block', marginBottom:6 }}>
                  {s.setting_key.replace(/_/g,' ')}
                </label>
                <div style={{ fontSize:11, color:'#969696', marginBottom:5 }}>{s.description}</div>
                <input
                  type="number" value={s.setting_value}
                  onChange={e => setSettings(prev => prev.map((x,j) => j===i ? {...x, setting_value: e.target.value} : x))}
                  style={{ ...INP }}
                />
              </div>
            ))}
            <button
              disabled={settingsSaving}
              onClick={async () => {
                setSettingsSaving(true);
                const payload = {};
                settings.forEach(s => payload[s.setting_key] = s.setting_value);
                await fetch('api/cms_driver_bookings.php?settings=1', {
                  method:'PUT', headers:{ 'Content-Type':'application/json', ...authHdr },
                  body: JSON.stringify(payload),
                });
                setSettingsSaving(false);
                setSettingsOpen(false);
              }}
              style={{ ...BTN, background:'#7C3AED', color:'#fff', width:'100%', padding:'12px 0', fontSize:14, opacity:settingsSaving?.7:1 }}
            >{settingsSaving ? '⏳ Saving…' : '✅ Save Settings'}</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── MAIN ADMIN PAGE ────────────────────────────���────────────
function AdminPage({ setPage }) {
  const [admin, setAdmin] = React.useState(() => {
    try {
      const s = localStorage.getItem('cr_admin');
      if (!s) return null;
      const p = JSON.parse(s);
      if (Date.now()-p.loginTime > 8*3600*1000) { localStorage.removeItem('cr_admin'); return null; }
      return p;
    } catch { return null; }
  });
  const [mod,     setMod]     = React.useState('dashboard');
  const [sideOpen,setSideOpen]= React.useState(false);
  const [data,    setData]    = React.useState({
    vehicles:      [],
    drivers:       [],
    guides:        [],
    packages:      [],
    bookings:      [],
    driverBookings:[],
    tourInquiries: [],
    users:         [],
    notifications: [],
    registrations: [],
    uiImages: UI_IMAGE_SCHEMA,
    revenue:  { daily: [], labels: [] },
  });
  const [detail,  setDetail]  = React.useState(null);
  const [auditLogs, setAuditLogs] = React.useState([]);
  const auditLog = { logs: auditLogs, setLogs: setAuditLogs };
  const [syncing,    setSyncing]    = React.useState(false);
  const [syncModal,  setSyncModal]  = React.useState(false);
  const [syncResults,setSyncResults]= React.useState(null);

  // ── Shared data loader — used by initial load AND Save & Sync ──
  const loadAllData = React.useCallback(async (tkn) => {
    const token = tkn || (admin?.token || '');
    const API = (window.CEYRIDE_API_BASE || 'api').replace(/\/$/, '');
    const safe = url => fetch(`${API}/${url}`, {
      headers: { 'Authorization': token ? `Bearer ${token}` : '' }
    }).then(r => r.ok ? r.json() : null).catch(() => null);

    const [v, d, g, p, b, db, ti, notifs, users, regs, cfg] = await Promise.all([
      safe('cms_vehicles.php'),
      safe('cms_drivers.php'),
      safe('cms_guides.php'),
      safe('cms_packages.php'),
      safe('cms_bookings.php'),
      safe('cms_driver_bookings.php'),
      safe('cms_tour_inquiries.php'),
      safe('admin.php?action=get_notifications'),
      safe('admin.php?action=get_users'),
      safe('owner_registrations.php'),
      safe('admin.php?action=get_homepage_config'),
    ]);

    // Merge saved image paths from DB into schema structure
    const mergedImages = cfg?.config
      ? UI_IMAGE_SCHEMA.map(img => cfg.config[img.key] ? { ...img, src: cfg.config[img.key] } : img)
      : UI_IMAGE_SCHEMA;

    // Compute real 7-day revenue from loaded bookings (same logic as Finance module)
    const allBks = [
      ...((b?.bookings  || []).map(bk => ({ ...bk, _type: 'vehicle' }))),
      ...((db?.bookings || []).map(bk => ({ ...bk, _type: 'driver'  }))),
      ...((ti?.inquiries|| []).map(bk => ({ ...bk, _type: 'tour', total: bk.package_price || 0 }))),
    ];
    const confBks = allBks.filter(bk => ['confirmed', 'approved', 'completed'].includes(bk.status));
    const days7 = []; const labels7 = [];
    for (let i = 6; i >= 0; i--) {
      const day = new Date(); day.setDate(day.getDate() - i);
      const dayKey = day.toISOString().slice(0, 10);
      labels7.push(day.toLocaleDateString('en-GB', { weekday: 'short' }));
      days7.push(confBks.filter(bk => (bk.created_at || '').startsWith(dayKey)).reduce((s, bk) => s + Number(bk.total || 0), 0));
    }

    setData(prev => ({
      ...prev,
      ...(v?.vehicles           ? { vehicles:       v.vehicles           } : {}),
      ...(d?.drivers            ? { drivers:        d.drivers            } : {}),
      ...(g?.guides             ? { guides:         g.guides             } : {}),
      ...(p?.packages           ? { packages:       p.packages           } : {}),
      ...(b?.bookings           ? { bookings:       b.bookings           } : {}),
      ...(db?.bookings          ? { driverBookings: db.bookings          } : {}),
      ...(db?.status_counts     ? { dbStatusCounts: db.status_counts     } : {}),
      ...(ti?.inquiries         ? { tourInquiries:  ti.inquiries         } : {}),
      ...(notifs?.notifications ? { notifications:  notifs.notifications } : {}),
      ...(users?.users          ? { users:          users.users          } : {}),
      ...(regs?.registrations   ? { registrations:  regs.registrations   } : {}),
      uiImages: mergedImages,
      revenue:  { daily: days7, labels: labels7 },
    }));
    return { v, d, g, p, b, db, notifs, users, regs, cfg };
  }, [admin]);

  // ── Save & Sync — manual refresh of all data from DB ──────
  const syncAllData = async () => {
    if (syncing) return;
    setSyncing(true);
    await loadAllData();
    setSyncing(false);
    logAction(auditLogs, setAuditLogs, 'Sync', 'System', 'Manual Save & Sync completed — all data refreshed from database');
  };

  // ── Sync Check — ping all API endpoints and report status ──
  const runSyncCheck = async () => {
    setSyncModal(true);
    setSyncResults(null);
    const token = admin?.token || '';
    const API = (window.CEYRIDE_API_BASE || 'api').replace(/\/$/, '');
    const ping = async (label, url, method='GET') => {
      const start = Date.now();
      try {
        const res = await fetch(`${API}/${url}`, {
          method,
          headers: { 'Authorization': token ? `Bearer ${token}` : '', 'Content-Type': 'application/json' }
        });
        const ms = Date.now() - start;
        const ok = res.ok || res.status < 500;
        return { label, ok, ms, status: res.status };
      } catch (e) {
        return { label, ok: false, ms: Date.now()-start, status: 'Network Error' };
      }
    };
    const checks = await Promise.all([
      ping('Vehicles DB',         'cms_vehicles.php'),
      ping('Owner Registrations', 'owner_registrations.php'),
      ping('Users DB',            'admin.php?action=get_users'),
      ping('Bookings DB',         'cms_bookings.php'),
      ping('Drivers DB',          'cms_drivers.php'),
      ping('Guides DB',           'cms_guides.php'),
      ping('Packages DB',         'cms_packages.php'),
      ping('Notifications',       'admin.php?action=get_notifications'),
      ping('Stats',               'admin.php?action=get_stats'),
      ping('Driver Bookings',     'cms_driver_bookings.php'),
      ping('Tour Inquiries',      'cms_tour_inquiries.php'),
    ]);
    setSyncResults(checks);
  };

  // ── Load real data from DB when admin logs in ──────────────
  React.useEffect(() => {
    if (!admin) return;
    loadAllData(admin.token);
  }, [admin]);

  const logout = () => { localStorage.removeItem('cr_admin'); setAdmin(null); };
  if (!admin) return <AdminLogin onLogin={s=>{setAdmin(s);}} />;

  const _listApiAction = {
    registrations: { endpoint: 'admin.php', actionApprove: 'update_vehicle_status', actionReject: 'update_vehicle_status' },
    drivers:       { endpoint: 'cms_drivers.php',  actionApprove: 'approve', actionReject: 'reject' },
    guides:        { endpoint: 'cms_guides.php',   actionApprove: 'approve', actionReject: 'reject' },
    bookings:      { endpoint: 'admin.php', actionApprove: 'update_booking_status', actionReject: 'update_booking_status' },
  };
  const _persistStatus = async (list, id, status) => {
    const API  = (window.CEYRIDE_API_BASE || 'api').replace(/\/$/, '');
    const conf = _listApiAction[list];
    if (!conf) return;
    const action = status === 'approved' ? conf.actionApprove : conf.actionReject;
    try {
      await fetch(`${API}/${conf.endpoint}?action=${action}`, {
        method: 'POST',
        headers: { 'Authorization': admin?.token ? `Bearer ${admin.token}` : '', 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, status }),
      });
    } catch (e) { console.warn('CeyRide CMS: persist failed', list, id, status, e); }
  };
  const approve = (list, id) => {
    const item = data[list]?.find(r=>r.id===id);
    setData(d=>({...d,[list]:(d[list]||[]).map(r=>r.id===id?{...r,status:'approved'}:r)}));
    logAction(auditLogs, setAuditLogs, 'Approved', list.charAt(0).toUpperCase()+list.slice(1), item?.name||item?.owner||`ID ${id}`);
    _persistStatus(list, id, 'approved');
  };
  const reject  = (list, id) => {
    const item = data[list]?.find(r=>r.id===id);
    setData(d=>({...d,[list]:(d[list]||[]).map(r=>r.id===id?{...r,status:'rejected'}:r)}));
    logAction(auditLogs, setAuditLogs, 'Rejected', list.charAt(0).toUpperCase()+list.slice(1), item?.name||item?.owner||`ID ${id}`);
    _persistStatus(list, id, 'rejected');
  };

  const badges = {
    veh: (data.registrations||[]).filter(r=>r.status==='pending').length,
    drv: data.drivers.filter(d=>d.status==='pending').length,
    gde: data.guides.filter(g=>g.status==='pending').length,
    pkg: data.packages.filter(p=>p.status==='pending').length,
    bk:  data.bookings.filter(b=>b.status==='pending').length,
    dbk: (data.driverBookings||[]).filter(b=>b.status==='pending').length,
    ntf: data.notifications.filter(n=>!n.read).length,
  };

  const mods = {
    dashboard: <Dashboard data={data} setMod={setMod} />,
    vehicles:  <VehiclesCMS  data={data} setData={setData} auditLog={auditLog} />,
    drivers:   <DriversCMS   data={data} setData={setData} auditLog={auditLog} />,
    guides:    <GuidesCMS    data={data} setData={setData} auditLog={auditLog} />,
    packages:  <PackagesCMS  data={data} setData={setData} auditLog={auditLog} />,
    bookings:         <BookingsCMS       data={data} setData={setData} auditLog={auditLog} />,
    'driver-bookings':<DriverBookingsCMS data={data} setData={setData} admin={admin} />,
    finance:   <Finance data={data} />,
    users:     <Users   data={data} setData={setData} />,
    images:    <ImageManager data={data} setData={setData} />,
    content:   <Content />,
    auditlog:  <AuditLogModule logs={auditLogs} />,
    notifs:    <Notifs  data={data} setData={setData} />,
  };

  return (
    <div style={{ background:'#F5F5F3', minHeight:'100vh' }}>
      <TopBar admin={admin} mod={mod} onMenu={()=>setSideOpen(!sideOpen)} notifCount={badges.ntf} setMod={setMod} onSync={syncAllData} syncing={syncing} onSyncCheck={runSyncCheck} />
      <Sidebar active={mod} setActive={setMod} onLogout={logout} open={sideOpen} setOpen={setSideOpen} badges={badges} />



      <div className="admin-content" style={{ marginLeft:0, paddingTop:58, minHeight:'100vh' }}>
        <div style={{ maxWidth:1200, margin:'0 auto', padding:'24px 16px 80px' }}>
          {mods[mod] || <div style={{ textAlign:'center', padding:48, color:'#969696' }}>Coming soon</div>}
        </div>
      </div>

      {/* ── Sync Check Modal ──────────────────────────────────── */}
      {syncModal && (
        <div onClick={()=>{setSyncModal(false);setSyncResults(null);}} style={{ position:'fixed', inset:0, background:'rgba(20,20,19,0.55)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:3000, padding:16 }}>
          <div onClick={e=>e.stopPropagation()} style={{ background:'#fff', borderRadius:20, width:'100%', maxWidth:500, maxHeight:'88vh', display:'flex', flexDirection:'column', boxShadow:'0 20px 60px rgba(20,20,19,0.25)', overflow:'hidden' }}>
            <div style={{ padding:'18px 22px 14px', borderBottom:'1px solid rgba(20,20,19,0.08)', display:'flex', justifyContent:'space-between', alignItems:'center', background:'#141413' }}>
              <div style={{ fontWeight:800, fontSize:16, color:'#fff' }}>🩺 Synchronization Status Check</div>
              <button onClick={()=>{setSyncModal(false);setSyncResults(null);}} style={{ background:'none', border:'none', fontSize:22, cursor:'pointer', color:'rgba(255,255,255,0.5)', lineHeight:1 }}>×</button>
            </div>
            <div style={{ padding:'20px 22px', overflowY:'auto', flex:1 }}>
              {!syncResults ? (
                <div style={{ textAlign:'center', padding:'32px 0' }}>
                  <div style={{ fontSize:32, marginBottom:12, animation:'crSpin 1s linear infinite', display:'inline-block' }}>🔄</div>
                  <div style={{ color:'#696969', fontWeight:600 }}>Pinging all system components…</div>
                </div>
              ) : (
                <div>
                  <div style={{ marginBottom:16, padding:'10px 14px', borderRadius:10, background: syncResults.every(r=>r.ok) ? '#D1FAE5' : '#FEF3C7', border:`1px solid ${syncResults.every(r=>r.ok) ? '#6EE7B7' : '#FCD34D'}` }}>
                    <span style={{ fontWeight:700, fontSize:13, color: syncResults.every(r=>r.ok) ? '#065F46' : '#92400E' }}>
                      {syncResults.every(r=>r.ok)
                        ? `✅ All ${syncResults.length} endpoints responding — system fully synchronized`
                        : `⚠️ ${syncResults.filter(r=>!r.ok).length} endpoint(s) not responding — check below`}
                    </span>
                  </div>
                  <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                    {syncResults.map((r, i) => (
                      <div key={i} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 14px', borderRadius:10, background: r.ok ? '#F0FDF4' : '#FFF1F2', border:`1px solid ${r.ok ? '#BBF7D0' : '#FECDD3'}` }}>
                        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                          <span style={{ fontSize:16 }}>{r.ok ? '✅' : '❌'}</span>
                          <span style={{ fontWeight:600, fontSize:13, color:'#141413' }}>{r.label}</span>
                        </div>
                        <div style={{ display:'flex', gap:10, alignItems:'center' }}>
                          <span style={{ fontSize:11, color:'#969696', fontFamily:'monospace' }}>{r.ms}ms</span>
                          <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:20, background: r.ok ? '#D1FAE5' : '#FEE2E2', color: r.ok ? '#065F46' : '#DC2626' }}>
                            {r.status}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div style={{ marginTop:16, display:'flex', gap:10 }}>
                    <button
                      onClick={()=>{setSyncResults(null); runSyncCheck();}}
                      style={{ ...BTN, flex:1, background:'#F5F5F3', color:'#141413', padding:'11px 0', fontSize:13 }}
                    >↻ Re-run Check</button>
                    <button
                      onClick={async ()=>{ setSyncResults(null); await runSyncCheck(); await syncAllData(); }}
                      style={{ ...BTN, flex:2, background:'#7C3AED', color:'#fff', padding:'11px 0', fontSize:13 }}
                    >🔄 Run Check + Sync All Data</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Detail Modal */}
      {detail && (
        <Modal title={`${detail.type} Detail`} onClose={()=>setDetail(null)}>
          <CmsBadge status={detail.data.status} />
          <div style={{ marginTop:14 }}>
            {Object.entries(detail.data).filter(([k])=>!['id','img'].includes(k)).map(([k,v])=>(
              <div key={k} style={{ display:'flex', justifyContent:'space-between', padding:'8px 0', borderBottom:'1px solid rgba(20,20,19,0.06)', fontSize:14 }}>
                <span style={{ color:'#696969', textTransform:'capitalize' }}>{k.replace(/_/g,' ')}</span>
                <span style={{ fontWeight:600, color:'#141413', textAlign:'right', maxWidth:'55%', wordBreak:'break-word' }}>{Array.isArray(v)?v.join(', '):String(v)}</span>
              </div>
            ))}
          </div>
        </Modal>
      )}

      <style>{`
        @media(min-width:900px){
          .admin-sidebar-always{left:0!important;box-shadow:none!important;}
          .admin-content{margin-left:240px!important;}
          .admin-menu-btn{display:none!important;}
        }
        @media(max-width:899px){
          .admin-menu-btn{display:flex!important;}
        }
        @media(max-width:480px){
          .admin-name-hide{display:none;}
        }
        @keyframes crSpin {
          from { transform: rotate(0deg); }
          to   { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { AdminPage });
