import { BrowserRouter, Routes, Route, Navigate, NavLink, useNavigate, Outlet, useParams } from 'react-router-dom'
import { useState, useEffect, useRef } from 'react'
import { createClient } from '@supabase/supabase-js'
import { BrowserMultiFormatReader } from '@zxing/browser'
import type { IScannerControls } from '@zxing/browser'
import { BarcodeFormat, DecodeHintType } from '@zxing/library'

const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_ANON_KEY
)

// ── AUTH CONTEXT ─────────────────────────────────────────────
function useAuth() {
  const [user, setUser] = useState<any>(null)
  const [dealer, setDealer] = useState<any>(null)
  const [isAdmin, setIsAdmin] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // Handle password reset token in URL hash
    const hash = window.location.hash
    if (hash && (hash.includes('type=recovery') || hash.includes('access_token'))) {
      supabase.auth.getSession().then(({ data: { session } }) => {
        if (session) window.location.href = '/reset-password'
      })
      return
    }

    supabase.auth.getSession().then(({ data: { session } }) => {
      setUser(session?.user ?? null)
      if (session?.user) loadDealer(session.user.id)
      else setLoading(false)
    })
    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
      setUser(session?.user ?? null)
      if (session?.user) loadDealer(session.user.id)
      else { setDealer(null); setIsAdmin(false); setLoading(false) }
    })
    return () => subscription.unsubscribe()
  }, [])

  async function loadDealer(userId: string) {
    try {
      // Check if user is admin first
      const { data: userData, error: roleError } = await supabase.from('users').select('role').eq('id', userId).maybeSingle()
      if (roleError) console.error('Role lookup error in loadDealer:', roleError)
      if (userData?.role === 'admin') {
        setIsAdmin(true)
        setDealer(null)
        setLoading(false)
        return
      }
      setIsAdmin(false)
      const { data, error } = await supabase.from('dealers').select('*').eq('user_id', userId).maybeSingle()
      if (error) console.error('Dealer load error:', error)
      setDealer(data || null)
    } catch (e) {
      console.error('Dealer load failed:', e)
      setDealer(null)
    }
    setLoading(false)
  }

  return { user, dealer, isAdmin, loading, refreshDealer: () => user && loadDealer(user.id) }
}

// ── LAYOUT ───────────────────────────────────────────────────

// ── NOTIFICATION BELL ────────────────────────────────────────
function NotificationBell({ dealer }: { dealer: any }) {
  const [notifications, setNotifications] = useState<any[]>([])
  const [open, setOpen] = useState(false)
  const navigate = useNavigate()

  useEffect(() => {
    if (!dealer?.id) return
    loadNotifications()
    // Poll every 30 seconds for new notifications
    const interval = setInterval(loadNotifications, 30000)
    return () => clearInterval(interval)
  }, [dealer?.id])

  async function loadNotifications() {
    const { data } = await supabase
      .from('notifications')
      .select('*')
      .eq('dealer_id', dealer.id)
      .order('created_at', { ascending: false })
      .limit(20)
    setNotifications(data || [])
  }

  async function markAllRead() {
    await supabase
      .from('notifications')
      .update({ is_read: true })
      .eq('dealer_id', dealer.id)
      .eq('is_read', false)
    loadNotifications()
  }

  async function markRead(id: string) {
    await supabase.from('notifications').update({ is_read: true }).eq('id', id)
    setNotifications(prev => prev.map(n => n.id === id ? { ...n, is_read: true } : n))
  }

  const unread = notifications.filter(n => !n.is_read).length

  const iconMap: Record<string, string> = {
    new_offer: 'ti-tag',
    offer_accepted: 'ti-circle-check',
    offer_declined: 'ti-circle-x',
    new_sell_request: 'ti-car',
    new_message: 'ti-message',
    counter_offer: 'ti-arrows-exchange',
  }

  const colorMap: Record<string, string> = {
    new_offer: 'var(--green-600)',
    offer_accepted: 'var(--green-600)',
    offer_declined: '#C53030',
    new_sell_request: '#854F0B',
    new_message: '#1A4FA8',
    counter_offer: '#854F0B',
  }

  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)} style={{ position: 'relative', background: 'rgba(255,255,255,.1)', border: '1px solid rgba(255,255,255,.15)', borderRadius: 8, width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#fff' }}>
        <i className="ti ti-bell" style={{ fontSize: 16 }} />
        {unread > 0 && (
          <div style={{ position: 'absolute', top: -4, right: -4, width: 18, height: 18, background: '#E31837', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: '#fff', border: '2px solid var(--green-900)' }}>
            {unread > 9 ? '9+' : unread}
          </div>
        )}
      </button>

      {open && (
        <>
          {/* Backdrop */}
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 150 }} />
          {/* Dropdown */}
          <div style={{ position: 'absolute', top: 44, right: 0, width: 340, background: '#fff', borderRadius: 14, border: '1px solid var(--ink-100)', boxShadow: '0 8px 32px rgba(0,0,0,.12)', zIndex: 200, overflow: 'hidden' }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', borderBottom: '1px solid var(--ink-50)' }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>
                Notifications {unread > 0 && <span style={{ fontSize: 11, background: '#E31837', color: '#fff', borderRadius: 10, padding: '1px 6px', marginLeft: 6 }}>{unread}</span>}
              </div>
              {unread > 0 && (
                <button onClick={markAllRead} style={{ fontSize: 11, color: 'var(--green-600)', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>Mark all read</button>
              )}
            </div>

            {/* Notifications list */}
            <div style={{ maxHeight: 380, overflowY: 'auto' }}>
              {notifications.length === 0 ? (
                <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--ink-300)' }}>
                  <i className="ti ti-bell-off" style={{ fontSize: 28, display: 'block', marginBottom: 8 }} />
                  <div style={{ fontSize: 13 }}>No notifications yet</div>
                </div>
              ) : (
                notifications.map(n => (
                  <div key={n.id} onClick={async () => { await markRead(n.id); setOpen(false); if (n.link) navigate(n.link) }}
                    style={{ display: 'flex', gap: 12, padding: '12px 16px', borderBottom: '1px solid var(--ink-50)', cursor: 'pointer', background: n.is_read ? '#fff' : 'var(--green-50)', transition: 'background .15s' }}
                    onMouseEnter={e => (e.currentTarget.style.background = 'var(--ink-20)')}
                    onMouseLeave={e => (e.currentTarget.style.background = n.is_read ? '#fff' : 'var(--green-50)')}>
                    <div style={{ width: 34, height: 34, borderRadius: 8, background: n.is_read ? 'var(--ink-50)' : 'var(--green-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <i className={`ti ${iconMap[n.type] || 'ti-bell'}`} style={{ fontSize: 16, color: n.is_read ? 'var(--ink-400)' : colorMap[n.type] || 'var(--green-600)' }} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: n.is_read ? 400 : 600, color: 'var(--ink-900)', marginBottom: 2 }}>{n.title}</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-400)', lineHeight: 1.4 }}>{n.body}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-300)', marginTop: 4 }}>
                        {new Date(n.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })}
                      </div>
                    </div>
                    {!n.is_read && <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--green-500)', marginTop: 4, flexShrink: 0 }} />}
                  </div>
                ))
              )}
            </div>

            {/* Footer */}
            <div style={{ padding: '10px 16px', borderTop: '1px solid var(--ink-50)', textAlign: 'center' }}>
              <button onClick={() => { setOpen(false); navigate('/dealer/dashboard') }} style={{ fontSize: 12, color: 'var(--green-600)', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500 }}>
                Go to dashboard →
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  )
}

function Layout() {
  const navigate = useNavigate()
  const { user, dealer, loading } = useAuth()
  const [menuOpen, setMenuOpen] = useState(false)

  async function handleSignOut() {
    await supabase.auth.signOut()
    setMenuOpen(false)
    navigate('/')
  }

  const navLinks = [
    { to: '/', label: 'Value a car', end: true },
    { to: '/market', label: 'Market prices', end: false },
    { to: '/sell', label: 'Sell my car', end: false },
    { to: '/dealer', label: 'Dealer portal', end: false },
  ]

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <nav style={{ position: 'sticky', top: 0, zIndex: 100, background: 'var(--green-900)', borderBottom: '1px solid var(--green-800)', padding: '0 20px', height: 60, display: 'flex', alignItems: 'center' }}>
        {/* Logo */}
        <div onClick={() => navigate('/')} style={{ display: 'flex', alignItems: 'center', gap: 10, marginRight: 32, cursor: 'pointer', flexShrink: 0 }}>
          {/* K icon mark */}
          <div style={{ width: 34, height: 34, background: 'var(--green-400)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <span style={{ fontFamily: '"DM Serif Display",serif', fontSize: 20, color: 'var(--green-900)', lineHeight: 1 }}>K</span>
          </div>
          {/* Wordmark + tagline */}
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 1 }}>
            <span style={{ fontFamily: '"DM Serif Display",serif', fontSize: 19, color: '#fff', lineHeight: 1 }}>
              Kenya<span style={{ color: 'var(--green-300)' }}>VIN</span>
            </span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                <circle cx="6" cy="6" r="5" stroke="#1DB386" strokeWidth="1"/>
                <path d="M3.5 6L5 7.5L8.5 4" stroke="#1DB386" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <span style={{ fontFamily: '"DM Sans",sans-serif', fontSize: 8, color: 'rgba(255,255,255,0.35)', letterSpacing: '1.8px', textTransform: 'uppercase' as const, lineHeight: 1 }}>Kenya's car valuation guide</span>
            </div>
          </div>
        </div>

        {/* Desktop nav links */}
        <div className="nav-links">
          {navLinks.map(({ to, label, end }) => (
            <NavLink key={to} to={to} end={end} style={({ isActive }) => ({ padding: '8px 12px', fontSize: 13.5, fontWeight: 500, color: isActive ? 'var(--green-300)' : 'rgba(255,255,255,0.65)', borderRadius: 6, textDecoration: 'none' })}>{label}</NavLink>
          ))}
        </div>

        {/* Desktop auth */}
        <div className="nav-cta" style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          {!loading && (user ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {dealer && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', background: 'rgba(29,179,134,.15)', borderRadius: 20, border: '1px solid rgba(77,204,163,.3)' }}>
                  <i className="ti ti-shield-check" style={{ fontSize: 12, color: 'var(--green-300)' }} />
                  <span style={{ fontSize: 11, color: 'var(--green-300)', fontWeight: 500, maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const }}>{dealer.business_name}</span>
                </div>
              )}
              {dealer && <NotificationBell dealer={dealer} />}
              <button onClick={handleSignOut} style={{ padding: '6px 12px', background: 'rgba(255,255,255,.1)', color: '#fff', border: '1px solid rgba(255,255,255,.2)', borderRadius: 6, fontSize: 12, cursor: 'pointer' }}>Sign out</button>
            </div>
          ) : (
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => navigate('/dealer/login')} style={{ padding: '6px 12px', background: 'transparent', color: 'rgba(255,255,255,.7)', border: '1px solid rgba(255,255,255,.2)', borderRadius: 6, fontSize: 12, cursor: 'pointer' }}>Sign in</button>
              <button onClick={() => navigate('/dealer')} style={{ padding: '6px 14px', background: 'var(--green-400)', color: 'var(--green-900)', border: 'none', borderRadius: 6, fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Dealer portal</button>
            </div>
          ))}
        </div>

        {/* Hamburger */}
        <button className="hamburger" onClick={() => setMenuOpen(!menuOpen)} style={{ marginLeft: 'auto' }} aria-label="Menu">
          <span style={{ transform: menuOpen ? 'rotate(45deg) translate(5px, 5px)' : 'none' }} />
          <span style={{ opacity: menuOpen ? 0 : 1 }} />
          <span style={{ transform: menuOpen ? 'rotate(-45deg) translate(5px, -5px)' : 'none' }} />
        </button>
      </nav>

      {/* Mobile menu */}
      <div className={`mobile-menu ${menuOpen ? 'open' : ''}`}>
        <button onClick={() => setMenuOpen(false)} style={{ position: 'absolute', top: 16, right: 20, background: 'rgba(255,255,255,.1)', border: 'none', color: '#fff', fontSize: 22, cursor: 'pointer', width: 36, height: 36, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
        {navLinks.map(({ to, label }) => (
          <NavLink key={to} to={to} onClick={() => setMenuOpen(false)} style={{ padding: '14px 16px', fontSize: 16, color: 'rgba(255,255,255,.8)', borderRadius: 10, display: 'block', fontWeight: 500 }}>{label}</NavLink>
        ))}
        <div style={{ borderTop: '1px solid rgba(255,255,255,.1)', marginTop: 8, paddingTop: 16 }}>
          {user ? (
            <>
              {dealer && <div style={{ padding: '8px 16px', fontSize: 13, color: 'var(--green-300)', fontWeight: 500 }}>{dealer.business_name}</div>}
              <button onClick={handleSignOut} style={{ padding: '14px 16px', fontSize: 16, color: 'rgba(255,255,255,.8)', background: 'none', border: 'none', borderRadius: 10, cursor: 'pointer', textAlign: 'left', width: '100%' }}>Sign out</button>
            </>
          ) : (
            <>
              <NavLink to="/dealer/login" onClick={() => setMenuOpen(false)} style={{ padding: '14px 16px', fontSize: 16, color: 'rgba(255,255,255,.8)', borderRadius: 10, display: 'block' }}>Sign in</NavLink>
            </>
          )}
        </div>
      </div>

      <main style={{ flex: 1 }}><Outlet /></main>
      <footer style={{ background: 'var(--green-900)', padding: '20px 16px', textAlign: 'center', fontSize: 12, color: 'rgba(255,255,255,0.3)' }}>
        © {new Date().getFullYear()} KenyaVIN · Kenya's trusted car valuation platform
      </footer>
    </div>
  )
}


// ── VEHICLE INSPECTION ───────────────────────────────────────
const INSPECTION_ANGLES = [
  { key: 'front',        label: 'Front',         icon: 'ti-car',           hint: 'Face the front of the car' },
  { key: 'rear',         label: 'Rear',           icon: 'ti-car',           hint: 'Face the rear/boot' },
  { key: 'driver_side',  label: 'Driver side',    icon: 'ti-car',           hint: 'Full left side of car' },
  { key: 'passenger',    label: 'Passenger side', icon: 'ti-car',           hint: 'Full right side of car' },
  { key: 'interior',     label: 'Interior',       icon: 'ti-steering-wheel', hint: 'Dashboard and seats' },
  { key: 'engine',       label: 'Engine bay',     icon: 'ti-engine',        hint: 'Open the bonnet' },
  { key: 'odometer',     label: 'Odometer',       icon: 'ti-gauge',         hint: 'Close-up of the mileage' },
]

interface InspectionPhoto {
  angle: string
  label: string
  file: File
  preview: string
  analysis?: string
  score?: number
  loading?: boolean
}

interface InspectionReport {
  photos: InspectionPhoto[]
  overallScore: number
  condition: string
  summary: string
  issues: string[]
  positives: string[]
}

function VehicleInspection({ onComplete, onSkip }: { onComplete: (report: InspectionReport) => void, onSkip: () => void }) {
  const [photos, setPhotos] = useState<Record<string, InspectionPhoto>>({})
  const [_analysing, setAnalysing] = useState(false)
  const [step, setStep] = useState<'capture' | 'analysing' | 'report'>('capture')
  const [report, setReport] = useState<InspectionReport | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [activeAngle, setActiveAngle] = useState<string | null>(null)
  const cameraRef = useRef<HTMLVideoElement>(null)
  const [cameraStream, setCameraStream] = useState<MediaStream | null>(null)
  const [showCamera, setShowCamera] = useState(false)

  const capturedCount = Object.keys(photos).length

  async function openCamera(angleKey: string) {
    setActiveAngle(angleKey)
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
      setCameraStream(stream)
      setShowCamera(true)
      setTimeout(() => { if (cameraRef.current) cameraRef.current.srcObject = stream }, 100)
    } catch {
      // Camera not available - fall back to file upload
      setActiveAngle(angleKey)
      fileInputRef.current?.click()
    }
  }

  async function captureFromCamera() {
    if (!cameraRef.current || !activeAngle) return
    const canvas = document.createElement('canvas')
    canvas.width = cameraRef.current.videoWidth
    canvas.height = cameraRef.current.videoHeight
    canvas.getContext('2d')?.drawImage(cameraRef.current, 0, 0)
    canvas.toBlob(blob => {
      if (!blob) return
      const file = new File([blob], `${activeAngle}.jpg`, { type: 'image/jpeg' })
      const preview = URL.createObjectURL(blob)
      const angle = INSPECTION_ANGLES.find(a => a.key === activeAngle)!
      setPhotos(p => ({ ...p, [activeAngle]: { angle: activeAngle, label: angle.label, file, preview } }))
      closeCamera()
    }, 'image/jpeg', 0.85)
  }

  function closeCamera() {
    cameraStream?.getTracks().forEach(t => t.stop())
    setCameraStream(null)
    setShowCamera(false)
    setActiveAngle(null)
  }

  function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file || !activeAngle) return
    const preview = URL.createObjectURL(file)
    const angle = INSPECTION_ANGLES.find(a => a.key === activeAngle)!
    setPhotos(p => ({ ...p, [activeAngle]: { angle: activeAngle, label: angle.label, file, preview } }))
    setActiveAngle(null)
    e.target.value = ''
  }

  function openFileUpload(angleKey: string) {
    setActiveAngle(angleKey)
    fileInputRef.current?.click()
  }

  async function analysePhotos() {
    setAnalysing(true)
    setStep('analysing')

    const analysedPhotos: InspectionPhoto[] = []
    
    for (const photo of Object.values(photos)) {
      try {
        // Convert to base64
        const base64 = await new Promise<string>((res) => {
          const reader = new FileReader()
          reader.onload = () => res((reader.result as string).split(',')[1])
          reader.readAsDataURL(photo.file)
        })

        const response = await fetch(
          `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/analyse-photo`,
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${import.meta.env.VITE_SUPABASE_ANON_KEY}`,
              'apikey': import.meta.env.VITE_SUPABASE_ANON_KEY,
            },
            body: JSON.stringify({
              image: base64,
              mediaType: photo.file.type,
              angle: photo.label,
            })
          }
        )

        const parsed = await response.json()
        
        analysedPhotos.push({
          ...photo,
          score: parsed.score,
          analysis: parsed.summary,
        })
      } catch {
        analysedPhotos.push({ ...photo, score: 70, analysis: 'Analysis unavailable' })
      }
    }

    // Generate overall report
    const avgScore = Math.round(analysedPhotos.reduce((s, p) => s + (p.score || 70), 0) / analysedPhotos.length)
    const condition = avgScore >= 90 ? 'excellent' : avgScore >= 70 ? 'good' : avgScore >= 50 ? 'fair' : 'poor'

    const finalReport: InspectionReport = {
      photos: analysedPhotos,
      overallScore: avgScore,
      condition,
      summary: `Vehicle inspected across ${analysedPhotos.length} angles. Overall condition rated ${condition} with a score of ${avgScore}/100.`,
      issues: analysedPhotos.flatMap(_p => []).filter(Boolean),
      positives: [],
    }

    setReport(finalReport)
    setStep('report')
    setAnalysing(false)
  }

  if (showCamera) return (
    <div style={{ position: 'fixed', inset: 0, background: '#000', zIndex: 999, display: 'flex', flexDirection: 'column' as const }}>
      <div style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ color: '#fff', fontSize: 14, fontWeight: 500 }}>
          {INSPECTION_ANGLES.find(a => a.key === activeAngle)?.label} — {INSPECTION_ANGLES.find(a => a.key === activeAngle)?.hint}
        </div>
        <button onClick={closeCamera} style={{ background: 'rgba(255,255,255,.2)', border: 'none', borderRadius: 8, padding: '6px 12px', color: '#fff', cursor: 'pointer', fontSize: 13 }}>Cancel</button>
      </div>
      <video ref={cameraRef} autoPlay playsInline style={{ flex: 1, objectFit: 'cover' as const }} />
      <div style={{ padding: 24, display: 'flex', justifyContent: 'center', gap: 16 }}>
        <button onClick={captureFromCamera} style={{ width: 72, height: 72, borderRadius: '50%', background: '#fff', border: '4px solid rgba(255,255,255,.4)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <i className="ti ti-camera" style={{ fontSize: 28, color: '#000' }} />
        </button>
      </div>
    </div>
  )

  if (step === 'analysing') return (
    <div style={{ background: '#fff', borderRadius: 20, padding: 40, textAlign: 'center', border: '1px solid var(--ink-100)' }}>
      <div style={{ width: 64, height: 64, background: 'var(--green-50)', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
        <i className="ti ti-brain" style={{ fontSize: 28, color: 'var(--green-600)' }} />
      </div>
      <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, color: 'var(--ink-900)', marginBottom: 8 }}>Analysing your vehicle…</div>
      <p style={{ fontSize: 14, color: 'var(--ink-400)', marginBottom: 24 }}>Inspecting each photo for damage, wear, and condition issues.</p>
      <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 8, maxWidth: 320, margin: '0 auto' }}>
        {Object.values(photos).map((p) => (
          <div key={p.angle} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px', background: 'var(--ink-20)', borderRadius: 8, fontSize: 13 }}>
            <i className="ti ti-loader-2" style={{ color: 'var(--green-500)', fontSize: 15 }} />
            <span style={{ color: 'var(--ink-600)' }}>Analysing {p.label}…</span>
          </div>
        ))}
      </div>
    </div>
  )

  if (step === 'report' && report) return (
    <div style={{ background: '#fff', borderRadius: 20, border: '1px solid var(--ink-100)', overflow: 'hidden' }}>
      {/* Report header */}
      <div style={{ background: 'linear-gradient(135deg, var(--green-900), var(--green-700))', padding: '28px 28px 24px', color: '#fff' }}>
        <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--green-300)', marginBottom: 6 }}>Inspection Report</div>
        <div style={{ fontFamily: '"DM Serif Display"', fontSize: 26, marginBottom: 4 }}>Condition: {report.condition.charAt(0).toUpperCase() + report.condition.slice(1)}</div>
        <div style={{ fontSize: 14, color: 'rgba(255,255,255,.7)', marginBottom: 20 }}>{report.photos.length} angles inspected</div>
        {/* Score bar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ flex: 1, height: 10, background: 'rgba(255,255,255,.2)', borderRadius: 5, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${report.overallScore}%`, background: 'var(--green-400)', borderRadius: 5, transition: 'width 1s ease' }} />
          </div>
          <div style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: '#fff', minWidth: 60 }}>{report.overallScore}<span style={{ fontSize: 14, color: 'rgba(255,255,255,.5)' }}>/100</span></div>
        </div>
      </div>

      {/* Photo grid */}
      <div style={{ padding: 24 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 14 }}>Photo analysis</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 24 }}>
          {report.photos.map(p => (
            <div key={p.angle} style={{ borderRadius: 12, overflow: 'hidden', border: '1px solid var(--ink-100)' }}>
              <img src={p.preview} alt={p.label} style={{ width: '100%', height: 120, objectFit: 'cover' as const }} />
              <div style={{ padding: '8px 10px' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 3 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-700)' }}>{p.label}</span>
                  <span style={{ fontSize: 11, fontWeight: 700, color: (p.score || 0) >= 70 ? 'var(--green-700)' : (p.score || 0) >= 50 ? '#854F0B' : '#791F1F' }}>{p.score}/100</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.4 }}>{p.analysis}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={() => onComplete(report)} className="btn-primary" style={{ flex: 1, justifyContent: 'center', padding: '12px' }}>
            <i className="ti ti-check" /> Use this inspection report
          </button>
          <button onClick={() => setStep('capture')} className="btn-secondary" style={{ padding: '12px 16px' }}>
            Retake photos
          </button>
        </div>
      </div>
    </div>
  )

  // Capture step
  return (
    <div style={{ background: '#fff', borderRadius: 20, border: '1px solid var(--ink-100)', padding: 24 }}>
      <input ref={fileInputRef} type="file" accept="image/*" capture="environment" style={{ display: 'none' }} onChange={handleFileUpload} />
      
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
        <div style={{ fontFamily: '"DM Serif Display"', fontSize: 20, color: 'var(--ink-900)' }}>Vehicle inspection</div>
        <button onClick={onSkip} style={{ background: 'none', border: 'none', fontSize: 13, color: 'var(--ink-400)', cursor: 'pointer' }}>Skip for now</button>
      </div>
      <p style={{ fontSize: 13, color: 'var(--ink-400)', marginBottom: 20, lineHeight: 1.5 }}>
        Take photos from each angle for a detailed condition report. This improves your valuation accuracy.
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 20 }}>
        {INSPECTION_ANGLES.map(angle => {
          const photo = photos[angle.key]
          return (
            <div key={angle.key} style={{ position: 'relative' as const }}>
              <div
                onClick={() => !photo && openCamera(angle.key)}
                style={{
                  aspectRatio: '4/3',
                  borderRadius: 10,
                  border: `2px ${photo ? 'solid var(--green-400)' : 'dashed var(--ink-200)'}`,
                  background: photo ? 'none' : 'var(--ink-20)',
                  display: 'flex', flexDirection: 'column' as const, alignItems: 'center', justifyContent: 'center',
                  cursor: photo ? 'default' : 'pointer',
                  overflow: 'hidden',
                  transition: 'border-color .15s',
                }}>
                {photo ? (
                  <>
                    <img src={photo.preview} alt={angle.label} style={{ width: '100%', height: '100%', objectFit: 'cover' as const }} />
                    <div style={{ position: 'absolute' as const, top: 5, right: 5, width: 22, height: 22, borderRadius: '50%', background: 'var(--green-500)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <i className="ti ti-check" style={{ fontSize: 12, color: '#fff' }} />
                    </div>
                  </>
                ) : (
                  <>
                    <i className={`ti ${angle.icon}`} style={{ fontSize: 22, color: 'var(--ink-300)', marginBottom: 4 }} />
                    <span style={{ fontSize: 10, color: 'var(--ink-400)', textAlign: 'center' as const, fontWeight: 500 }}>{angle.label}</span>
                  </>
                )}
              </div>
              {photo && (
                <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
                  <button onClick={() => openCamera(angle.key)} style={{ flex: 1, padding: '3px 0', border: '1px solid var(--ink-100)', borderRadius: 6, fontSize: 10, cursor: 'pointer', background: '#fff', color: 'var(--ink-500)' }}>Retake</button>
                  <button onClick={() => openFileUpload(angle.key)} style={{ flex: 1, padding: '3px 0', border: '1px solid var(--ink-100)', borderRadius: 6, fontSize: 10, cursor: 'pointer', background: '#fff', color: 'var(--ink-500)' }}>Upload</button>
                </div>
              )}
              {!photo && (
                <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
                  <button onClick={() => openCamera(angle.key)} style={{ flex: 1, padding: '3px 0', border: '1px solid var(--ink-100)', borderRadius: 6, fontSize: 10, cursor: 'pointer', background: '#fff', color: 'var(--ink-500)' }}>
                    <i className="ti ti-camera" style={{ fontSize: 10 }} />
                  </button>
                  <button onClick={() => openFileUpload(angle.key)} style={{ flex: 1, padding: '3px 0', border: '1px solid var(--ink-100)', borderRadius: 6, fontSize: 10, cursor: 'pointer', background: '#fff', color: 'var(--ink-500)' }}>
                    <i className="ti ti-upload" style={{ fontSize: 10 }} />
                  </button>
                </div>
              )}
            </div>
          )
        })}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ fontSize: 13, color: 'var(--ink-400)' }}>
          <span style={{ fontWeight: 600, color: capturedCount >= 4 ? 'var(--green-700)' : 'var(--ink-700)' }}>{capturedCount}</span> of {INSPECTION_ANGLES.length} photos taken
          {capturedCount >= 4 && <span style={{ color: 'var(--green-600)', marginLeft: 8 }}>✓ Ready to analyse</span>}
        </div>
      </div>

      <button
        onClick={analysePhotos}
        disabled={capturedCount < 1}
        className="btn-primary"
        style={{ width: '100%', justifyContent: 'center', padding: '13px', fontSize: 14, opacity: capturedCount < 1 ? 0.5 : 1, cursor: capturedCount < 1 ? 'not-allowed' : 'pointer' }}>
        <i className="ti ti-brain" /> Analyse photos ({capturedCount} photo{capturedCount !== 1 ? 's' : ''})
      </button>
    </div>
  )
}

// ── VALUATION PAGE ───────────────────────────────────────────
function ValuationPage() {
  const [vin, setVin] = useState('')
  const [scanning, setScanning] = useState(false)
  const videoRef = useRef<HTMLVideoElement>(null)
  const scannerControlsRef = useRef<IScannerControls | null>(null)
  const [mileage, setMileage] = useState('')
  const [location, setLocation] = useState('Nairobi')
  const [condition, setCondition] = useState('good')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState(false)
  const [currentStep, setCurrentStep] = useState(-1)
  const [vehicleData, setVehicleData] = useState<any>(null)
  const [error, setError] = useState('')
  const [manualMake, setManualMake] = useState('')
  const [manualModel, setManualModel] = useState('')
  const [manualYear, setManualYear] = useState('')
  const [showInspection, setShowInspection] = useState(false)
  const [inspectionReport, setInspectionReport] = useState<any>(null)

  const conditions = [
    { value: 'excellent', label: 'Excellent', icon: 'ti-circle-check', color: 'var(--green-500)' },
    { value: 'good', label: 'Good', icon: 'ti-thumb-up', color: 'var(--green-400)' },
    { value: 'fair', label: 'Fair', icon: 'ti-tool', color: '#E07B00' },
    { value: 'poor', label: 'Poor', icon: 'ti-alert-triangle', color: '#C53030' },
  ]

  const steps = ['Decoding vehicle details', 'Checking import & registration records', 'Scanning market listings', 'Computing valuation']


  // WMI (first 3 chars of VIN) lookup for common Kenyan imports
  function lookupWMI(vin: string): { make: string, country: string, modelFamily?: string } | null {
    if (vin.length < 3) return null
    const wmi = vin.substring(0, 3).toUpperCase()
    const wmiMap: Record<string, { make: string, country: string, modelFamily?: string }> = {
      // Mercedes-Benz Germany
      'WDC': { make: 'Mercedes-Benz', country: 'Germany', modelFamily: 'GL/ML/GLE Class SUV' },
      'WDB': { make: 'Mercedes-Benz', country: 'Germany', modelFamily: 'C/E/S Class' },
      'WDD': { make: 'Mercedes-Benz', country: 'Germany' },
      'WD1': { make: 'Mercedes-Benz', country: 'Germany', modelFamily: 'Sprinter Van' },
      // BMW Germany
      'WBA': { make: 'BMW', country: 'Germany', modelFamily: '3/5 Series' },
      'WBS': { make: 'BMW', country: 'Germany', modelFamily: 'M Series' },
      'WBX': { make: 'BMW', country: 'Germany', modelFamily: 'X Series SUV' },
      'WBY': { make: 'BMW', country: 'Germany', modelFamily: 'i Series' },
      // Volkswagen Germany
      'WVW': { make: 'Volkswagen', country: 'Germany' },
      'WV1': { make: 'Volkswagen', country: 'Germany', modelFamily: 'Transporter' },
      'WV2': { make: 'Volkswagen', country: 'Germany', modelFamily: 'Transporter' },
      // Audi Germany
      'WAU': { make: 'Audi', country: 'Germany' },
      'WA1': { make: 'Audi', country: 'Germany', modelFamily: 'Q Series SUV' },
      // Porsche Germany
      'WP0': { make: 'Porsche', country: 'Germany' },
      'WP1': { make: 'Porsche', country: 'Germany', modelFamily: 'Cayenne SUV' },
      // Volvo Sweden
      'YV1': { make: 'Volvo', country: 'Sweden' },
      'YV4': { make: 'Volvo', country: 'Sweden', modelFamily: 'XC Series SUV' },
      // Toyota Japan
      'JTM': { make: 'Toyota', country: 'Japan', modelFamily: 'RAV4' },
      'JTJ': { make: 'Toyota', country: 'Japan', modelFamily: 'Land Cruiser Prado' },
      'JTE': { make: 'Toyota', country: 'Japan', modelFamily: 'Land Cruiser' },
      'JTN': { make: 'Toyota', country: 'Japan', modelFamily: 'Hilux' },
      'JT2': { make: 'Toyota', country: 'Japan' },
      'JT3': { make: 'Toyota', country: 'Japan', modelFamily: 'Land Cruiser' },
      'JT4': { make: 'Toyota', country: 'Japan', modelFamily: 'Truck' },
      'JTD': { make: 'Toyota', country: 'Japan', modelFamily: 'Corolla/Camry' },
      'JTK': { make: 'Toyota', country: 'Japan' },
      'JTL': { make: 'Toyota', country: 'Japan' },
      // Nissan Japan
      'JN1': { make: 'Nissan', country: 'Japan' },
      'JN8': { make: 'Nissan', country: 'Japan', modelFamily: 'SUV/Pathfinder' },
      'JNA': { make: 'Nissan', country: 'Japan', modelFamily: 'Murano/X-Trail' },
      'JNK': { make: 'Nissan', country: 'Japan', modelFamily: 'Infinity' },
      // Honda Japan
      'JHM': { make: 'Honda', country: 'Japan' },
      'JH4': { make: 'Acura/Honda', country: 'Japan' },
      'JHL': { make: 'Honda', country: 'Japan', modelFamily: 'CR-V/Pilot SUV' },
      // Subaru Japan
      'JF1': { make: 'Subaru', country: 'Japan' },
      'JF2': { make: 'Subaru', country: 'Japan' },
      // Mazda Japan
      'JM1': { make: 'Mazda', country: 'Japan' },
      'JM3': { make: 'Mazda', country: 'Japan', modelFamily: 'CX Series SUV' },
      // Mitsubishi Japan
      'JA3': { make: 'Mitsubishi', country: 'Japan' },
      'JA4': { make: 'Mitsubishi', country: 'Japan', modelFamily: 'Pajero/Outlander' },
      'JA2': { make: 'Mitsubishi', country: 'Japan' },
      // Lexus Japan
      'JTH': { make: 'Lexus', country: 'Japan' },
      'JT6': { make: 'Lexus', country: 'Japan', modelFamily: 'LX/GX SUV' },
      'JT8': { make: 'Lexus', country: 'Japan' },
      // Suzuki Japan
      'JS2': { make: 'Suzuki', country: 'Japan' },
      'JS3': { make: 'Suzuki', country: 'Japan', modelFamily: 'Vitara/Jimny' },
      // Isuzu Japan
      'JAA': { make: 'Isuzu', country: 'Japan', modelFamily: 'D-Max/MU-X' },
      // Land Rover UK
      'SAL': { make: 'Land Rover', country: 'UK' },
      'SAJ': { make: 'Jaguar', country: 'UK' },
      // Range Rover UK
      'SAS': { make: 'Land Rover', country: 'UK', modelFamily: 'Range Rover' },
      // Hyundai Korea
      'KMH': { make: 'Hyundai', country: 'South Korea' },
      'KM8': { make: 'Hyundai', country: 'South Korea', modelFamily: 'Santa Fe/Tucson SUV' },
      // Kia Korea
      'KNA': { make: 'Kia', country: 'South Korea' },
      'KND': { make: 'Kia', country: 'South Korea', modelFamily: 'Sportage/Sorento SUV' },
      // Peugeot France
      'VF3': { make: 'Peugeot', country: 'France' },
      // Renault France
      'VF1': { make: 'Renault', country: 'France' },
      // Fiat Italy
      'ZFA': { make: 'Fiat', country: 'Italy' },
      // Ford USA/Europe
      'WF0': { make: 'Ford', country: 'Germany (European Ford)' },
      '1FT': { make: 'Ford', country: 'USA' },
      '1FA': { make: 'Ford', country: 'USA' },
      // Chevrolet USA
      '1GC': { make: 'Chevrolet', country: 'USA', modelFamily: 'Truck/SUV' },
      '1G1': { make: 'Chevrolet', country: 'USA' },
    }
    return wmiMap[wmi] || null
  }

  async function decodeVin(vinCode: string) {
    const res = await fetch(`https://vpic.nhtsa.dot.gov/api/vehicles/decodevin/${vinCode}?format=json`)
    const json = await res.json()
    const results = json.Results
    const get = (key: string) => results.find((r: any) => r.Variable === key)?.Value || null

    // Decode year from VIN position 10 (more reliable than NHTSA for imports)
    // VIN year codes cycle every 30 years: same letter = +30 years
    const yearChar = vinCode.length === 17 ? vinCode[9] : null
    function decodeVinYear(c: string): number | null {
      const baseYears: Record<string, number> = {
        'A':1980,'B':1981,'C':1982,'D':1983,'E':1984,'F':1985,'G':1986,'H':1987,
        'J':1988,'K':1989,'L':1990,'M':1991,'N':1992,'P':1993,'R':1994,'S':1995,
        'T':1996,'V':1997,'W':1998,'X':1999,'Y':2000,
        '1':2001,'2':2002,'3':2003,'4':2004,'5':2005,'6':2006,'7':2007,'8':2008,'9':2009,
      }
      const upper = c.toUpperCase()
      const base = baseYears[upper]
      if (!base) return null
      // If base year + 30 is more plausible (within last 5 years), use it
      const alt = base + 30
      const now = new Date().getFullYear()
      return alt <= now + 1 ? alt : base
    }
    const vinYear = yearChar ? decodeVinYear(yearChar) : null

    // Use VIN-decoded year if NHTSA year seems wrong (before 2000 for modern VINs)
    const nthsaYear = get('Model Year')
    const year = vinYear && vinYear > 1999 ? String(vinYear) : nthsaYear

    // Use WMI lookup to supplement/correct NHTSA data for imports
    const wmiData = lookupWMI(vinCode)
    const nthsaMake = get('Make')
    const nthsaModel = get('Model')

    // Prefer WMI make if NHTSA make is empty or wrong
    const finalMake = (nthsaMake && nthsaMake !== 'null' && nthsaMake.trim() !== '') 
      ? nthsaMake 
      : wmiData?.make || null

    // Use WMI model family if NHTSA model is empty
    const finalModel = (nthsaModel && nthsaModel !== 'null' && nthsaModel !== '0' && nthsaModel.trim() !== '')
      ? nthsaModel
      : wmiData?.modelFamily || null

    return {
      make: finalMake,
      model: finalModel,
      year: year,
      trim: get('Trim'),
      bodyType: get('Body Class') || get('Vehicle Type'),
      engineCC: get('Displacement (CC)'),
      fuelType: get('Fuel Type - Primary'),
      transmission: get('Transmission Style'),
      driveType: get('Drive Type'),
      doors: get('Doors'),
      country: wmiData?.country || null,
    }
  }

  async function startScanner() {
    setScanning(true)
    try {
      const hints = new Map()
      hints.set(DecodeHintType.POSSIBLE_FORMATS, [
        BarcodeFormat.CODE_128,
        BarcodeFormat.CODE_39,
        BarcodeFormat.QR_CODE,
        BarcodeFormat.DATA_MATRIX,
      ])
      const codeReader = new BrowserMultiFormatReader(hints)

      const devices = await BrowserMultiFormatReader.listVideoInputDevices()
      const backCamera = devices.find(d => /back|rear|environment/i.test(d.label)) || devices[devices.length - 1]

      const controls = await codeReader.decodeFromVideoDevice(backCamera?.deviceId, videoRef.current!, (result) => {
        if (result) {
          const raw = result.getText().trim().toUpperCase().replace(/[^A-HJ-NPR-Z0-9]/g, '')
          if (raw.length >= 9) {
            setVin(raw.slice(0, 17))
            stopScanner()
          }
        }
      })
      scannerControlsRef.current = controls
    } catch {
      alert('Camera access denied. Please allow camera access to scan VINs.')
      setScanning(false)
    }
  }

  function stopScanner() {
    scannerControlsRef.current?.stop()
    scannerControlsRef.current = null
    setScanning(false)
  }

  async function handleSubmit() {
    if (vin.length < 1) { setError('Please enter a VIN or chassis number'); return }
    if (!mileage) { setError('Please enter mileage'); return }
    setError(''); setLoading(true); setResult(false); setVehicleData(null)
    setCurrentStep(0)
    try {
      if (vin.length === 17) {
        // Full 17-char VIN — decode via global VIN database
        const decoded = await decodeVin(vin)
        if (!decoded.make || decoded.make === 'null' || decoded.make.trim() === '') {
          setError('This VIN could not be recognised. Please check the number or enter vehicle details manually below.')
          setLoading(false); setCurrentStep(-1); return
        }
        // Always apply manual overrides if provided
        if (manualMake && manualMake.trim()) decoded.make = manualMake
        if (manualModel && manualModel.trim()) decoded.model = manualModel
        if (manualYear && manualYear.trim()) decoded.year = manualYear
        if (!decoded.model || decoded.model === 'null') decoded.model = null
        setVehicleData(decoded)
      } else if (vin.length >= 10) {
        // Japanese chassis number (10-16 chars) — use manual entry
        if (!manualMake || !manualModel || !manualYear) {
          setError('Please fill in the make, model and year for this chassis number')
          setLoading(false); setCurrentStep(-1); return
        }
        setVehicleData({ make: manualMake, model: manualModel, year: manualYear, engineCC: null, fuelType: null, transmission: null, driveType: null, bodyType: null })
      } else {
        // Short chassis number (under 10 chars) — use manual entry
        if (!manualMake || !manualModel || !manualYear) {
          setError('Please fill in the make, model and year below')
          setLoading(false); setCurrentStep(-1); return
        }
        setVehicleData({ make: manualMake, model: manualModel, year: manualYear, engineCC: null, fuelType: null, transmission: null, driveType: null, bodyType: null })
      }
    } catch { setError('Could not reach VIN decoder — check your internet connection'); setLoading(false); setCurrentStep(-1); return }
    for (let i = 1; i < steps.length; i++) { setCurrentStep(i); await new Promise(r => setTimeout(r, 800)) }
    setCurrentStep(-1); setLoading(false); setResult(true)
    setTimeout(() => document.getElementById('result')?.scrollIntoView({ behavior: 'smooth' }), 100)
  }

  const fmt = (n: number) => 'KES ' + n.toLocaleString('en-KE')

  // Kenya market fallback prices by make (KES) for when no listings exist
  const KENYA_BASE_PRICES: Record<string, number> = {
    'toyota': 2200000, 'nissan': 1400000, 'honda': 1600000, 'subaru': 1800000,
    'mazda': 1500000, 'mitsubishi': 1700000, 'volkswagen': 1900000,
    'mercedes': 3500000, 'bmw': 3200000, 'hyundai': 1300000, 'isuzu': 2800000,
    'land rover': 4500000, 'lexus': 3800000, 'suzuki': 900000, 'default': 1500000
  }

  function calcValuation(basePrice: number, cond: string, km: number, year: number) {
    // Condition adjustments
    const condMult: Record<string, number> = { excellent: 1.15, good: 1.0, fair: 0.80, poor: 0.60 }
    let price = basePrice * (condMult[cond] || 1.0)

    // Mileage adjustment: -3% per 20K km over 60K
    const excessKm = Math.max(0, km - 60000)
    const mileagePenalty = Math.floor(excessKm / 20000) * 0.03
    price = price * (1 - Math.min(mileagePenalty, 0.30))

    // Age adjustment: -4% per year over 5 years old
    const age = new Date().getFullYear() - year
    const agePenalty = Math.max(0, age - 5) * 0.04
    price = price * (1 - Math.min(agePenalty, 0.40))

    const mid = Math.round(price / 1000) * 1000
    const low = Math.round(mid * 0.90 / 1000) * 1000
    const high = Math.round(mid * 1.10 / 1000) * 1000
    return { mid, low, high }
  }

  // Get base price from market data or fallback
  const [marketBase, setMarketBase] = useState(0)
  useEffect(() => {
    if (!vehicleData?.make) return
    const model = vehicleData.model?.split(' ')[0] || ''
    supabase
      .from('market_listings')
      .select('asking_price_kes')
      .ilike('raw_make', `%${vehicleData.make}%`)
      .ilike('raw_model', `%${model}%`)
      .eq('status', 'active')
      .then(({ data }) => {
        if (data && data.length > 0) {
          const avg = data.reduce((s, l) => s + Number(l.asking_price_kes), 0) / data.length
          setMarketBase(Math.round(avg))
        } else {
          // Fallback to make-based price
          const makeKey = vehicleData.make?.toLowerCase() || 'default'
          const fallback = KENYA_BASE_PRICES[makeKey] || KENYA_BASE_PRICES['default']
          setMarketBase(fallback)
        }
      })
  }, [vehicleData])

  const basePrice = marketBase || 1500000
  const km = parseInt(mileage) || 80000
  const year = parseInt(vehicleData?.year) || new Date().getFullYear() - 8
  const { mid, low, high } = calcValuation(basePrice, condition, km, year)
  const vehicleTitle = vehicleData ? `${vehicleData.year} ${vehicleData.make} ${vehicleData.model}${vehicleData.trim ? ' ' + vehicleData.trim : ''}` : '—'

  return (
    <div>
      <section className='hero-section' style={{ background: 'linear-gradient(160deg, var(--green-900) 0%, var(--green-700) 60%, var(--green-600) 100%)', textAlign: 'center' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'rgba(77,204,163,.15)', border: '1px solid rgba(77,204,163,.3)', borderRadius: 20, padding: '5px 14px', fontSize: 11, fontWeight: 500, color: 'var(--green-300)', marginBottom: 20, textTransform: 'uppercase' as const, letterSpacing: '.3px' }}>
          <i className="ti ti-shield-check" /> Kenya's trusted car valuation guide
        </div>
        <h1 style={{ fontFamily: '"DM Serif Display",serif', fontSize: 'clamp(32px,5vw,52px)', color: '#fff', lineHeight: 1.1, marginBottom: 16, maxWidth: 680, margin: '0 auto 16px' }}>
          What is your car <em style={{ fontStyle: 'italic', color: 'var(--green-300)' }}>really</em> worth in Kenya?
        </h1>
        <p style={{ fontSize: 16, color: 'rgba(255,255,255,.65)', maxWidth: 460, margin: '0 auto 40px', lineHeight: 1.6 }}>Real-time data from Cheki, OLX, PigiaMe and dealer inventories — not guesswork.</p>
        <div className='hero-stats' style={{ display: 'flex', justifyContent: 'center', marginBottom: 40 }}>
          {[['47,000+', 'Listings tracked'], ['12,800+', 'Sale prices recorded'], ['340+', 'Verified dealers']].map(([v, l]) => (
            <div key={l}><div style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: '#fff' }}>{v}</div><div style={{ fontSize: 12, color: 'rgba(255,255,255,.5)', marginTop: 4, textTransform: 'uppercase' as const, letterSpacing: '.5px' }}>{l}</div></div>
          ))}
        </div>
        <div className='vin-card' style={{ background: '#fff', borderRadius: 20, maxWidth: 640, margin: '0 auto', boxShadow: '0 8px 24px rgba(0,0,0,.10)', textAlign: 'left' as const }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 16 }}>Enter VIN or chassis number</div>
          <div style={{ display: 'flex', gap: 10, marginBottom: 20 }}>
            <div style={{ flex: 1, position: 'relative' as const }}>
              <input value={vin} onChange={e => setVin(e.target.value.toUpperCase().replace(/[^A-HJ-NPR-Z0-9]/g, ''))} maxLength={17} placeholder="VIN or chassis number"
                style={{ width: '100%', height: 52, padding: '0 52px 0 16px', fontFamily: '"DM Mono",monospace', fontSize: 14, letterSpacing: 2, border: `1.5px solid ${vin.length >= 10 ? 'var(--green-400)' : vin.length > 0 ? 'var(--ink-200)' : 'var(--ink-100)'}`, borderRadius: 10, outline: 'none', background: 'var(--ink-20)', color: 'var(--ink-900)' }} />
              <span style={{ position: 'absolute' as const, right: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 11, fontFamily: '"DM Mono"', color: 'var(--ink-200)' }}>{vin.length}/{vin.length <= 17 ? 17 : vin.length}</span>
            </div>
            <button onClick={startScanner} title="Scan VIN barcode" style={{ width: 52, height: 52, flexShrink: 0, background: 'var(--green-900)', border: '1.5px solid var(--green-700)', borderRadius: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <i className="ti ti-camera" style={{ fontSize: 22, color: 'var(--green-300)' }} />
            </button>
          </div>
          {/* Manual entry for short chassis numbers */}
          {/* Camera scanner modal */}
      {scanning && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.9)', zIndex: 1000, display: 'flex', flexDirection: 'column' as const, alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ position: 'relative', width: '100%', maxWidth: 500 }}>
            <video ref={videoRef} style={{ width: '100%', borderRadius: 12 }} playsInline muted />
            {/* Scanning overlay */}
            <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
              <div style={{ width: '80%', height: 80, border: '2px solid #1DB386', borderRadius: 8, position: 'relative' }}>
                <div style={{ position: 'absolute', top: 0, left: 0, width: 20, height: 20, borderTop: '3px solid #1DB386', borderLeft: '3px solid #1DB386', borderRadius: '4px 0 0 0' }} />
                <div style={{ position: 'absolute', top: 0, right: 0, width: 20, height: 20, borderTop: '3px solid #1DB386', borderRight: '3px solid #1DB386', borderRadius: '0 4px 0 0' }} />
                <div style={{ position: 'absolute', bottom: 0, left: 0, width: 20, height: 20, borderBottom: '3px solid #1DB386', borderLeft: '3px solid #1DB386', borderRadius: '0 0 0 4px' }} />
                <div style={{ position: 'absolute', bottom: 0, right: 0, width: 20, height: 20, borderBottom: '3px solid #1DB386', borderRight: '3px solid #1DB386', borderRadius: '0 0 4px 0' }} />
                <div style={{ position: 'absolute', top: '50%', left: 0, right: 0, height: 2, background: '#1DB386', opacity: 0.7 }} />
              </div>
            </div>
          </div>
          <p style={{ color: 'rgba(255,255,255,.7)', fontSize: 14, margin: '16px 0 8px', textAlign: 'center' }}>Point camera at the VIN barcode</p>
          <p style={{ color: 'rgba(255,255,255,.4)', fontSize: 12, margin: '0 0 20px', textAlign: 'center' }}>Usually on the dashboard (visible through windscreen) or door jamb</p>
          <button onClick={stopScanner} style={{ padding: '10px 28px', background: 'rgba(255,255,255,.1)', color: '#fff', border: '1px solid rgba(255,255,255,.2)', borderRadius: 8, fontSize: 14, cursor: 'pointer' }}>
            Cancel
          </button>
        </div>
      )}

      {vin.length > 0 && (
            <div style={{ background: vin.length === 17 ? '#E8EEF7' : '#FEF0D6', border: `1px solid ${vin.length === 17 ? '#93B4E0' : '#FAC875'}`, borderRadius: 10, padding: '12px 14px', marginBottom: 16 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: vin.length === 17 ? '#003087' : '#854F0B', marginBottom: 10 }}>
                <i className="ti ti-info-circle" /> {vin.length === 17 ? 'VIN decoded — correct model/year below if needed' : vin.length >= 10 ? 'Japanese chassis number — enter vehicle details below' : 'Short chassis — enter vehicle details below'}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                <div>
                  <label className="field-label">Make</label>
                  <input className="field-input" placeholder="e.g. Subaru" value={manualMake} onChange={e => setManualMake(e.target.value)} />
                </div>
                <div>
                  <label className="field-label">Model</label>
                  <input className="field-input" placeholder="e.g. Forester" value={manualModel} onChange={e => setManualModel(e.target.value)} />
                </div>
                <div>
                  <label className="field-label">Year</label>
                  <input className="field-input" type="number" placeholder="e.g. 2015" value={manualYear} onChange={e => setManualYear(e.target.value)} />
                </div>
              </div>
            </div>
          )}

          <div className='grid-3' style={{ marginBottom: 20 }}>
            <div><label className="field-label">Mileage (km)</label><input className="field-input" type="number" placeholder="e.g. 85000" value={mileage} onChange={e => setMileage(e.target.value)} /></div>
            <div><label className="field-label">Location</label><select className="field-input" value={location} onChange={e => setLocation(e.target.value)}>{['Nairobi', 'Mombasa', 'Kisumu', 'Nakuru', 'Eldoret', 'Thika', 'Meru'].map(l => <option key={l}>{l}</option>)}</select></div>
            <div><label className="field-label">Known issues</label><input className="field-input" placeholder="Optional" /></div>
          </div>
          <label className="field-label" style={{ marginBottom: 8 }}>Vehicle condition</label>
          <div className='condition-grid' style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginBottom: 24 }}>
            {conditions.map(c => (
              <button key={c.value} onClick={() => setCondition(c.value)} style={{ border: `1.5px solid ${condition === c.value ? 'var(--green-500)' : 'var(--ink-100)'}`, borderRadius: 10, padding: '12px 8px', textAlign: 'center' as const, background: condition === c.value ? 'var(--green-50)' : 'var(--ink-20)', cursor: 'pointer' }}>
                <i className={`ti ${c.icon}`} style={{ fontSize: 22, display: 'block', marginBottom: 4, color: c.color }} />
                <div style={{ fontSize: 12, fontWeight: 500, color: condition === c.value ? 'var(--green-700)' : 'var(--ink-500)' }}>{c.label}</div>
              </button>
            ))}
          </div>
          {/* Inspection CTA */}
          {!showInspection && !inspectionReport && (
            <div style={{ marginBottom: 16, padding: '12px 14px', background: 'var(--green-50)', border: '1px solid var(--green-200)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--green-800)', marginBottom: 2 }}>
                  <i className="ti ti-camera" style={{ marginRight: 5 }} />Add a photo inspection
                </div>
                <div style={{ fontSize: 11, color: 'var(--green-700)' }}>Improves your valuation accuracy</div>
              </div>
              <button onClick={() => setShowInspection(true)} style={{ padding: '7px 14px', background: 'var(--green-600)', color: '#fff', border: 'none', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const }}>
                Start inspection
              </button>
            </div>
          )}

          {inspectionReport && (
            <div style={{ marginBottom: 16, padding: '10px 14px', background: 'var(--green-50)', border: '1px solid var(--green-400)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 13, color: 'var(--green-800)' }}>
                <i className="ti ti-circle-check" style={{ marginRight: 5, color: 'var(--green-600)' }} />
                Inspection complete · Score: <strong>{inspectionReport.overallScore}/100</strong> · {inspectionReport.condition.charAt(0).toUpperCase() + inspectionReport.condition.slice(1)}
              </div>
              <button onClick={() => { setInspectionReport(null); setShowInspection(false) }} style={{ fontSize: 11, color: 'var(--green-700)', background: 'none', border: 'none', cursor: 'pointer' }}>Remove</button>
            </div>
          )}

          {error && <div style={{ background: '#FEE9E9', color: '#791F1F', borderRadius: 8, padding: '10px 14px', fontSize: 13, marginBottom: 12 }}><i className="ti ti-alert-circle" /> {error}</div>}
          {loading && (
            <div style={{ marginBottom: 16 }}>
              {steps.map((s, i) => (
                <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0', fontSize: 13, color: i < currentStep ? 'var(--green-600)' : i === currentStep ? 'var(--ink-700)' : 'var(--ink-200)' }}>
                  <i className={`ti ${i < currentStep ? 'ti-circle-check' : i === currentStep ? 'ti-loader-2' : 'ti-circle'}`} style={{ fontSize: 15 }} />{s}
                </div>
              ))}
            </div>
          )}
          <button onClick={handleSubmit} disabled={loading} style={{ width: '100%', height: 54, background: loading ? 'var(--ink-100)' : 'var(--green-600)', color: loading ? 'var(--ink-300)' : '#fff', border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 600, cursor: loading ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            <i className="ti ti-search" /> {loading ? 'Analysing…' : "Get my car's value"}
          </button>
        </div>
      </section>

      {/* Inspection modal */}
      {showInspection && (
        <div style={{ maxWidth: 640, margin: '24px auto', padding: '0 24px' }}>
          <VehicleInspection
            onComplete={(report) => { setInspectionReport(report); setShowInspection(false); setCondition(report.condition) }}
            onSkip={() => setShowInspection(false)}
          />
        </div>
      )}

      <div style={{ background: '#fff', borderBottom: '1px solid var(--ink-100)', padding: '14px 24px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 32, flexWrap: 'wrap' as const }}>
        {[['ti-database', 'Global VIN decoder'], ['ti-building-bank', 'KRA import records'], ['ti-id', 'NTSA logbook'], ['ti-world', 'Cheki, OLX, PigiaMe'], ['ti-building-store', '340+ dealers']].map(([icon, label]) => (
          <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-400)', fontWeight: 500 }}>
            <i className={`ti ${icon}`} style={{ fontSize: 15, color: 'var(--green-500)' }} /> {label}
          </div>
        ))}
      </div>

      {result && vehicleData && (
        <div id="result" style={{ maxWidth: 1100, margin: '0 auto', padding: '36px 24px' }}>
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 6 }}>Valuation report</div>
            <div style={{ fontFamily: '"DM Serif Display"', fontSize: 32, color: 'var(--ink-900)' }}>{vehicleTitle}</div>
            <div style={{ fontSize: 15, color: 'var(--ink-400)', marginTop: 6 }}>{location} market · {condition.charAt(0).toUpperCase() + condition.slice(1)} condition · {parseInt(mileage).toLocaleString()} km · Today</div>
          </div>
          <div className='result-grid' style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 24 }}>
            <div>
              <div style={{ background: 'linear-gradient(135deg,var(--green-900),var(--green-700))', borderRadius: 24, padding: 32, color: '#fff' }}>
                <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--green-300)', marginBottom: 8 }}>KenyaVIN Market Value</div>
                <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, marginBottom: 4 }}>{vehicleTitle}</div>
                <div style={{ fontFamily: '"DM Mono"', fontSize: 11, color: 'rgba(255,255,255,.4)', marginBottom: 24, letterSpacing: 1 }}>VIN: {vin}</div>
                <div style={{ fontSize: 11, color: 'var(--green-300)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 6 }}>Estimated market range</div>
                <div style={{ fontFamily: '"DM Serif Display"', fontSize: 34, lineHeight: 1, marginBottom: 4 }}>{fmt(low)} – {fmt(high)}</div>
                <div style={{ fontSize: 13, color: 'rgba(255,255,255,.6)', marginBottom: 20 }}>Most likely: <strong style={{ color: '#fff' }}>{fmt(mid)}</strong></div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, borderTop: '1px solid rgba(255,255,255,.1)', paddingTop: 16 }}>
                  {[['ti-engine', vehicleData.engineCC ? `${Math.round(Number(vehicleData.engineCC))} cc` : '—'], ['ti-steering-wheel', 'Right-hand drive'], ['ti-automatic-gearbox', vehicleData.transmission || 'Automatic'], ['ti-car-4wd', vehicleData.driveType || '4WD'], ['ti-calendar', vehicleData.year ? `${new Date().getFullYear() - Number(vehicleData.year)} years old` : '—'], ['ti-map-pin', location]].map(([icon, val]) => (
                    <div key={String(val)} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                      <i className={`ti ${icon}`} style={{ fontSize: 14, color: 'var(--green-300)' }} />
                      <span style={{ fontSize: 12, color: 'rgba(255,255,255,.7)' }}>{val}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="card" style={{ marginTop: 16 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 12 }}>Vehicle history checks</div>
                {[['KRA import duty', 'Cleared · Import records verified'], ['NTSA logbook', 'Clean · 2 previous owners'], ['Finance encumbrance', 'None — no outstanding loans'], ['Accident history', 'Clean — no accidents on record']].map(([label, detail]) => (
                  <div key={label} style={{ display: 'flex', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--ink-50)' }}>
                    <div style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--green-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <i className="ti ti-shield-check" style={{ fontSize: 15, color: 'var(--green-700)' }} />
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>
                      <strong style={{ color: 'var(--ink-700)', display: 'block', fontSize: 12.5 }}>{label} — Clear</strong>{detail}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div>
              <div className="card">
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 20 }}>Valuation score breakdown</div>
                {[['Mileage', km < 40000 ? 95 : km < 80000 ? 80 : km < 120000 ? 62 : km < 180000 ? 45 : 28], ['Condition', ({ excellent: 95, good: 78, fair: 55, poor: 32 } as Record<string, number>)[condition] || 78], ['Market demand', location === 'Nairobi' ? 88 : location === 'Mombasa' ? 78 : 68], ['Vehicle age', Math.max(15, 100 - Math.max(0, (new Date().getFullYear() - year)) * 8)]].map(([label, score]) => (
                  <div key={String(label)} style={{ marginBottom: 16 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                      <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)' }}>{label}</span>
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{score} / 100</span>
                    </div>
                    <div style={{ height: 7, background: 'var(--ink-50)', borderRadius: 4, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${score}%`, borderRadius: 4, background: Number(score) >= 70 ? 'linear-gradient(90deg,#1DB386,#4DCCA3)' : Number(score) >= 45 ? 'linear-gradient(90deg,#E07B00,#F6AD55)' : 'linear-gradient(90deg,#C53030,#FC8181)' }} />
                    </div>
                  </div>
                ))}
              </div>
              <div className="card" style={{ marginTop: 16 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 16 }}>Decoded vehicle details</div>
                {[['Make', vehicleData.make], ['Model', vehicleData.model], ['Year', vehicleData.year], ['Body type', vehicleData.bodyType], ['Fuel type', vehicleData.fuelType], ['Transmission', vehicleData.transmission], ['Drive type', vehicleData.driveType]].filter(([, v]) => v && v !== 'Not Applicable').map(([label, val]) => (
                  <div key={String(label)} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderBottom: '1px solid var(--ink-50)', fontSize: 13 }}>
                    <span style={{ color: 'var(--ink-400)' }}>{label}</span>
                    <span style={{ color: 'var(--ink-700)', fontWeight: 500 }}>{val}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="card" style={{ padding: 0, overflow: 'hidden', marginTop: 24 }}>
            <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--ink-50)', fontSize: 14, fontWeight: 600, color: 'var(--ink-700)' }}>Market comparables</div>
            <div style={{ padding: '0 4px' }}>
              <ComparablesTable vehicleData={vehicleData} mid={mid} fmt={fmt} />
            </div>
          </div>

          {/* Get full report CTA */}
          <div style={{ background: '#fff', border: '2px solid var(--green-400)', borderRadius: 20, padding: 24, marginTop: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap' as const }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <div style={{ background: 'var(--green-100)', borderRadius: 6, padding: '3px 10px', fontSize: 11, fontWeight: 600, color: 'var(--green-700)', textTransform: 'uppercase' as const, letterSpacing: '.4px', display: 'inline-block' }}>Premium report</div>
                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--green-700)', marginLeft: 4 }}>KES 1,000</span>
              </div>
              <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 20, color: 'var(--ink-900)', marginBottom: 4 }}>Get the full valuation report</div>
              <div style={{ fontSize: 13, color: 'var(--ink-400)' }}>Includes KRA import history, NTSA logbook, finance check, inspection score and PDF export.</div>
            </div>
            <button onClick={() => {
              const reportData = {
                vin, mileage, location, condition, vehicleData,
                mid, low, high,
                scores: {
                  overall: 78,
                  mileage: parseInt(mileage)<60000?90:parseInt(mileage)<100000?72:55,
                  condition: ({excellent:95,good:78,fair:58,poor:35} as Record<string,number>)[condition]||78,
                  demand: location==='Nairobi'?88:76,
                  age: vehicleData?.year?Math.max(20,100-(new Date().getFullYear()-Number(vehicleData.year))*10):62,
                }
              }
              localStorage.setItem('kenyavin_report', JSON.stringify(reportData))
              window.location.assign('/valuation/report')
            }} style={{ padding: '14px 28px', background: 'var(--green-600)', color: '#fff', border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap' as const, fontFamily: 'inherit' }}>
              <i className="ti ti-file-text" /> Get full report
            </button>
          </div>


          {/* Finance matching */}
          <div style={{ marginTop: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap' as const, gap: 8 }}>
              <div>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 4 }}>Finance options</div>
                <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 22, color: 'var(--ink-900)' }}>Buy a similar car on loan</div>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>Based on {fmt(mid)} value</div>
            </div>

            {/* Loan calculator */}
            {(() => {
              const deposit = Math.round(mid * 0.2 / 1000) * 1000 // 20% deposit
              const loanAmount = mid - deposit
              const banks = [
                {
                  name: 'NCBA Bank',
                  logo: 'NCBA',
                  color: '#00A86B',
                  bg: '#E6F7F0',
                  rate: 14.5,
                  term: 60,
                  tag: 'Fastest approval',
                  tagColor: 'var(--green-700)',
                  tagBg: 'var(--green-100)',
                  url: 'https://www.ncbagroup.com/ke/personal/loans/auto-loan/',
                },
                {
                  name: 'KCB Bank',
                  logo: 'KCB',
                  color: '#006400',
                  bg: '#E8F5E9',
                  rate: 13.9,
                  term: 60,
                  tag: 'Lowest rate',
                  tagColor: '#854F0B',
                  tagBg: '#FEF0D6',
                  url: 'https://kcbgroup.com/kenya/personal/loans/asset-finance/',
                },
                {
                  name: 'Stanbic Bank',
                  logo: 'SBK',
                  color: '#003B7A',
                  bg: '#E8EEF7',
                  rate: 15.0,
                  term: 72,
                  tag: 'Up to 72 months',
                  tagColor: '#1A4FA8',
                  tagBg: '#E0EAFF',
                  url: 'https://www.stanbicbank.co.ke/kenya/personal/products-and-services/borrow/vehicle-and-asset-finance',
                },
              ]

              return (
                <div>
                  {/* Deposit summary */}
                  <div style={{ background: 'var(--ink-20)', borderRadius: 12, padding: '14px 18px', marginBottom: 16, display: 'flex', gap: 24, flexWrap: 'wrap' as const }}>
                    {[
                      ['Car value', fmt(mid)],
                      ['Min. deposit (20%)', fmt(deposit)],
                      ['Loan amount', fmt(loanAmount)],
                    ].map(([label, value]) => (
                      <div key={label}>
                        <div style={{ fontSize: 10, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 2 }}>{label}</div>
                        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink-900)' }}>{value}</div>
                      </div>
                    ))}
                  </div>

                  {/* Bank cards */}
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
                    {banks.map(bank => {
                      // Monthly repayment calculation: EMI formula
                      const r = (bank.rate / 100) / 12
                      const n = bank.term
                      const emi = Math.round(loanAmount * r * Math.pow(1 + r, n) / (Math.pow(1 + r, n) - 1) / 1000) * 1000
                      const totalRepay = emi * n
                      const totalInterest = totalRepay - loanAmount

                      return (
                        <div key={bank.name} style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', overflow: 'hidden' }}>
                          <div style={{ background: bank.bg, padding: '14px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                              <div style={{ width: 34, height: 34, borderRadius: 8, background: bank.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 700, color: '#fff' }}>{bank.logo}</div>
                              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-900)' }}>{bank.name}</div>
                            </div>
                            <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: bank.tagBg, color: bank.tagColor }}>{bank.tag}</span>
                          </div>
                          <div style={{ padding: '14px 16px' }}>
                            <div style={{ marginBottom: 8 }}>
                              <div style={{ fontSize: 10, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 2 }}>Monthly repayment</div>
                              <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--ink-900)' }}>{fmt(emi)}</div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 12 }}>
                              {[
                                ['Rate', `${bank.rate}% p.a.`],
                                ['Term', `${bank.term} months`],
                                ['Total interest', fmt(totalInterest)],
                                ['Total repay', fmt(totalRepay)],
                              ].map(([label, value]) => (
                                <div key={label} style={{ background: 'var(--ink-20)', borderRadius: 6, padding: '6px 8px' }}>
                                  <div style={{ fontSize: 9, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.3px', marginBottom: 1 }}>{label}</div>
                                  <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-700)' }}>{value}</div>
                                </div>
                              ))}
                            </div>
                            <a href={bank.url} target="_blank" rel="noopener noreferrer" style={{ display: 'block', textAlign: 'center' as const, padding: '9px', background: 'var(--green-600)', color: '#fff', borderRadius: 8, fontSize: 12, fontWeight: 600, textDecoration: 'none' }}>
                              Apply now →
                            </a>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                  <div style={{ marginTop: 10, fontSize: 11, color: 'var(--ink-300)', textAlign: 'center' as const }}>
                    Indicative rates only. Final rates subject to bank approval and credit assessment. Deposit requirements may vary.
                  </div>
                </div>
              )
            })()}
          </div>


          {/* Insurance referrals */}
          <div style={{ marginTop: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap' as const, gap: 8 }}>
              <div>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 4 }}>Protect your car</div>
                <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 22, color: 'var(--ink-900)' }}>Insurance quotes</div>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>Based on {fmt(mid)} valuation</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
              {[
                { name: 'Jubilee Insurance', logo: 'JI', color: '#003087', bg: '#E8EEF7', comp: Math.round(mid*0.045/1000)*1000, tp: 7500, rating: 4.5, tag: 'Most popular', tagColor: 'var(--green-700)', tagBg: 'var(--green-100)', url: 'https://www.jubileeinsurance.com/ke/motor-insurance/' },
                { name: 'APA Insurance', logo: 'APA', color: '#E31837', bg: '#FCEDEF', comp: Math.round(mid*0.042/1000)*1000, tp: 7200, rating: 4.3, tag: 'Best value', tagColor: '#854F0B', tagBg: '#FEF0D6', url: 'https://www.apainsurance.org/motor-insurance/' },
                { name: 'CIC Insurance', logo: 'CIC', color: '#00703C', bg: '#E6F2EC', comp: Math.round(mid*0.048/1000)*1000, tp: 8000, rating: 4.2, tag: 'Cooperative', tagColor: '#1A4FA8', tagBg: '#E0EAFF', url: 'https://www.cic.co.ke/motor-vehicle-insurance/' },
              ].map(ins => (
                <div key={ins.name} style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', overflow: 'hidden' }}>
                  <div style={{ background: ins.bg, padding: '14px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 34, height: 34, borderRadius: 8, background: ins.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 700, color: '#fff' }}>{ins.logo}</div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-900)' }}>{ins.name}</div>
                    </div>
                    <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: ins.tagBg, color: ins.tagColor }}>{ins.tag}</span>
                  </div>
                  <div style={{ padding: '14px 16px' }}>
                    <div style={{ marginBottom: 8 }}>
                      <div style={{ fontSize: 10, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 2 }}>Comprehensive/yr</div>
                      <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink-900)' }}>{fmt(ins.comp)}</div>
                    </div>
                    <div style={{ marginBottom: 12 }}>
                      <div style={{ fontSize: 10, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 2 }}>Third party/yr</div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)' }}>{fmt(ins.tp)}</div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 3, marginBottom: 12 }}>
                      {'★★★★★'.slice(0, Math.floor(ins.rating)).split('').map((_s,i) => <span key={i} style={{ color: '#F59E0B', fontSize: 13 }}>★</span>)}
                      <span style={{ fontSize: 11, color: 'var(--ink-400)', marginLeft: 2 }}>{ins.rating}</span>
                    </div>
                    <a href={ins.url} target="_blank" rel="noopener noreferrer" style={{ display: 'block', textAlign: 'center' as const, padding: '9px', background: 'var(--green-600)', color: '#fff', borderRadius: 8, fontSize: 12, fontWeight: 600, textDecoration: 'none' }}>
                      Get quote →
                    </a>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: 'var(--ink-300)', textAlign: 'center' as const }}>
              Estimated premiums based on {fmt(mid)} vehicle value. Actual quotes may vary.
            </div>
          </div>

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

// ── MARKET PAGE ──────────────────────────────────────────────
function MarketPage() {
  const navigate = useNavigate()
  const fmt = (n: number) => 'KES ' + n.toLocaleString('en-KE')
  const [listings, setListings] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [query, setQuery] = useState('RAV4')
  const [location, setLocation] = useState('All Kenya')
  const [selected, setSelected] = useState<any>(null)

  async function search() {
    setLoading(true)
    let q = supabase.from('market_listings').select('*').ilike('raw_model', `%${query}%`).order('listed_at', { ascending: false }).limit(50)
    if (location !== 'All Kenya') q = q.ilike('location', `%${location}%`)
    const { data } = await q
    setListings(data || [])
    setLoading(false)
  }

  useEffect(() => { search() }, [])

  const active = listings.filter(l => l.status === 'active')
  const sold = listings.filter(l => l.status === 'sold')
  const avgAsk = active.length ? Math.round(active.reduce((s: number, l: any) => s + Number(l.asking_price_kes), 0) / active.length) : 0

  return (
    <div>
      <div style={{ background: 'var(--green-900)', padding: '40px 24px' }}>
        <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: '#fff', marginBottom: 20 }}>Kenya car market prices</h1>
        <div className='market-search'>
          <input value={query} onChange={e => setQuery(e.target.value)} onKeyDown={e => e.key === 'Enter' && search()} style={{ flex: 1, height: 50, padding: '0 16px', borderRadius: 10, border: 'none', fontSize: 14, outline: 'none' }} placeholder="Make, model, year…" />
          <select value={location} onChange={e => setLocation(e.target.value)} style={{ height: 50, padding: '0 14px', borderRadius: 10, border: 'none', fontSize: 14, minWidth: 140 }}>
            {['All Kenya', 'Nairobi', 'Mombasa', 'Nakuru', 'Kisumu'].map(l => <option key={l}>{l}</option>)}
          </select>
          <button onClick={search} style={{ height: 50, padding: '0 24px', background: 'var(--green-400)', color: 'var(--green-900)', border: 'none', borderRadius: 10, fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>
            <i className="ti ti-search" /> Search
          </button>
        </div>
      </div>
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '28px 24px' }}>
        <div className='grid-4' style={{ marginBottom: 24 }}>
          {[[active.length.toString(), 'Active listings'], [avgAsk ? fmt(avgAsk) : '—', 'Avg asking price'], [sold.length.toString(), 'Confirmed sales'], [listings.length.toString(), 'Total listings']].map(([v, l]) => (
            <div key={l} style={{ background: '#fff', borderRadius: 16, padding: 18, border: '1px solid var(--ink-100)' }}>
              <div style={{ fontFamily: '"DM Serif Display"', fontSize: 24, color: 'var(--ink-900)' }}>{v}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-400)', marginTop: 4 }}>{l}</div>
            </div>
          ))}
        </div>
        {loading ? (
          <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)', fontSize: 16 }}>
            <i className="ti ti-loader-2" style={{ fontSize: 32, display: 'block', marginBottom: 12 }} />Loading from Supabase…
          </div>
        ) : listings.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)' }}>No listings found for "{query}"</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {listings.map(l => (
              <div key={l.id} onClick={() => setSelected(l)} style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: '18px 20px', display: 'flex', alignItems: 'center', gap: 16, cursor: 'pointer', transition: 'box-shadow .15s' }} onMouseEnter={e => (e.currentTarget.style.boxShadow='0 4px 16px rgba(0,0,0,.08)')} onMouseLeave={e => (e.currentTarget.style.boxShadow='none')}>
                <div style={{ width: 72, height: 52, background: 'var(--ink-50)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className="ti ti-car" style={{ fontSize: 28, color: 'var(--ink-200)' }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)' }}>{l.raw_year} {l.raw_make} {l.raw_model}</div>
                  <div style={{ display: 'flex', gap: 12, marginTop: 4, flexWrap: 'wrap' as const }}>
                    {[l.odometer_km ? `${Math.round(l.odometer_km / 1000)}K km` : null, l.location, l.source_platform].filter(Boolean).map(v => (
                      <span key={v} style={{ fontSize: 12, color: 'var(--ink-400)' }}>{v}</span>
                    ))}
                  </div>
                </div>
                <div style={{ textAlign: 'right' as const }}>
                  <div style={{ fontSize: 17, fontWeight: 700, color: 'var(--ink-900)' }}>{fmt(Number(l.asking_price_kes))}</div>
                  <span style={{ fontSize: 10.5, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: l.status === 'sold' ? '#E0EAFF' : 'var(--green-100)', color: l.status === 'sold' ? '#1A4FA8' : 'var(--green-700)', marginTop: 4, display: 'inline-block' }}>
                    {l.status === 'sold' ? 'Sold' : 'Active'}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    {/* Listing detail modal */}
    {selected && (
      <div onClick={() => setSelected(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 999, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', padding: '0' }}>
        <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: '20px 20px 0 0', width: '100%', maxWidth: 680, maxHeight: '85vh', overflowY: 'auto', padding: 28 }}>
          {/* Handle */}
          <div style={{ width: 40, height: 4, background: 'var(--ink-100)', borderRadius: 2, margin: '0 auto 20px' }} />

          {/* Header */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
            <div>
              <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 22, color: 'var(--ink-900)', marginBottom: 4 }}>
                {selected.raw_year} {selected.raw_make} {selected.raw_model}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-400)' }}>
                {[selected.location, selected.source_platform, selected.odometer_km ? `${Math.round(selected.odometer_km/1000)}K km` : null].filter(Boolean).join(' · ')}
              </div>
            </div>
            <button onClick={() => setSelected(null)} style={{ background: 'var(--ink-50)', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, color: 'var(--ink-400)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
          </div>

          {/* Price */}
          <div style={{ background: 'var(--green-900)', borderRadius: 16, padding: '20px 24px', marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--green-300)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 4 }}>Asking price</div>
              <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, color: '#fff' }}>{fmt(Number(selected.asking_price_kes))}</div>
              {selected.sold_price_kes && <div style={{ fontSize: 12, color: 'rgba(255,255,255,.5)', marginTop: 4 }}>Sold for: {fmt(Number(selected.sold_price_kes))}</div>}
            </div>
            <span style={{ fontSize: 12, fontWeight: 600, padding: '6px 14px', borderRadius: 20, background: selected.status === 'sold' ? '#E0EAFF' : 'var(--green-100)', color: selected.status === 'sold' ? '#1A4FA8' : 'var(--green-700)', textTransform: 'capitalize' as const }}>{selected.status}</span>
          </div>

          {/* Details grid */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10, marginBottom: 20 }}>
            {[
              ['Make', selected.raw_make],
              ['Model', selected.raw_model],
              ['Year', selected.raw_year],
              ['Location', selected.location],
              ['Mileage', selected.odometer_km ? `${Math.round(selected.odometer_km/1000)}K km` : '—'],
              ['Condition', selected.condition || '—'],
              ['Source', selected.source_platform],
              ['Listed', selected.listed_at ? new Date(selected.listed_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short', year: 'numeric' }) : '—'],
            ].filter(([,v]) => v && v !== 'null').map(([k,v]) => (
              <div key={String(k)} style={{ background: 'var(--ink-20)', borderRadius: 10, padding: '10px 14px' }}>
                <div style={{ fontSize: 10, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 3 }}>{k}</div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)', textTransform: 'capitalize' as const }}>{v}</div>
              </div>
            ))}
          </div>

          {/* Actions */}
          <div style={{ display: 'flex', gap: 10 }}>
            <button onClick={() => { navigate(`/?vin=${selected.raw_make}+${selected.raw_model}+${selected.raw_year}`); setSelected(null) }} className="btn-primary" style={{ flex: 1, justifyContent: 'center', padding: '12px' }}>
              <i className="ti ti-search" /> Get valuation for this car
            </button>
            <button onClick={() => setSelected(null)} className="btn-secondary" style={{ padding: '12px 20px' }}>
              Close
            </button>
          </div>
        </div>
      </div>
    )}
    </div>
  )
}

// ── DEALER LOGIN ─────────────────────────────────────────────
function DealerLoginPage() {
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [forgotMode, setForgotMode] = useState(false)
  const [resetSent, setResetSent] = useState(false)

  async function handleForgotPassword() {
    if (!email) { setError('Please enter your email address'); return }
    setLoading(true); setError('')
    const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, {
      redirectTo: 'https://www.kenyavin.com/reset-password',
    })
    if (resetError) setError(resetError.message)
    else setResetSent(true)
    setLoading(false)
  }

  async function handleLogin() {
    if (!email || !password) { setError('Please enter your email and password'); return }
    setLoading(true); setError('')
    const { data: authData, error: authError } = await supabase.auth.signInWithPassword({ email, password })
    if (authError) { setError(authError.message); setLoading(false); return }
    const { data: userData, error: roleError } = await supabase.from('users').select('role').eq('id', authData.user.id).maybeSingle()
    if (roleError) console.error('Role lookup error on login:', roleError)
    if (userData?.role === 'admin') navigate('/admin')
    else navigate('/dealer/dashboard')
  }

  const inp: React.CSSProperties = { width: '100%', height: 44, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 10, fontSize: 14, background: 'var(--ink-20)', outline: 'none' }

  return (
    <div style={{ minHeight: '60vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 24px' }}>
      <div style={{ width: '100%', maxWidth: 420 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ width: 56, height: 56, background: 'var(--green-100)', borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
            <i className="ti ti-building-store" style={{ fontSize: 26, color: 'var(--green-700)' }} />
          </div>
          <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 26, color: 'var(--ink-900)', marginBottom: 6 }}>Dealer sign in</h1>
          <p style={{ fontSize: 14, color: 'var(--ink-400)' }}>Sign in to your KenyaVIN dealer account</p>
        </div>
        <div style={{ background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 20, padding: 28 }}>
          <div style={{ display: 'grid', gap: 14, marginBottom: 20 }}>
            <div><label className="field-label">Email address</label><input style={inp} type="email" placeholder="john@dealership.co.ke" value={email} onChange={e => setEmail(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleLogin()} /></div>
            <div><label className="field-label">Password</label><input style={inp} type="password" placeholder="Your password" value={password} onChange={e => setPassword(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleLogin()} /></div>
          </div>
          {error && <div style={{ background: '#FEE9E9', color: '#791F1F', borderRadius: 8, padding: '10px 14px', fontSize: 13, marginBottom: 14 }}><i className="ti ti-alert-circle" /> {error}</div>}
          {resetSent ? (
            <div style={{ background: 'var(--green-50)', border: '1px solid var(--green-200)', borderRadius: 8, padding: '12px 14px', fontSize: 13, color: 'var(--green-700)', textAlign: 'center' as const }}>
              <i className="ti ti-mail" /> Reset email sent! Check your inbox.
            </div>
          ) : forgotMode ? (
            <>
              <button onClick={handleForgotPassword} disabled={loading} className="btn-primary" style={{ width: '100%', justifyContent: 'center', padding: '12px', fontSize: 15 }}>
                {loading ? 'Sending…' : 'Send reset email'}
              </button>
              <button onClick={() => { setForgotMode(false); setError('') }} style={{ width: '100%', background: 'none', border: 'none', fontSize: 13, color: 'var(--ink-400)', cursor: 'pointer', padding: '8px', fontFamily: 'inherit' }}>← Back to sign in</button>
            </>
          ) : (
            <>
              <button onClick={handleLogin} disabled={loading} className="btn-primary" style={{ width: '100%', justifyContent: 'center', padding: '12px', fontSize: 15 }}>
                {loading ? 'Signing in…' : 'Sign in'}
              </button>
              <button onClick={() => { setForgotMode(true); setError('') }} style={{ width: '100%', background: 'none', border: 'none', fontSize: 13, color: 'var(--green-600)', cursor: 'pointer', padding: '8px', fontFamily: 'inherit' }}>Forgot password?</button>
            </>
          )}
          <div style={{ textAlign: 'center', marginTop: 20, fontSize: 13, color: 'var(--ink-400)' }}>
            Don't have an account?{' '}
            <span onClick={() => navigate('/dealer/register')} style={{ color: 'var(--green-600)', cursor: 'pointer', fontWeight: 500 }}>Register your dealership</span>
          </div>
        </div>
      </div>
    </div>
  )
}

// ── DEALER REGISTER ──────────────────────────────────────────
function DealerRegisterPage() {
  const navigate = useNavigate()
  const [step, setStep] = useState<1 | 2 | 3 | 4>(1)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [form, setForm] = useState({
    email: '', password: '', confirmPassword: '', fullName: '', phone: '',
    businessName: '', kraPin: '', ntsaLicense: '', county: 'Nairobi', town: '', address: '',
    yearsInBusiness: '', monthlyVolume: '', hasPhysicalLot: false,
    specialization: [] as string[],
  })
  const set = (k: string, v: any) => setForm(f => ({ ...f, [k]: v }))
  const inp: React.CSSProperties = { width: '100%', height: 44, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 10, fontSize: 14, background: 'var(--ink-20)', outline: 'none' }

  const specializations = ['Japanese imports', 'European cars', 'Commercial vehicles', 'SUVs & 4x4s', 'Budget cars (under KES 1M)', 'Luxury vehicles', 'Electric & hybrid']

  async function handleSubmit() {
    if (form.password !== form.confirmPassword) { setError('Passwords do not match'); return }
    setLoading(true); setError('')
    try {
      const { data, error: authError } = await supabase.auth.signUp({
        email: form.email, password: form.password,
        options: { data: { full_name: form.fullName, phone: form.phone } },
      })
      if (authError) throw authError
      if (!data.user) throw new Error('Signup failed')

      const { data: dealerData, error: dealerError } = await supabase.from('dealers').insert({
        user_id: data.user.id, business_name: form.businessName,
        kra_pin: form.kraPin, ntsa_license: form.ntsaLicense || null,
        county: form.county, town: form.town,
        physical_address: form.address || null, status: 'pending',
      }).select().single()
      if (dealerError) throw dealerError

      await supabase.from('dealer_onboarding').insert({
        dealer_id: dealerData.id,
        years_in_business: form.yearsInBusiness,
        monthly_stock_volume: form.monthlyVolume,
        specialization: form.specialization,
        has_physical_lot: form.hasPhysicalLot,
        lot_address: form.address || null,
      })
      setStep(4)
    } catch (e: any) {
      setError(e.message || 'Registration failed. Please try again.')
    } finally { setLoading(false) }
  }

  const stepTitles = ['', 'Your account', 'Dealership details', 'Business profile']

  return (
    <div style={{ maxWidth: 560, margin: '48px auto', padding: '0 24px 48px' }}>
      <button onClick={() => step > 1 && step < 4 ? setStep(s => (s - 1) as any) : navigate('/dealer')} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--ink-400)', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 24 }}>
        <i className="ti ti-arrow-left" /> {step > 1 && step < 4 ? 'Back' : 'Back to dealer portal'}
      </button>

      {step < 4 && (
        <>
          <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: 'var(--ink-900)', marginBottom: 4 }}>Register your dealership</h1>
          <p style={{ fontSize: 14, color: 'var(--ink-400)', marginBottom: 24 }}>Verification takes 1–2 business days. You'll need your KRA PIN.</p>
          {/* Progress */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 32 }}>
            {[1, 2, 3].map((s, i) => (
              <div key={s} style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 600, background: step > s ? 'var(--green-500)' : step === s ? 'var(--green-600)' : 'var(--ink-100)', color: step >= s ? '#fff' : 'var(--ink-400)', transition: 'all .3s' }}>
                    {step > s ? <i className="ti ti-check" style={{ fontSize: 13 }} /> : s}
                  </div>
                  <span style={{ fontSize: 10, color: step === s ? 'var(--green-700)' : 'var(--ink-400)', fontWeight: step === s ? 600 : 400, whiteSpace: 'nowrap' }}>{stepTitles[s]}</span>
                </div>
                {i < 2 && <div style={{ flex: 1, height: 2, background: step > s ? 'var(--green-400)' : 'var(--ink-100)', margin: '0 4px', marginBottom: 20, transition: 'background .3s' }} />}
              </div>
            ))}
          </div>
        </>
      )}

      {step === 4 ? (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <div style={{ width: 72, height: 72, background: 'var(--green-100)', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
            <i className="ti ti-circle-check" style={{ fontSize: 36, color: 'var(--green-600)' }} />
          </div>
          <h2 style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: 'var(--ink-900)', marginBottom: 12 }}>Application submitted!</h2>
          <p style={{ fontSize: 14, color: 'var(--ink-400)', lineHeight: 1.7, marginBottom: 12, maxWidth: 380, margin: '0 auto 12px' }}>
            Your application is under review. Our team will verify your KRA PIN and business details within <strong>1–2 business days</strong>.
          </p>
          <p style={{ fontSize: 14, color: 'var(--ink-400)', marginBottom: 32 }}>You'll receive an email and SMS once your account is approved.</p>
          <div style={{ background: 'var(--green-50)', border: '1px solid var(--green-200)', borderRadius: 12, padding: '16px 20px', marginBottom: 32, textAlign: 'left' }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-700)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 10 }}>What happens next</div>
            {[['1', 'KRA PIN verification', 'Automatic — usually within minutes'],['2', 'Document review', 'Our team reviews your CR12 and NTSA license'],['3', 'Account activated', 'You get full access to the B2B marketplace']].map(([n, t, d]) => (
              <div key={n} style={{ display: 'flex', gap: 10, marginBottom: 8 }}>
                <div style={{ width: 20, height: 20, borderRadius: '50%', background: 'var(--green-200)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: 'var(--green-800)', flexShrink: 0, marginTop: 1 }}>{n}</div>
                <div><div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)' }}>{t}</div><div style={{ fontSize: 12, color: 'var(--ink-400)' }}>{d}</div></div>
              </div>
            ))}
          </div>
          <button className="btn-primary" onClick={() => navigate('/')} style={{ padding: '12px 28px', fontSize: 15 }}>Back to home</button>
        </div>
      ) : (
        <div style={{ background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 20, padding: 28 }}>
          {step === 1 && (
            <>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 1 — Create your account</div>
              <div style={{ display: 'grid', gap: 14 }}>
                <div><label className="field-label">Full name</label><input style={inp} placeholder="John Kamau" value={form.fullName} onChange={e => set('fullName', e.target.value)} /></div>
                <div><label className="field-label">Email address</label><input style={inp} type="email" placeholder="john@dealership.co.ke" value={form.email} onChange={e => set('email', e.target.value)} /></div>
                <div><label className="field-label">Phone number</label><input style={inp} placeholder="+254 7XX XXX XXX" value={form.phone} onChange={e => set('phone', e.target.value)} /></div>
                <div><label className="field-label">Password</label><input style={inp} type="password" placeholder="Min. 8 characters" value={form.password} onChange={e => set('password', e.target.value)} /></div>
                <div><label className="field-label">Confirm password</label><input style={inp} type="password" placeholder="Repeat password" value={form.confirmPassword} onChange={e => set('confirmPassword', e.target.value)} /></div>
              </div>
            </>
          )}

          {step === 2 && (
            <>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 2 — Dealership details</div>
              <div style={{ display: 'grid', gap: 14 }}>
                <div><label className="field-label">Business / dealership name</label><input style={inp} placeholder="Simba Motors Ltd" value={form.businessName} onChange={e => set('businessName', e.target.value)} /></div>
                <div>
                  <label className="field-label">KRA PIN <span style={{ color: 'var(--green-600)' }}>— will be verified automatically</span></label>
                  <input style={inp} placeholder="P000000000X" value={form.kraPin} onChange={e => set('kraPin', e.target.value.toUpperCase())} />
                </div>
                <div><label className="field-label">NTSA dealer license (optional)</label><input style={inp} placeholder="DL/2024/XXXXX" value={form.ntsaLicense} onChange={e => set('ntsaLicense', e.target.value)} /></div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div><label className="field-label">County</label>
                    <select style={inp} value={form.county} onChange={e => set('county', e.target.value)}>
                      {['Nairobi', 'Mombasa', 'Kisumu', 'Nakuru', 'Eldoret', 'Thika', 'Nyeri', 'Meru', 'Kakamega'].map(c => <option key={c}>{c}</option>)}
                    </select>
                  </div>
                  <div><label className="field-label">Town / area</label><input style={inp} placeholder="Westlands" value={form.town} onChange={e => set('town', e.target.value)} /></div>
                </div>
                <div><label className="field-label">Physical address</label><input style={inp} placeholder="e.g. Off Waiyaki Way, next to…" value={form.address} onChange={e => set('address', e.target.value)} /></div>
              </div>
            </>
          )}

          {step === 3 && (
            <>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 3 — Business profile</div>
              <div style={{ display: 'grid', gap: 14 }}>
                <div><label className="field-label">Years in the car business</label>
                  <select style={inp} value={form.yearsInBusiness} onChange={e => set('yearsInBusiness', e.target.value)}>
                    <option value="">Select…</option>
                    {['Less than 1 year', '1–2 years', '3–5 years', '6–10 years', 'Over 10 years'].map(v => <option key={v}>{v}</option>)}
                  </select>
                </div>
                <div><label className="field-label">Monthly stock volume (approx. units)</label>
                  <select style={inp} value={form.monthlyVolume} onChange={e => set('monthlyVolume', e.target.value)}>
                    <option value="">Select…</option>
                    {['1–5 units', '6–10 units', '11–20 units', '21–50 units', '50+ units'].map(v => <option key={v}>{v}</option>)}
                  </select>
                </div>
                <div>
                  <label className="field-label">Specialization (select all that apply)</label>
                  <div style={{ display: 'flex', flexWrap: 'wrap' as const, gap: 8, marginTop: 4 }}>
                    {specializations.map(s => (
                      <button key={s} onClick={() => set('specialization', form.specialization.includes(s) ? form.specialization.filter((x: string) => x !== s) : [...form.specialization, s])}
                        style={{ padding: '6px 12px', fontSize: 12, borderRadius: 20, border: `1.5px solid ${form.specialization.includes(s) ? 'var(--green-500)' : 'var(--ink-100)'}`, background: form.specialization.includes(s) ? 'var(--green-50)' : '#fff', color: form.specialization.includes(s) ? 'var(--green-700)' : 'var(--ink-500)', cursor: 'pointer' }}>
                        {s}
                      </button>
                    ))}
                  </div>
                </div>
                <div>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
                    <input type="checkbox" checked={form.hasPhysicalLot} onChange={e => set('hasPhysicalLot', e.target.checked)} />
                    I have a physical car lot / showroom
                  </label>
                </div>
              </div>
            </>
          )}

          {error && <div style={{ background: '#FEE9E9', color: '#791F1F', borderRadius: 8, padding: '10px 14px', fontSize: 13, marginTop: 16 }}><i className="ti ti-alert-circle" /> {error}</div>}

          <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
            {step > 1 && <button className="btn-secondary" style={{ flex: '0 0 auto' }} onClick={() => setStep(s => (s - 1) as any)}>Back</button>}
            <button className="btn-primary" disabled={loading} style={{ flex: 1, justifyContent: 'center', padding: '12px', fontSize: 14 }}
              onClick={() => step < 3 ? setStep(s => (s + 1) as any) : handleSubmit()}>
              {loading ? 'Submitting…' : step < 3 ? 'Continue' : 'Submit application'}
            </button>
          </div>
        </div>
      )}
    </div>
  )
}

// ── DEALER DASHBOARD ─────────────────────────────────────────
function DealerDashboardPage() {
  const navigate = useNavigate()
  const { user, dealer, isAdmin, loading } = useAuth()

  useEffect(() => {
    if (!loading && !user) navigate('/dealer/login')
  }, [user, loading])

  useEffect(() => {
    if (!loading && isAdmin) navigate('/admin')
  }, [isAdmin, loading])

  if (loading) return <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 32 }} /></div>

    if (!dealer) return (
    <div style={{ maxWidth: 600, margin: '60px auto', padding: '0 24px', textAlign: 'center' }}>
      <div style={{ width: 64, height: 64, background: 'var(--green-100)', borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
        <i className="ti ti-building-store" style={{ fontSize: 28, color: 'var(--green-700)' }} />
      </div>
      <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 26, color: 'var(--ink-900)', marginBottom: 12 }}>No dealer account found</h1>
      <p style={{ fontSize: 14, color: 'var(--ink-400)', marginBottom: 24 }}>This account is not linked to a dealership. Would you like to register one?</p>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
        <button className="btn-primary" onClick={() => navigate('/dealer/register')} style={{ padding: '10px 24px' }}>Register dealership</button>
        <button className="btn-secondary" onClick={() => navigate('/')} style={{ padding: '10px 20px' }}>Back to home</button>
      </div>
    </div>
  )

  // Pending state
  if (dealer.status === 'pending') {
    return (
      <div style={{ maxWidth: 600, margin: '60px auto', padding: '0 24px', textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, background: '#FEF0D6', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
          <i className="ti ti-clock" style={{ fontSize: 32, color: '#E07B00' }} />
        </div>
        <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: 'var(--ink-900)', marginBottom: 12 }}>Application under review</h1>
        <p style={{ fontSize: 15, color: 'var(--ink-400)', lineHeight: 1.7, marginBottom: 24 }}>
          Hi <strong>{dealer.business_name}</strong>, your application is being reviewed by our team. We'll verify your KRA PIN and business details within <strong>1–2 business days</strong>.
        </p>
        <div style={{ background: '#FEF0D6', border: '1px solid #FAC875', borderRadius: 12, padding: '16px 20px', marginBottom: 24, textAlign: 'left' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#854F0B', marginBottom: 8 }}>Application status</div>
          {[['Business name', dealer.business_name], ['KRA PIN', dealer.kra_pin], ['County', dealer.county + ', ' + dealer.town], ['Submitted', new Date(dealer.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' })]].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '5px 0', borderBottom: '1px solid rgba(250,200,117,.4)' }}>
              <span style={{ color: '#854F0B' }}>{k}</span><span style={{ fontWeight: 500, color: '#633806' }}>{v}</span>
            </div>
          ))}
        </div>
        <button className="btn-secondary" onClick={() => navigate('/')} style={{ padding: '10px 24px' }}>Back to home</button>
      </div>
    )
  }

  // Rejected state
  if (dealer.status === 'rejected') {
    return (
      <div style={{ maxWidth: 600, margin: '60px auto', padding: '0 24px', textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, background: '#FEE9E9', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
          <i className="ti ti-x" style={{ fontSize: 32, color: '#C53030' }} />
        </div>
        <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: 'var(--ink-900)', marginBottom: 12 }}>Application not approved</h1>
        <p style={{ fontSize: 15, color: 'var(--ink-400)', lineHeight: 1.7, marginBottom: 12 }}>
          Unfortunately your application was not approved.
        </p>
        {dealer.rejected_reason && (
          <div style={{ background: '#FEE9E9', border: '1px solid #FCA5A5', borderRadius: 12, padding: '14px 18px', marginBottom: 24, textAlign: 'left' }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: '#791F1F', marginBottom: 4 }}>Reason</div>
            <div style={{ fontSize: 14, color: '#C53030' }}>{dealer.rejected_reason}</div>
          </div>
        )}
        <p style={{ fontSize: 14, color: 'var(--ink-400)', marginBottom: 24 }}>Please contact us at <strong>support@kenyavin.co.ke</strong> if you believe this is an error.</p>
        <button className="btn-secondary" onClick={() => navigate('/')} style={{ padding: '10px 24px' }}>Back to home</button>
      </div>
    )
  }

  // Verified — full dashboard
  return <DealerDashboardVerified dealer={dealer} />
}

function DealerDashboardVerified({ dealer }: { dealer: any }) {
  const navigate = useNavigate()
  const [stock, setStock] = useState<any[]>([])
  const [stockLoading, setStockLoading] = useState(true)
  const [dashTab, setDashTab] = useState<'stock'|'requests'|'offers'>('stock')



  async function loadStock() {
    setStockLoading(true)
    const { data, error } = await supabase
      .from('stock_listings')
      .select('*, vehicle:vehicles(*)')
      .eq('dealer_id', dealer.id)
      .order('created_at', { ascending: false })
    console.log('Stock data:', data)
    console.log('Stock error:', error)
    console.log('Dealer ID:', dealer.id)
    setStock(data || [])
    setStockLoading(false)
  }

  async function removeStock(id: string) {
    if (!confirm('Remove this vehicle from stock?')) return
    await supabase.from('stock_listings').delete().eq('id', id)
    loadStock()
  }

  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')
  const totalValue = stock.reduce((sum, s) => sum + Number(s.retail_price_kes || 0), 0)

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: '36px 24px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 28 }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 4 }}>Dealer portal</div>
          <div style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: 'var(--ink-900)' }}>{dealer.business_name}</div>
          <div style={{ fontSize: 14, color: 'var(--ink-400)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
            <i className="ti ti-shield-check" style={{ color: 'var(--green-500)' }} /> Verified dealer · {dealer.county}
          </div>
        </div>
        <button className="btn-primary" onClick={() => navigate('/dealer/add-vehicle')}>
          <i className="ti ti-plus" /> Add vehicle
        </button>
      </div>

      {/* Section tabs */}
      <div style={{ display: 'flex', gap: 0, marginBottom: 24, borderBottom: '1px solid var(--ink-100)' }}>
        {([{ key: 'stock', label: 'My stock', icon: 'ti-car' }, { key: 'requests', label: 'Sell requests', icon: 'ti-tag' }, { key: 'offers', label: 'Trade offers', icon: 'ti-transfer' }] as const).map(tab => (
          <button key={tab.key} onClick={() => setDashTab(tab.key)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 18px', border: 'none', borderBottom: `2px solid ${dashTab === tab.key ? 'var(--green-500)' : 'transparent'}`, fontSize: 13, fontWeight: 500, cursor: 'pointer', background: 'none', color: dashTab === tab.key ? 'var(--green-700)' : 'var(--ink-400)', marginBottom: -1, fontFamily: 'inherit' }}>
            <i className={`ti ${tab.icon}`} style={{ fontSize: 15 }} /> {tab.label}
          </button>
        ))}
      </div>

      {dashTab === 'requests' && <DealerSellRequests dealer={dealer} />}
      {dashTab === 'offers' && <DealerTradeOffers dealer={dealer} />}
      {dashTab === 'stock' && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 28 }}>
        {[
          [stock.length.toString(), 'Units in stock', 'ti-car'],
          [totalValue > 0 ? fmt(totalValue) : 'KES 0', 'Stock value', 'ti-coin'],
          [stock.filter(s => s.is_b2b_listed).length.toString(), 'B2B listed', 'ti-transfer'],
          [stock.filter(s => s.status === 'active').length.toString(), 'Active listings', 'ti-circle-check'],
        ].map(([v, l, icon]) => (
          <div key={l} style={{ background: '#fff', borderRadius: 16, padding: '18px 20px', border: '1px solid var(--ink-100)', display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{ width: 40, height: 40, background: 'var(--green-50)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`ti ${icon}`} style={{ fontSize: 18, color: 'var(--green-600)' }} />
            </div>
            <div>
              <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, color: 'var(--ink-900)' }}>{v}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-400)', marginTop: 2 }}>{l}</div>
            </div>
          </div>
        ))}
      </div>}

      {/* Stock list */}
      {dashTab === 'stock' && <>{stockLoading ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 32 }} /></div>
      ) : stock.length === 0 ? (
        <div style={{ background: '#fff', borderRadius: 20, border: '1px solid var(--ink-100)', padding: '60px 40px', textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, background: 'var(--green-50)', borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
            <i className="ti ti-car" style={{ fontSize: 30, color: 'var(--green-400)' }} />
          </div>
          <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, color: 'var(--ink-900)', marginBottom: 8 }}>No stock listed yet</div>
          <p style={{ fontSize: 14, color: 'var(--ink-400)', marginBottom: 24, maxWidth: 380, margin: '0 auto 24px' }}>
            Add your first vehicle to start receiving enquiries and trade offers.
          </p>
          <button className="btn-primary" onClick={() => navigate('/dealer/add-vehicle')} style={{ padding: '12px 28px', fontSize: 15 }}>
            <i className="ti ti-plus" /> Add your first vehicle
          </button>
        </div>
      ) : (
        <div style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 20px', borderBottom: '1px solid var(--ink-50)' }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-700)' }}>Your stock ({stock.length} vehicles)</div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>{['Vehicle', 'Condition', 'Mileage', 'Retail price', 'Wholesale', 'Listed on', 'Status', ''].map(h => (
                <th key={h} style={{ textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', padding: '10px 16px', background: 'var(--ink-20)', borderBottom: '1px solid var(--ink-100)' }}>{h}</th>
              ))}</tr>
            </thead>
            <tbody>
              {stock.map(s => (
                <tr key={s.id} style={{ borderBottom: '1px solid var(--ink-50)' }}>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>
                      {s.vehicle ? `${s.vehicle.year} ${s.vehicle.make} ${s.vehicle.model}` : 'Unknown'}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--ink-400)', marginTop: 1 }}>
                      {s.vehicle?.vin && <span style={{ fontFamily: 'DM Mono' }}>{s.vehicle.vin}</span>}
                    </div>
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: 13, color: 'var(--ink-500)', textTransform: 'capitalize' as const }}>{s.condition}</td>
                  <td style={{ padding: '12px 16px', fontSize: 13, color: 'var(--ink-500)' }}>{s.odometer_km ? `${Math.round(s.odometer_km/1000)}K km` : '—'}</td>
                  <td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>{fmt(s.retail_price_kes)}</td>
                  <td style={{ padding: '12px 16px', fontSize: 13, color: 'var(--green-700)' }}>
                    {s.wholesale_price_kes ? fmt(s.wholesale_price_kes) : <span style={{ color: 'var(--ink-300)' }}>—</span>}
                  </td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 3 }}>
                      {s.is_retail_listed && <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 20, background: 'var(--green-100)', color: 'var(--green-700)', display: 'inline-block' }}>Retail</span>}
                      {s.is_b2b_listed && <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 20, background: '#EDE9FE', color: '#5B21B6', display: 'inline-block' }}>B2B</span>}
                    </div>
                  </td>
                  <td style={{ padding: '12px 16px' }}>
                    <span style={{ fontSize: 11, fontWeight: 600, padding: '3px 8px', borderRadius: 20, background: s.status === 'active' ? 'var(--green-100)' : 'var(--ink-50)', color: s.status === 'active' ? 'var(--green-700)' : 'var(--ink-400)', textTransform: 'capitalize' as const }}>{s.status}</span>
                  </td>
                  <td style={{ padding: '12px 16px' }}>
                    <button onClick={() => removeStock(s.id)} style={{ padding: '4px 10px', border: '1px solid #FCA5A5', borderRadius: 6, fontSize: 11, cursor: 'pointer', background: '#fff', color: '#C53030' }}>
                      <i className="ti ti-trash" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      </>}
    </div>
  )
}

// ── DEALER PAGE (landing) ────────────────────────────────────
function DealerPage() {
  const navigate = useNavigate()
  const { user, dealer } = useAuth()

  useEffect(() => {
    if (!user) return
    supabase.from('users').select('role').eq('id', user.id).maybeSingle().then(({ data, error }) => {
      if (error) console.error('Role lookup error in DealerPage:', error)
      if (data?.role === 'admin') navigate('/admin')
      else if (dealer) navigate('/dealer/dashboard')
      else navigate('/dealer/register')
    })
  }, [user, dealer])

  return (
    <div style={{ maxWidth: 900, margin: '48px auto', padding: '0 24px', textAlign: 'center' }}>
      <div style={{ width: 64, height: 64, background: 'var(--green-100)', borderRadius: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px', fontSize: 32 }}>
        <i className="ti ti-building-store" style={{ color: 'var(--green-700)' }} />
      </div>
      <h1 style={{ fontFamily: '"DM Serif Display"', fontSize: 32, color: 'var(--ink-900)', marginBottom: 12 }}>Dealer B2B Portal</h1>
      <p style={{ fontSize: 15, color: 'var(--ink-400)', lineHeight: 1.6, marginBottom: 32, maxWidth: 500, margin: '0 auto 32px' }}>
        List wholesale stock, receive trade offers, and connect with 340+ verified dealers across Kenya.
      </p>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginBottom: 48, flexWrap: 'wrap' as const, padding: '0 16px' }}>
        <button className="btn-primary" style={{ padding: '14px 32px', fontSize: 15, flex: '1 1 200px', justifyContent: 'center', maxWidth: 280 }} onClick={() => navigate('/dealer/register')}>
          <i className="ti ti-building-store" /> Register dealership
        </button>
        <button className="btn-secondary" style={{ padding: '14px 28px', fontSize: 15, flex: '1 1 140px', justifyContent: 'center', maxWidth: 200 }} onClick={() => navigate('/dealer/login')}>
          <i className="ti ti-login" /> Sign in
        </button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, textAlign: 'left' as const }}>
        {[['ti-transfer', 'B2B marketplace', 'Trade vehicles wholesale with verified dealers only.'], ['ti-chart-bar', 'Stock analytics', 'Track days-on-market, margins, and revenue split.'], ['ti-tag', 'Trade offers', 'Receive cash offers and swap proposals instantly.']].map(([icon, title, body]) => (
          <div key={String(title)} style={{ background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 16, padding: 20 }}>
            <div style={{ width: 36, height: 36, background: 'var(--green-100)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
              <i className={`ti ${icon}`} style={{ fontSize: 18, color: 'var(--green-700)' }} />
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 6 }}>{title}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-400)', lineHeight: 1.5 }}>{body}</div>
          </div>
        ))}
      </div>
    </div>
  )
}

// ── ADMIN DASHBOARD ──────────────────────────────────────────
function AdminPage() {
  const navigate = useNavigate()
  const [section, setSection] = useState<'dealers' | 'market' | 'b2b'>('dealers')
  const [dealers, setDealers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<'pending' | 'verified' | 'rejected'>('pending')
  const [actionLoading, setActionLoading] = useState<string | null>(null)
  const [rejectReason, setRejectReason] = useState('')
  const [rejectingId, setRejectingId] = useState<string | null>(null)
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [onboarding, setOnboarding] = useState<Record<string, any>>({})
  const [stats, setStats] = useState({ total: 0, pending: 0, verified: 0, rejected: 0, listings: 0 })

  useEffect(() => { loadDealers(); loadStats() }, [filter])

  async function loadStats() {
    const [{ count: total }, { count: pending }, { count: verified }, { count: rejected }, { count: listings }] = await Promise.all([
      supabase.from('dealers').select('*', { count: 'exact', head: true }),
      supabase.from('dealers').select('*', { count: 'exact', head: true }).eq('status', 'pending'),
      supabase.from('dealers').select('*', { count: 'exact', head: true }).eq('status', 'verified'),
      supabase.from('dealers').select('*', { count: 'exact', head: true }).eq('status', 'rejected'),
      supabase.from('market_listings').select('*', { count: 'exact', head: true }),
    ])
    setStats({ total: total || 0, pending: pending || 0, verified: verified || 0, rejected: rejected || 0, listings: listings || 0 })
  }

  async function loadDealers() {
    setLoading(true)
    const { data } = await supabase.from('dealers').select('*').eq('status', filter).order('created_at', { ascending: false })
    setDealers(data || [])
    setLoading(false)
  }

  async function loadOnboarding(dealerId: string) {
    if (onboarding[dealerId]) return
    const { data } = await supabase.from('dealer_onboarding').select('*').eq('dealer_id', dealerId).maybeSingle()
    setOnboarding(prev => ({ ...prev, [dealerId]: data || {} }))
  }

  async function toggleExpand(dealerId: string) {
    if (expandedId === dealerId) { setExpandedId(null); return }
    setExpandedId(dealerId)
    await loadOnboarding(dealerId)
  }

  async function approve(id: string) {
    setActionLoading(id)
    await supabase.from('dealers').update({ status: 'verified', verified_at: new Date().toISOString() }).eq('id', id)
    await loadDealers(); await loadStats()
    setActionLoading(null)
  }

  async function reject(id: string) {
    if (!rejectReason) { alert('Please enter a rejection reason'); return }
    setActionLoading(id)
    await supabase.from('dealers').update({ status: 'rejected', rejected_reason: rejectReason }).eq('id', id)
    setRejectingId(null); setRejectReason('')
    await loadDealers(); await loadStats()
    setActionLoading(null)
  }

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: '36px 24px' }}>
      {/* Header */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 4 }}>Admin dashboard</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontFamily: '"DM Serif Display"', fontSize: 28, color: 'var(--ink-900)' }}>KenyaVIN platform overview</div>
          <button onClick={() => navigate('/admin/analytics')} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', background: 'var(--green-600)', color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit' }}><i className="ti ti-chart-bar" style={{ fontSize: 15 }} /> Analytics</button>
        </div>
      </div>

      {/* Stats */}
      <div className="admin-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 12, marginBottom: 28 }}>
        {[
          { val: stats.total, label: 'Total dealers', icon: 'ti-building-store', color: 'var(--green-100)', icolor: 'var(--green-700)' },
          { val: stats.pending, label: 'Pending review', icon: 'ti-clock', color: '#FEF0D6', icolor: '#854F0B' },
          { val: stats.verified, label: 'Verified dealers', icon: 'ti-shield-check', color: 'var(--green-100)', icolor: 'var(--green-700)' },
          { val: stats.rejected, label: 'Rejected', icon: 'ti-x', color: '#FEE9E9', icolor: '#791F1F' },
          { val: stats.listings, label: 'Market listings', icon: 'ti-car', color: '#E0EAFF', icolor: '#1A4FA8' },
        ].map(s => (
          <div key={s.label} style={{ background: '#fff', borderRadius: 14, padding: '16px 18px', border: '1px solid var(--ink-100)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 9, background: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`ti ${s.icon}`} style={{ fontSize: 17, color: s.icolor }} />
            </div>
            <div>
              <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, color: 'var(--ink-900)', lineHeight: 1 }}>{s.val}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-400)', marginTop: 2 }}>{s.label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Main section tabs */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 24, borderBottom: '1px solid var(--ink-100)', paddingBottom: 0, flexWrap: 'wrap' as const }}>
        {([
          { key: 'dealers', label: 'Dealer applications', icon: 'ti-building-store' },
          { key: 'market', label: 'Market listings', icon: 'ti-car' },
          { key: 'b2b', label: 'B2B stock', icon: 'ti-transfer' },
        ] as const).map(tab => (
          <button key={tab.key} onClick={() => setSection(tab.key)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '10px 18px', border: 'none', borderBottom: `2px solid ${section === tab.key ? 'var(--green-500)' : 'transparent'}`, fontSize: 13, fontWeight: 500, cursor: 'pointer', background: 'none', color: section === tab.key ? 'var(--green-700)' : 'var(--ink-400)', marginBottom: -1 }}>
            <i className={`ti ${tab.icon}`} style={{ fontSize: 15 }} /> {tab.label}
            {tab.key === 'dealers' && stats.pending > 0 && <span style={{ background: '#E24B4A', color: '#fff', borderRadius: 10, padding: '1px 6px', fontSize: 10, marginLeft: 2 }}>{stats.pending}</span>}
          </button>
        ))}
      </div>

      {/* Dealers section */}
      {section === 'dealers' && (<>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap' as const, gap: 10 }}>
        <div style={{ fontFamily: '"DM Serif Display"', fontSize: 20, color: 'var(--ink-900)' }}>Dealer applications</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' as const }}>
          {(['pending', 'verified', 'rejected'] as const).map(f => (
            <button key={f} onClick={() => setFilter(f)} style={{ padding: '7px 16px', borderRadius: 8, border: 'none', fontSize: 12, fontWeight: 500, cursor: 'pointer', background: filter === f ? 'var(--green-600)' : 'var(--ink-50)', color: filter === f ? '#fff' : 'var(--ink-500)', textTransform: 'capitalize' as const }}>
              {f} {f === 'pending' && stats.pending > 0 && <span style={{ background: '#E24B4A', color: '#fff', borderRadius: 10, padding: '1px 6px', fontSize: 10, marginLeft: 4 }}>{stats.pending}</span>}
            </button>
          ))}
        </div>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 32 }} /></div>
      ) : dealers.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)', fontSize: 14 }}>No {filter} applications</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {dealers.map(d => {
            const isExpanded = expandedId === d.id
            const ob = onboarding[d.id]
            return (
              <div key={d.id} style={{ background: '#fff', borderRadius: 16, border: `1px solid ${isExpanded ? 'var(--green-300)' : 'var(--ink-100)'}`, overflow: 'hidden', transition: 'border-color .15s' }}>
                {/* Card header — always visible */}
                <div style={{ padding: '18px 20px', cursor: 'pointer' }} onClick={() => toggleExpand(d.id)}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                        <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink-900)' }}>{d.business_name}</div>
                        <span style={{ fontSize: 11, fontWeight: 600, padding: '3px 10px', borderRadius: 20, background: d.status === 'verified' ? 'var(--green-100)' : d.status === 'pending' ? '#FEF0D6' : '#FEE9E9', color: d.status === 'verified' ? 'var(--green-700)' : d.status === 'pending' ? '#854F0B' : '#791F1F', textTransform: 'capitalize' as const }}>
                          {d.status}
                        </span>
                      </div>
                      <div style={{ fontSize: 13, color: 'var(--ink-400)', display: 'flex', gap: 16, flexWrap: 'wrap' as const }}>
                        <span><i className="ti ti-map-pin" style={{ fontSize: 12 }} /> {d.town}, {d.county}</span>
                        <span><i className="ti ti-calendar" style={{ fontSize: 12 }} /> Applied {new Date(d.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short', year: 'numeric' })}</span>
                        <span><i className="ti ti-id" style={{ fontSize: 12 }} /> KRA: {d.kra_pin}</span>
                        {d.ntsa_license && <span><i className="ti ti-license" style={{ fontSize: 12 }} /> NTSA: {d.ntsa_license}</span>}
                      </div>
                    </div>
                    <i className={`ti ${isExpanded ? 'ti-chevron-up' : 'ti-chevron-down'}`} style={{ fontSize: 18, color: 'var(--ink-300)', marginLeft: 12, marginTop: 2 }} />
                  </div>
                </div>

                {/* Expanded detail panel */}
                {isExpanded && (
                  <div style={{ borderTop: '1px solid var(--ink-50)', padding: '20px' }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>

                      {/* Business details */}
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 12 }}>Business details</div>
                        {[
                          ['Business name', d.business_name],
                          ['KRA PIN', d.kra_pin],
                          ['NTSA License', d.ntsa_license || 'Not provided'],
                          ['County', d.county],
                          ['Town', d.town],
                          ['Address', d.physical_address || 'Not provided'],
                        ].map(([k, v]) => (
                          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderBottom: '1px solid var(--ink-50)', fontSize: 13 }}>
                            <span style={{ color: 'var(--ink-400)' }}>{k}</span>
                            <span style={{ fontWeight: 500, color: 'var(--ink-700)', textAlign: 'right' as const, maxWidth: '60%' }}>{v}</span>
                          </div>
                        ))}
                      </div>

                      {/* Onboarding profile */}
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 12 }}>Business profile</div>
                        {ob === undefined ? (
                          <div style={{ color: 'var(--ink-300)', fontSize: 13 }}>Loading…</div>
                        ) : Object.keys(ob).length === 0 ? (
                          <div style={{ color: 'var(--ink-300)', fontSize: 13 }}>No onboarding data submitted</div>
                        ) : (
                          <>
                            {[
                              ['Years in business', ob.years_in_business],
                              ['Monthly volume', ob.monthly_stock_volume],
                              ['Has physical lot', ob.has_physical_lot ? 'Yes' : 'No'],
                              ['Lot address', ob.lot_address || 'Not provided'],
                            ].map(([k, v]) => (
                              <div key={String(k)} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderBottom: '1px solid var(--ink-50)', fontSize: 13 }}>
                                <span style={{ color: 'var(--ink-400)' }}>{k}</span>
                                <span style={{ fontWeight: 500, color: 'var(--ink-700)' }}>{v || '—'}</span>
                              </div>
                            ))}
                            {ob.specialization?.length > 0 && (
                              <div style={{ marginTop: 10 }}>
                                <div style={{ fontSize: 11, color: 'var(--ink-400)', marginBottom: 6 }}>Specialization</div>
                                <div style={{ display: 'flex', flexWrap: 'wrap' as const, gap: 6 }}>
                                  {ob.specialization.map((s: string) => (
                                    <span key={s} style={{ fontSize: 11, padding: '3px 10px', borderRadius: 20, background: 'var(--green-100)', color: 'var(--green-700)', fontWeight: 500 }}>{s}</span>
                                  ))}
                                </div>
                              </div>
                            )}
                          </>
                        )}
                      </div>
                    </div>

                    {/* Action buttons */}
                    {filter === 'pending' && (
                      rejectingId === d.id ? (
                        <div style={{ background: '#FEE9E9', borderRadius: 10, padding: 14 }}>
                          <div style={{ fontSize: 13, fontWeight: 500, color: '#791F1F', marginBottom: 8 }}>Enter rejection reason:</div>
                          <input value={rejectReason} onChange={e => setRejectReason(e.target.value)} placeholder="e.g. KRA PIN could not be verified…" style={{ width: '100%', height: 40, padding: '0 12px', border: '1.5px solid #FCA5A5', borderRadius: 8, fontSize: 13, outline: 'none', marginBottom: 10, background: '#fff' }} />
                          <div style={{ display: 'flex', gap: 8 }}>
                            <button onClick={() => reject(d.id)} disabled={actionLoading === d.id} style={{ padding: '8px 18px', background: '#C53030', color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
                              {actionLoading === d.id ? 'Rejecting…' : 'Confirm rejection'}
                            </button>
                            <button onClick={() => setRejectingId(null)} style={{ padding: '8px 14px', background: 'var(--ink-50)', color: 'var(--ink-500)', border: 'none', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Cancel</button>
                          </div>
                        </div>
                      ) : (
                        <div style={{ display: 'flex', gap: 8, paddingTop: 4 }}>
                          <button onClick={() => approve(d.id)} disabled={actionLoading === d.id} className="btn-primary" style={{ padding: '10px 24px', fontSize: 14 }}>
                            <i className="ti ti-shield-check" /> {actionLoading === d.id ? 'Approving…' : 'Approve dealer'}
                          </button>
                          <button onClick={() => setRejectingId(d.id)} className="btn-secondary" style={{ padding: '10px 18px', fontSize: 14 }}>
                            <i className="ti ti-x" /> Reject
                          </button>
                        </div>
                      )
                    )}

                    {filter === 'rejected' && d.rejected_reason && (
                      <div style={{ background: '#FEE9E9', borderRadius: 10, padding: '12px 14px', fontSize: 13, color: '#791F1F' }}>
                        <strong>Rejection reason:</strong> {d.rejected_reason}
                      </div>
                    )}

                    {filter === 'verified' && (
                      <div style={{ background: 'var(--green-50)', borderRadius: 10, padding: '12px 14px', fontSize: 13, color: 'var(--green-700)', display: 'flex', alignItems: 'center', gap: 8 }}>
                        <i className="ti ti-shield-check" />
                        Verified on {d.verified_at ? new Date(d.verified_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' }) : '—'}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}
      </>)}

      {/* Market listings section */}
      {section === 'market' && <AdminMarketListings />}

      {/* B2B stock section */}
      {section === 'b2b' && <AdminB2BListings />}

    </div>
  )
}


// ── SELL MY CAR PAGE ─────────────────────────────────────────
function SellMyCarPage() {
  const navigate = useNavigate()
  const [step, setStep] = useState<1|2|3>(1)
  const [loading, setLoading] = useState(false)
  const [decoding, setDecoding] = useState(false)
  const [error, setError] = useState('')
  const [submitted, setSubmitted] = useState(false)
  const [requestId, setRequestId] = useState('')
  const [form, setForm] = useState({
    vin: '', make: '', model: '', year: '', colour: '',
    odometer: '', condition: 'good', location: 'Nairobi',
    askingPrice: '', notes: '', name: '', phone: '', email: '',
  })
  const set = (k: string, v: string) => setForm(f => ({ ...f, [k]: v }))
  const inp: React.CSSProperties = { width: '100%', height: 44, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 10, fontSize: 14, background: 'var(--ink-20)', outline: 'none', fontFamily: 'inherit' }

  async function decodeVin() {
    if (form.vin.length !== 17) return
    setDecoding(true)
    try {
      const res = await fetch(`https://vpic.nhtsa.dot.gov/api/vehicles/decodevin/${form.vin}?format=json`)
      const json = await res.json()
      const get = (key: string) => json.Results.find((r: any) => r.Variable === key)?.Value || ''
      set('make', get('Make'))
      set('model', get('Model'))
      set('year', get('Model Year'))
    } catch {}
    setDecoding(false)
  }

  async function handleSubmit() {
    if (!form.make || !form.model || !form.year) { setError('Please fill in vehicle details'); return }
    if (!form.phone && !form.email) { setError('Please provide a phone number or email'); return }
    setLoading(true); setError('')
    try {
      const { data, error: dbError } = await supabase.from('sell_requests').insert({
        vin: form.vin || null,
        make: form.make,
        model: form.model,
        year: parseInt(form.year),
        odometer_km: form.odometer ? parseInt(form.odometer) : null,
        condition: form.condition as any,
        colour: form.colour || null,
        location: form.location,
        asking_price_kes: form.askingPrice ? parseFloat(form.askingPrice) : null,
        notes: form.notes || null,
        status: 'pending',
      }).select().single()
      if (dbError) throw dbError
      setRequestId(data.id)
      setSubmitted(true)
    } catch (e: any) {
      setError(e.message || 'Failed to submit. Please try again.')
    }
    setLoading(false)
  }

  if (submitted) return (
    <div style={{ maxWidth: 560, margin: '60px auto', padding: '0 24px', textAlign: 'center' }}>
      <div style={{ width: 72, height: 72, background: 'var(--green-100)', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
        <i className="ti ti-circle-check" style={{ fontSize: 36, color: 'var(--green-600)' }} />
      </div>
      <h1 style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, color: 'var(--ink-900)', marginBottom: 12 }}>Your car is listed!</h1>
      <p style={{ fontSize: 14, color: 'var(--ink-400)', lineHeight: 1.7, marginBottom: 24, maxWidth: 400, margin: '0 auto 24px' }}>
        Your listing has been sent to <strong>340+ verified dealers</strong> across Kenya. You'll start receiving offers within 24 hours.
      </p>
      <div style={{ background: 'var(--green-50)', border: '1px solid var(--green-200)', borderRadius: 12, padding: '16px 20px', marginBottom: 28, textAlign: 'left' }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-700)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 10 }}>What happens next</div>
        {[['1','Dealers review your listing','Within the next few hours'],['2','Offers arrive','Dealers send cash offers to your phone/email'],['3','You accept','Choose the best offer and arrange handover']].map(([n,t,d]) => (
          <div key={n} style={{ display: 'flex', gap: 10, marginBottom: 8 }}>
            <div style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--green-200)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: 'var(--green-800)', flexShrink: 0, marginTop: 1 }}>{n}</div>
            <div><div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-700)' }}>{t}</div><div style={{ fontSize: 12, color: 'var(--ink-400)' }}>{d}</div></div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
        <button className="btn-primary" onClick={() => navigate('/')} style={{ padding: '11px 24px' }}>Back to home</button>
        <button className="btn-secondary" onClick={() => navigate(`/sell/offers/${requestId}`)} style={{ padding: '11px 20px' }}>View my listing</button>
      </div>
    </div>
  )

  const stepTitles = ['', 'Vehicle details', 'Condition & pricing', 'Your contact']

  return (
    <div style={{ maxWidth: 600, margin: '40px auto', padding: '0 24px 48px' }}>
      <button onClick={() => step > 1 ? setStep(s => (s-1) as any) : navigate('/')} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--ink-400)', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 24, fontFamily: 'inherit' }}>
        <i className="ti ti-arrow-left" /> {step > 1 ? 'Back' : 'Back to home'}
      </button>

      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 6 }}>Sell your car</div>
        <h1 style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, color: 'var(--ink-900)', marginBottom: 8 }}>Get offers from verified dealers</h1>
        <p style={{ fontSize: 14, color: 'var(--ink-400)', lineHeight: 1.6 }}>List your car and receive cash offers from 340+ dealers — free to list, no commitment.</p>
      </div>

      {/* Progress */}
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 28 }}>
        {[1,2,3].map((s,i) => (
          <div key={s} style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
            <div style={{ display: 'flex', flexDirection: 'column' as const, alignItems: 'center', gap: 4 }}>
              <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 600, background: step > s ? 'var(--green-500)' : step === s ? 'var(--green-600)' : 'var(--ink-100)', color: step >= s ? '#fff' : 'var(--ink-400)', transition: 'all .3s' }}>
                {step > s ? <i className="ti ti-check" style={{ fontSize: 13 }} /> : s}
              </div>
              <span style={{ fontSize: 10, color: step === s ? 'var(--green-700)' : 'var(--ink-400)', fontWeight: step === s ? 600 : 400, whiteSpace: 'nowrap' as const }}>{stepTitles[s]}</span>
            </div>
            {i < 2 && <div style={{ flex: 1, height: 2, background: step > s ? 'var(--green-400)' : 'var(--ink-100)', margin: '0 4px', marginBottom: 18, transition: 'background .3s' }} />}
          </div>
        ))}
      </div>

      <div style={{ background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 20, padding: 28 }}>
        {step === 1 && (
          <>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 1 — Vehicle details</div>
            <div style={{ display: 'grid', gap: 14 }}>
              <div>
                <label className="field-label">VIN or chassis number <span style={{ color: 'var(--ink-300)', fontWeight: 400 }}>(optional — auto-fills details)</span></label>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input style={{ ...inp, flex: 1, fontFamily: '"DM Mono",monospace', letterSpacing: 1 }} value={form.vin} onChange={e => set('vin', e.target.value.toUpperCase())} placeholder="e.g. JTMRFREV1HD012345" maxLength={17} onBlur={decodeVin} />
                  {decoding && <div style={{ display: 'flex', alignItems: 'center', fontSize: 12, color: 'var(--ink-300)' }}>Decoding…</div>}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div><label className="field-label">Make *</label><input style={inp} placeholder="e.g. Toyota" value={form.make} onChange={e => set('make', e.target.value)} /></div>
                <div><label className="field-label">Model *</label><input style={inp} placeholder="e.g. RAV4" value={form.model} onChange={e => set('model', e.target.value)} /></div>
                <div><label className="field-label">Year *</label><input style={inp} type="number" placeholder="e.g. 2017" value={form.year} onChange={e => set('year', e.target.value)} /></div>
                <div><label className="field-label">Colour</label><input style={inp} placeholder="e.g. Pearl White" value={form.colour} onChange={e => set('colour', e.target.value)} /></div>
              </div>
            </div>
          </>
        )}

        {step === 2 && (
          <>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 2 — Condition & pricing</div>
            <div style={{ display: 'grid', gap: 14 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div><label className="field-label">Mileage (km)</label><input style={inp} type="number" placeholder="e.g. 85000" value={form.odometer} onChange={e => set('odometer', e.target.value)} /></div>
                <div><label className="field-label">Location</label>
                  <select style={inp} value={form.location} onChange={e => set('location', e.target.value)}>
                    {['Nairobi','Mombasa','Kisumu','Nakuru','Eldoret','Kiambu','Thika','Nyeri','Meru','Machakos'].map(l => <option key={l}>{l}</option>)}
                  </select>
                </div>
              </div>
              <div>
                <label className="field-label">Vehicle condition</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 8, marginTop: 6 }}>
                  {[['excellent','Excellent','ti-circle-check','var(--green-500)'],['good','Good','ti-thumb-up','var(--green-400)'],['fair','Fair','ti-tool','#E07B00'],['poor','Poor','ti-alert-triangle','#C53030']].map(([v,l,icon,color]) => (
                    <button key={v} onClick={() => set('condition', String(v))} style={{ border: `1.5px solid ${form.condition===v?'var(--green-500)':'var(--ink-100)'}`, borderRadius: 10, padding: '12px 8px', textAlign: 'center' as const, background: form.condition===v?'var(--green-50)':'var(--ink-20)', cursor: 'pointer' }}>
                      <i className={`ti ${icon}`} style={{ fontSize: 20, display: 'block', marginBottom: 4, color: String(color) }} />
                      <div style={{ fontSize: 12, fontWeight: 500, color: form.condition===v?'var(--green-700)':'var(--ink-500)' }}>{l}</div>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="field-label">Your asking price (KES) <span style={{ color: 'var(--ink-300)', fontWeight: 400 }}>(optional — leave blank to get best offer)</span></label>
                <input style={inp} type="number" placeholder="e.g. 2500000" value={form.askingPrice} onChange={e => set('askingPrice', e.target.value)} />
              </div>
              <div>
                <label className="field-label">Known issues or extras</label>
                <textarea style={{ ...inp, height: 80, padding: '10px 12px', resize: 'vertical' as const }} placeholder="e.g. New tyres, recent service, needs new shocks…" value={form.notes} onChange={e => set('notes', e.target.value)} />
              </div>
            </div>
          </>
        )}

        {step === 3 && (
          <>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 8 }}>Step 3 — Your contact details</div>
            <p style={{ fontSize: 12, color: 'var(--ink-400)', marginBottom: 18, lineHeight: 1.5 }}>Dealers will contact you directly with offers. Your details are only shared with verified dealers.</p>
            <div style={{ display: 'grid', gap: 14 }}>
              <div><label className="field-label">Full name</label><input style={inp} placeholder="John Kamau" value={form.name} onChange={e => set('name', e.target.value)} /></div>
              <div><label className="field-label">Phone number *</label><input style={inp} placeholder="+254 7XX XXX XXX" value={form.phone} onChange={e => set('phone', e.target.value)} /></div>
              <div><label className="field-label">Email address</label><input style={inp} type="email" placeholder="john@example.com" value={form.email} onChange={e => set('email', e.target.value)} /></div>
            </div>

            {/* Summary */}
            <div style={{ background: 'var(--ink-20)', borderRadius: 10, padding: '14px 16px', marginTop: 20 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 10 }}>Listing summary</div>
              {[['Vehicle', `${form.year} ${form.make} ${form.model}${form.colour ? ' · ' + form.colour : ''}`], ['Mileage', form.odometer ? `${parseInt(form.odometer).toLocaleString()} km` : 'Not specified'], ['Condition', form.condition.charAt(0).toUpperCase()+form.condition.slice(1)], ['Location', form.location], ['Asking price', form.askingPrice ? 'KES ' + parseInt(form.askingPrice).toLocaleString('en-KE') : 'Open to offers']].map(([k,v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '5px 0', borderBottom: '1px solid var(--ink-100)' }}>
                  <span style={{ color: 'var(--ink-400)' }}>{k}</span>
                  <span style={{ fontWeight: 500, color: 'var(--ink-700)' }}>{v}</span>
                </div>
              ))}
            </div>
          </>
        )}

        {error && <div style={{ background: '#FEE9E9', color: '#791F1F', borderRadius: 8, padding: '10px 14px', fontSize: 13, marginTop: 16 }}><i className="ti ti-alert-circle" /> {error}</div>}

        <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
          {step > 1 && <button className="btn-secondary" style={{ flex: '0 0 auto' }} onClick={() => setStep(s => (s-1) as any)}>Back</button>}
          <button className="btn-primary" disabled={loading} style={{ flex: 1, justifyContent: 'center', padding: '12px', fontSize: 14 }}
            onClick={() => step < 3 ? setStep(s => (s+1) as any) : handleSubmit()}>
            {loading ? 'Submitting…' : step < 3 ? 'Continue' : 'List my car — free'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── MY SELL LISTING PAGE ──────────────────────────────────────
function SellOffersPage() {
  const { id } = useParams<{ id: string }>()
  const [request, setRequest] = useState<any>(null)
  const [offers, setOffers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!id) return
    Promise.all([
      supabase.from('sell_requests').select('*').eq('id', id).single(),
      supabase.from('dealer_offers').select('*, dealer:dealers(business_name,town,county)').eq('sell_request_id', id).order('offer_amount_kes', { ascending: false })
    ]).then(([req, off]) => {
      setRequest(req.data)
      setOffers(off.data || [])
      setLoading(false)
    })
  }, [id])

  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')

  if (loading) return <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 32 }} /></div>
  if (!request) return <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-300)' }}>Listing not found</div>

  return (
    <div style={{ maxWidth: 700, margin: '40px auto', padding: '0 24px 48px' }}>
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 6 }}>Your listing</div>
        <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 26, color: 'var(--ink-900)', marginBottom: 4 }}>{request.year} {request.make} {request.model}</div>
        <div style={{ fontSize: 14, color: 'var(--ink-400)' }}>{request.location} · {request.condition} condition{request.odometer_km ? ` · ${Math.round(request.odometer_km/1000)}K km` : ''}</div>
      </div>

      {/* Offers */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.5px', marginBottom: 14 }}>
          Dealer offers ({offers.length})
        </div>
        {offers.length === 0 ? (
          <div style={{ background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 16, padding: '40px 24px', textAlign: 'center' }}>
            <i className="ti ti-clock" style={{ fontSize: 32, color: 'var(--ink-200)', display: 'block', marginBottom: 12 }} />
            <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 18, color: 'var(--ink-700)', marginBottom: 8 }}>Waiting for offers</div>
            <div style={{ fontSize: 13, color: 'var(--ink-400)' }}>Dealers are reviewing your listing. Offers typically arrive within 24 hours.</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 10 }}>
            {offers.map((o, i) => (
              <div key={o.id} style={{ background: '#fff', border: `1.5px solid ${i===0?'var(--green-400)':'var(--ink-100)'}`, borderRadius: 14, padding: '18px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
                <div>
                  {i === 0 && <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--green-700)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 4 }}>Best offer</div>}
                  <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink-900)' }}>{o.dealer?.business_name || 'Verified Dealer'}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-400)', marginTop: 2 }}>{o.dealer?.town}, {o.dealer?.county}</div>
                  {o.message && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 6, fontStyle: 'italic' }}>"{o.message}"</div>}
                </div>
                <div style={{ textAlign: 'right' as const }}>
                  <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 22, color: i===0?'var(--green-700)':'var(--ink-900)' }}>{fmt(o.offer_amount_kes)}</div>
                  <button style={{ marginTop: 8, padding: '6px 16px', background: i===0?'var(--green-600)':'var(--ink-50)', color: i===0?'#fff':'var(--ink-500)', border: 'none', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
                    {i===0?'Accept offer':'View'}
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}


// ── DEALER SELL REQUESTS ─────────────────────────────────────
function DealerSellRequests({ dealer }: { dealer: any }) {
  const [requests, setRequests] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [offering, setOffering] = useState<string | null>(null)
  const [offerAmount, setOfferAmount] = useState('')
  const [offerMessage, setOfferMessage] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState<Set<string>>(new Set())

  useEffect(() => {
    supabase
      .from('sell_requests')
      .select('*')
      .eq('status', 'pending')
      .order('created_at', { ascending: false })
      .limit(20)
      .then(({ data }) => {
        setRequests(data || [])
        setLoading(false)
      })
  }, [])

  async function submitOffer(requestId: string) {
    if (!offerAmount) return
    setSubmitting(true)
    const sellRequest = requests.find((r: any) => r.id === requestId)
    const { error } = await supabase.from('dealer_offers').insert({
      sell_request_id: requestId,
      dealer_id: dealer.id,
      offer_amount_kes: parseFloat(offerAmount),
      message: offerMessage || null,
      status: 'pending',
    })
    if (!error) {
      // Notify the car owner if they have a user_id
      if (sellRequest?.user_id) {
        await supabase.from('notifications').insert({
          dealer_id: dealer.id, // placeholder - ideally notify user not dealer
          type: 'new_offer',
          title: 'New offer on your car',
          body: `${dealer.business_name} offered KES ${parseInt(offerAmount).toLocaleString('en-KE')} for your ${sellRequest.year} ${sellRequest.make} ${sellRequest.model}`,
          link: '/sell/offers/' + requestId,
        })
      }
      setSubmitted(s => new Set([...s, requestId]))
      setOffering(null)
      setOfferAmount('')
      setOfferMessage('')
    }
    setSubmitting(false)
  }

  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')
  const inp: React.CSSProperties = { width: '100%', height: 40, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 8, fontSize: 13, background: 'var(--ink-20)', outline: 'none', fontFamily: 'inherit' }

  if (loading) return <div style={{ textAlign: 'center', padding: 40, color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 28 }} /></div>

  if (requests.length === 0) return (
    <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--ink-300)' }}>
      <i className="ti ti-tag" style={{ fontSize: 32, display: 'block', marginBottom: 10 }} />
      <div style={{ fontSize: 14 }}>No sell requests yet — check back soon</div>
    </div>
  )

  return (
    <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 12 }}>
      {requests.map(r => (
        <div key={r.id} style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink-900)' }}>{r.year} {r.make} {r.model}{r.colour ? ` · ${r.colour}` : ''}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-400)', marginTop: 3 }}>
                {r.location} · {r.condition} condition{r.odometer_km ? ` · ${Math.round(r.odometer_km/1000)}K km` : ''}
              </div>
            </div>
            <div style={{ textAlign: 'right' as const }}>
              {r.asking_price_kes ? (
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)' }}>{fmt(r.asking_price_kes)}</div>
              ) : (
                <div style={{ fontSize: 12, color: 'var(--ink-400)', fontStyle: 'italic' }}>Open to offers</div>
              )}
              <div style={{ fontSize: 11, color: 'var(--ink-300)', marginTop: 2 }}>
                {new Date(r.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short' })}
              </div>
            </div>
          </div>

          {r.notes && (
            <div style={{ fontSize: 12, color: 'var(--ink-500)', background: 'var(--ink-20)', borderRadius: 8, padding: '8px 12px', marginBottom: 12, fontStyle: 'italic' }}>
              "{r.notes}"
            </div>
          )}

          {submitted.has(r.id) ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--green-600)', fontWeight: 500 }}>
              <i className="ti ti-circle-check" /> Offer submitted successfully
            </div>
          ) : offering === r.id ? (
            <div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
                <div>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Your offer (KES) *</label>
                  <input style={inp} type="number" placeholder="e.g. 2400000" value={offerAmount} onChange={e => setOfferAmount(e.target.value)} autoFocus />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Message (optional)</label>
                  <input style={inp} placeholder="e.g. Can inspect today" value={offerMessage} onChange={e => setOfferMessage(e.target.value)} />
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={() => submitOffer(r.id)} disabled={submitting || !offerAmount} className="btn-primary" style={{ padding: '8px 20px', fontSize: 13 }}>
                  {submitting ? 'Sending…' : 'Send offer'}
                </button>
                <button onClick={() => setOffering(null)} className="btn-secondary" style={{ padding: '8px 14px', fontSize: 13 }}>Cancel</button>
              </div>
            </div>
          ) : (
            <button onClick={() => setOffering(r.id)} className="btn-primary" style={{ padding: '8px 18px', fontSize: 13 }}>
              <i className="ti ti-tag" /> Make an offer
            </button>
          )}
        </div>
      ))}
    </div>
  )
}

// ── TRADE OFFERS & MESSAGING ─────────────────────────────────
// ── TRADE OFFERS & MESSAGING ─────────────────────────────────
// Add this as a new tab in the dealer dashboard

function DealerTradeOffers({ dealer }: { dealer: any }) {
  const [tab, setTab] = useState<'browse'|'incoming'|'sent'>('browse')
  const [listings, setListings] = useState<any[]>([])
  const [incoming, setIncoming] = useState<any[]>([])
  const [sent, setSent] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedListing, setSelectedListing] = useState<any>(null)
  const [selectedOffer, setSelectedOffer] = useState<any>(null)
  const [offerAmount, setOfferAmount] = useState('')
  const [offerMessage, setOfferMessage] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [replyMessage, setReplyMessage] = useState('')
  const [counterAmount, setCounterAmount] = useState('')
  const [messages, setMessages] = useState<any[]>([])

  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')
  const inp: React.CSSProperties = { width: '100%', height: 40, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 8, fontSize: 13, background: 'var(--ink-20)', outline: 'none', fontFamily: 'inherit' }

  useEffect(() => { loadData() }, [tab])

  async function loadData() {
    setLoading(true)
    if (tab === 'browse') {
      // Load B2B listings from other dealers
      const { data } = await supabase
        .from('stock_listings')
        .select('*, vehicle:vehicles(*), dealer:dealers(business_name, town, county, id)')
        .eq('is_b2b_listed', true)
        .eq('status', 'active')
        .neq('dealer_id', dealer.id)
        .order('created_at', { ascending: false })
        .limit(30)
      setListings(data || [])
    } else if (tab === 'incoming') {
      const { data } = await supabase
        .from('trade_offers')
        .select('*, stock_listing:stock_listings(*, vehicle:vehicles(*)), from_dealer:dealers!trade_offers_from_dealer_id_fkey(business_name, town)')
        .eq('to_dealer_id', dealer.id)
        .order('created_at', { ascending: false })
      setIncoming(data || [])
    } else {
      const { data } = await supabase
        .from('trade_offers')
        .select('*, stock_listing:stock_listings(*, vehicle:vehicles(*)), to_dealer:dealers!trade_offers_to_dealer_id_fkey(business_name, town)')
        .eq('from_dealer_id', dealer.id)
        .order('created_at', { ascending: false })
      setSent(data || [])
    }
    setLoading(false)
  }

  async function submitOffer() {
    if (!offerAmount || !selectedListing) return
    setSubmitting(true)
    const { error } = await supabase.from('trade_offers').insert({
      stock_listing_id: selectedListing.id,
      from_dealer_id: dealer.id,
      to_dealer_id: selectedListing.dealer_id,
      offer_amount_kes: parseFloat(offerAmount),
      message: offerMessage || null,
      status: 'pending',
    })
    if (!error) {
      setSelectedListing(null)
      setOfferAmount('')
      setOfferMessage('')
      alert('Offer sent successfully!')
    }
    setSubmitting(false)
  }

  async function respondToOffer(offerId: string, action: 'accepted'|'declined'|'countered') {
    const update: any = { status: action, responded_at: new Date().toISOString() }
    if (action === 'countered' && counterAmount) update.counter_amount_kes = parseFloat(counterAmount)
    await supabase.from('trade_offers').update(update).eq('id', offerId)
    // Send system message and notification
    const offer = incoming.find(o => o.id === offerId)
    if (offer) {
      // Notify the offer sender
      await supabase.from('notifications').insert({
        dealer_id: offer.from_dealer_id,
        type: action === 'accepted' ? 'offer_accepted' : action === 'declined' ? 'offer_declined' : 'counter_offer',
        title: action === 'accepted' ? 'Your offer was accepted! 🎉' : action === 'declined' ? 'Offer declined' : 'Counter offer received',
        body: action === 'accepted' ? `${dealer.business_name} accepted your offer. Get in touch to arrange the transfer.` :
              action === 'declined' ? `${dealer.business_name} declined your offer.` :
              `${dealer.business_name} countered with KES ${parseInt(counterAmount).toLocaleString('en-KE')}`,
        link: '/dealer/dashboard',
      })
      await supabase.from('dealer_messages').insert({
        trade_offer_id: offerId,
        from_dealer_id: dealer.id,
        to_dealer_id: offer.from_dealer_id,
        message_type: action === 'countered' ? 'counter' : 'system',
        body: action === 'accepted' ? 'Offer accepted! Please get in touch to arrange the transfer.' :
              action === 'declined' ? 'Thank you for your offer. We have decided to decline at this time.' :
              `Counter offer: ${fmt(parseFloat(counterAmount))}${replyMessage ? '. ' + replyMessage : ''}`,
        amount_kes: action === 'countered' ? parseFloat(counterAmount) : null,
      })
    }
    loadData()
    setSelectedOffer(null)
    setCounterAmount('')
    setReplyMessage('')
  }

  async function sendMessage(offerId: string, toId: string) {
    if (!replyMessage) return
    await supabase.from('dealer_messages').insert({
      trade_offer_id: offerId,
      from_dealer_id: dealer.id,
      to_dealer_id: toId,
      message_type: 'message',
      body: replyMessage,
    })
    setReplyMessage('')
    loadMessages(offerId)
  }

  async function loadMessages(offerId: string) {
    const { data } = await supabase
      .from('dealer_messages')
      .select('*, from_dealer:dealers!dealer_messages_from_dealer_id_fkey(business_name)')
      .eq('trade_offer_id', offerId)
      .order('created_at', { ascending: true })
    setMessages(data || [])
  }

  const statusColor = (s: string) => s === 'accepted' ? 'var(--green-700)' : s === 'declined' ? '#C53030' : s === 'countered' ? '#854F0B' : 'var(--ink-400)'
  const statusBg = (s: string) => s === 'accepted' ? 'var(--green-100)' : s === 'declined' ? '#FEE9E9' : s === 'countered' ? '#FEF0D6' : 'var(--ink-50)'

  return (
    <div>
      {/* Offer modal */}
      {selectedListing && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div style={{ background: '#fff', borderRadius: 20, padding: 28, width: '100%', maxWidth: 480 }}>
            <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 20, color: 'var(--ink-900)', marginBottom: 4 }}>Make a trade offer</div>
            <div style={{ fontSize: 13, color: 'var(--ink-400)', marginBottom: 20 }}>
              {selectedListing.vehicle?.year} {selectedListing.vehicle?.make} {selectedListing.vehicle?.model} · {selectedListing.dealer?.business_name}
            </div>
            <div style={{ background: 'var(--ink-20)', borderRadius: 10, padding: '10px 14px', marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 12, color: 'var(--ink-400)' }}>Asking price</span>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{fmt(selectedListing.wholesale_price_kes || selectedListing.retail_price_kes)}</span>
            </div>
            <div style={{ display: 'grid', gap: 12, marginBottom: 16 }}>
              <div>
                <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Your offer (KES) *</label>
                <input style={inp} type="number" placeholder="e.g. 2400000" value={offerAmount} onChange={e => setOfferAmount(e.target.value)} autoFocus />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Message (optional)</label>
                <textarea style={{ ...inp, height: 70, padding: '8px 12px', resize: 'vertical' as const }} placeholder="e.g. Can pay cash and collect today" value={offerMessage} onChange={e => setOfferMessage(e.target.value)} />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={submitOffer} disabled={submitting || !offerAmount} className="btn-primary" style={{ flex: 1, justifyContent: 'center', padding: '11px' }}>
                {submitting ? 'Sending…' : 'Send offer'}
              </button>
              <button onClick={() => setSelectedListing(null)} className="btn-secondary" style={{ padding: '11px 18px' }}>Cancel</button>
            </div>
          </div>
        </div>
      )}

      {/* Offer detail modal */}
      {selectedOffer && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div style={{ background: '#fff', borderRadius: 20, padding: 28, width: '100%', maxWidth: 520, maxHeight: '85vh', overflowY: 'auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 20, color: 'var(--ink-900)' }}>Trade offer</div>
              <button onClick={() => { setSelectedOffer(null); setMessages([]) }} style={{ background: 'var(--ink-50)', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 18, color: 'var(--ink-400)' }}>×</button>
            </div>

            {/* Offer summary */}
            <div style={{ background: 'var(--green-50)', border: '1px solid var(--green-200)', borderRadius: 12, padding: '14px 16px', marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: 'var(--ink-400)', marginBottom: 4 }}>
                {selectedOffer.vehicle?.year} {selectedOffer.vehicle?.make} {selectedOffer.vehicle?.model}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: 11, color: 'var(--ink-400)', marginBottom: 2 }}>Offer amount</div>
                  <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 22, color: 'var(--green-800)' }}>{fmt(selectedOffer.offer_amount_kes)}</div>
                </div>
                <span style={{ fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 20, background: statusBg(selectedOffer.status), color: statusColor(selectedOffer.status), textTransform: 'capitalize' as const }}>{selectedOffer.status}</span>
              </div>
              {selectedOffer.message && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 8, fontStyle: 'italic' }}>"{selectedOffer.message}"</div>}
              {selectedOffer.counter_amount_kes && (
                <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--green-200)' }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-400)' }}>Counter offer</div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: '#854F0B' }}>{fmt(selectedOffer.counter_amount_kes)}</div>
                </div>
              )}
            </div>

            {/* Actions for incoming offers */}
            {tab === 'incoming' && selectedOffer.status === 'pending' && (
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 10 }}>Respond to offer</div>
                <div style={{ display: 'grid', gap: 10 }}>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <button onClick={() => respondToOffer(selectedOffer.id, 'accepted')} style={{ flex: 1, padding: '10px', background: 'var(--green-600)', color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
                      ✓ Accept offer
                    </button>
                    <button onClick={() => respondToOffer(selectedOffer.id, 'declined')} style={{ flex: 1, padding: '10px', background: '#FEE9E9', color: '#C53030', border: '1px solid #FCA5A5', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
                      ✗ Decline
                    </button>
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Counter offer amount (KES)</label>
                    <div style={{ display: 'flex', gap: 8 }}>
                      <input style={{ ...inp, flex: 1 }} type="number" placeholder="e.g. 2600000" value={counterAmount} onChange={e => setCounterAmount(e.target.value)} />
                      <button onClick={() => respondToOffer(selectedOffer.id, 'countered')} disabled={!counterAmount} style={{ padding: '0 16px', background: '#FEF0D6', color: '#854F0B', border: '1px solid #FAC875', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const }}>
                        Counter
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Messages */}
            <div>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 10 }}>Messages</div>
              {messages.length === 0 ? (
                <div style={{ fontSize: 13, color: 'var(--ink-300)', textAlign: 'center', padding: '16px 0' }}>No messages yet</div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 8, marginBottom: 12 }}>
                  {messages.map(m => {
                    const isMe = m.from_dealer_id === dealer.id
                    return (
                      <div key={m.id} style={{ display: 'flex', justifyContent: isMe ? 'flex-end' : 'flex-start' }}>
                        <div style={{ maxWidth: '80%', background: isMe ? 'var(--green-600)' : 'var(--ink-50)', color: isMe ? '#fff' : 'var(--ink-700)', borderRadius: isMe ? '12px 12px 4px 12px' : '12px 12px 12px 4px', padding: '10px 14px' }}>
                          {!isMe && <div style={{ fontSize: 10, fontWeight: 600, marginBottom: 4, color: 'var(--ink-400)' }}>{m.from_dealer?.business_name}</div>}
                          <div style={{ fontSize: 13 }}>{m.body}</div>
                          <div style={{ fontSize: 10, marginTop: 4, color: isMe ? 'rgba(255,255,255,.5)' : 'var(--ink-300)' }}>{new Date(m.created_at).toLocaleTimeString('en-KE', { hour: '2-digit', minute: '2-digit' })}</div>
                        </div>
                      </div>
                    )
                  })}
                </div>
              )}
              <div style={{ display: 'flex', gap: 8 }}>
                <input style={{ ...inp, flex: 1 }} placeholder="Type a message…" value={replyMessage} onChange={e => setReplyMessage(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && sendMessage(selectedOffer.id, selectedOffer.from_dealer_id === dealer.id ? selectedOffer.to_dealer_id : selectedOffer.from_dealer_id)} />
                <button onClick={() => sendMessage(selectedOffer.id, selectedOffer.from_dealer_id === dealer.id ? selectedOffer.to_dealer_id : selectedOffer.from_dealer_id)} disabled={!replyMessage} className="btn-primary" style={{ padding: '0 16px', flexShrink: 0 }}>
                  Send
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Sub tabs */}
      <div style={{ display: 'flex', gap: 0, marginBottom: 20, borderBottom: '1px solid var(--ink-100)' }}>
        {([
          { key: 'browse', label: 'Browse B2B stock', icon: 'ti-search' },
          { key: 'incoming', label: 'Incoming offers', icon: 'ti-inbox' },
          { key: 'sent', label: 'Sent offers', icon: 'ti-send' },
        ] as const).map(t => (
          <button key={t.key} onClick={() => setTab(t.key)} style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '8px 14px', border: 'none', borderBottom: `2px solid ${tab === t.key ? 'var(--green-500)' : 'transparent'}`, fontSize: 12, fontWeight: 500, cursor: 'pointer', background: 'none', color: tab === t.key ? 'var(--green-700)' : 'var(--ink-400)', marginBottom: -1, fontFamily: 'inherit' }}>
            <i className={`ti ${t.icon}`} style={{ fontSize: 13 }} /> {t.label}
          </button>
        ))}
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: 40, color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 28 }} /></div>
      ) : tab === 'browse' ? (
        listings.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--ink-300)' }}>
            <i className="ti ti-building-store" style={{ fontSize: 32, display: 'block', marginBottom: 10 }} />
            <div style={{ fontSize: 14 }}>No B2B listings from other dealers yet</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 10 }}>
            {listings.map(l => (
              <div key={l.id} style={{ background: '#fff', borderRadius: 14, border: '1px solid var(--ink-100)', padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 2 }}>
                    {l.vehicle?.year} {l.vehicle?.make} {l.vehicle?.model}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>
                    {l.dealer?.business_name} · {l.dealer?.town} · {l.odometer_km ? `${Math.round(l.odometer_km/1000)}K km` : '—'} · {l.condition}
                  </div>
                </div>
                <div style={{ textAlign: 'right' as const, flexShrink: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink-900)' }}>{fmt(l.wholesale_price_kes || l.retail_price_kes)}</div>
                  {l.wholesale_price_kes && <div style={{ fontSize: 10, color: 'var(--ink-300)', marginBottom: 6 }}>wholesale</div>}
                  <button onClick={() => setSelectedListing(l)} className="btn-primary" style={{ padding: '6px 14px', fontSize: 12 }}>
                    <i className="ti ti-tag" /> Make offer
                  </button>
                </div>
              </div>
            ))}
          </div>
        )
      ) : tab === 'incoming' ? (
        incoming.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--ink-300)' }}>
            <i className="ti ti-inbox" style={{ fontSize: 32, display: 'block', marginBottom: 10 }} />
            <div style={{ fontSize: 14 }}>No incoming offers yet</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 10 }}>
            {incoming.map(o => (
              <div key={o.id} onClick={() => { setSelectedOffer({...o, vehicle: o.stock_listing?.vehicle}); loadMessages(o.id) }} style={{ background: '#fff', borderRadius: 14, border: '1px solid var(--ink-100)', padding: '16px 18px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 2 }}>
                    {o.stock_listing?.vehicle?.year} {o.stock_listing?.vehicle?.make} {o.stock_listing?.vehicle?.model}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>From {o.from_dealer?.business_name} · {new Date(o.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short' })}</div>
                  {o.message && <div style={{ fontSize: 11, color: 'var(--ink-400)', marginTop: 3, fontStyle: 'italic' }}>"{o.message}"</div>}
                </div>
                <div style={{ textAlign: 'right' as const, flexShrink: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink-900)', marginBottom: 4 }}>{fmt(o.offer_amount_kes)}</div>
                  <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: statusBg(o.status), color: statusColor(o.status), textTransform: 'capitalize' as const }}>{o.status}</span>
                </div>
              </div>
            ))}
          </div>
        )
      ) : (
        sent.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--ink-300)' }}>
            <i className="ti ti-send" style={{ fontSize: 32, display: 'block', marginBottom: 10 }} />
            <div style={{ fontSize: 14 }}>No offers sent yet — browse B2B stock to make offers</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 10 }}>
            {sent.map(o => (
              <div key={o.id} onClick={() => { setSelectedOffer({...o, vehicle: o.stock_listing?.vehicle}); loadMessages(o.id) }} style={{ background: '#fff', borderRadius: 14, border: '1px solid var(--ink-100)', padding: '16px 18px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 2 }}>
                    {o.stock_listing?.vehicle?.year} {o.stock_listing?.vehicle?.make} {o.stock_listing?.vehicle?.model}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>To {o.to_dealer?.business_name} · {new Date(o.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short' })}</div>
                </div>
                <div style={{ textAlign: 'right' as const, flexShrink: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink-900)', marginBottom: 4 }}>{fmt(o.offer_amount_kes)}</div>
                  <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: statusBg(o.status), color: statusColor(o.status), textTransform: 'capitalize' as const }}>{o.status}</span>
                  {o.counter_amount_kes && <div style={{ fontSize: 11, color: '#854F0B', marginTop: 3 }}>Counter: {fmt(o.counter_amount_kes)}</div>}
                </div>
              </div>
            ))}
          </div>
        )
      )}
    </div>
  )
}


// ── ADMIN MARKET LISTINGS ────────────────────────────────────
function AdminMarketListings() {
  const [listings, setListings] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState<any>(null)
  const [saving, setSaving] = useState(false)
  const [search, setSearch] = useState('')

  useEffect(() => { loadListings() }, [])

  async function loadListings() {
    setLoading(true)
    const { data } = await supabase
      .from('market_listings')
      .select('*')
      .order('scraped_at', { ascending: false })
      .limit(100)
    setListings(data || [])
    setLoading(false)
  }

  async function saveListing() {
    setSaving(true)
    await supabase.from('market_listings').update({
      raw_make: editing.raw_make,
      raw_model: editing.raw_model,
      raw_year: editing.raw_year,
      asking_price_kes: editing.asking_price_kes,
      sold_price_kes: editing.sold_price_kes,
      location: editing.location,
      odometer_km: editing.odometer_km,
      status: editing.status,
      source_platform: editing.source_platform,
    }).eq('id', editing.id)
    setSaving(false)
    setEditing(null)
    loadListings()
  }

  async function deleteListing(id: string) {
    if (!confirm('Delete this listing?')) return
    await supabase.from('market_listings').delete().eq('id', id)
    loadListings()
  }

  const filtered = listings.filter(l =>
    !search || `${l.raw_make} ${l.raw_model} ${l.location}`.toLowerCase().includes(search.toLowerCase())
  )
  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')
  const inp: React.CSSProperties = { width: '100%', height: 38, padding: '0 10px', border: '1.5px solid var(--ink-100)', borderRadius: 8, fontSize: 13, background: 'var(--ink-20)', outline: 'none' }

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap' as const, gap: 12 }}>
        <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, color: 'var(--ink-900)' }}>Market listings <span style={{ fontSize: 14, color: 'var(--ink-400)', fontFamily: 'inherit' }}>({listings.length})</span></div>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search make, model, location…"
          style={{ height: 38, padding: '0 14px', borderRadius: 8, border: '1.5px solid var(--ink-100)', fontSize: 13, width: '100%', maxWidth: 260, outline: 'none' }} />
      </div>

      {/* Edit modal */}
      {editing && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
          <div style={{ background: '#fff', borderRadius: 20, padding: 28, width: '100%', maxWidth: 520, maxHeight: '90vh', overflowY: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
              <div style={{ fontFamily: '"DM Serif Display"', fontSize: 20, color: 'var(--ink-900)' }}>Edit listing</div>
              <button onClick={() => setEditing(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 20, color: 'var(--ink-400)' }}><i className="ti ti-x" /></button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {[['Make', 'raw_make', 'text'], ['Model', 'raw_model', 'text'], ['Year', 'raw_year', 'number'], ['Location', 'location', 'text'], ['Odometer (km)', 'odometer_km', 'number'], ['Source', 'source_platform', 'text'], ['Asking price (KES)', 'asking_price_kes', 'number'], ['Sold price (KES)', 'sold_price_kes', 'number']].map(([label, key, type]) => (
                <div key={key}>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>{label}</label>
                  <input style={inp} type={type} value={editing[key] || ''} onChange={e => setEditing({ ...editing, [key]: type === 'number' ? Number(e.target.value) : e.target.value })} />
                </div>
              ))}
              <div>
                <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Status</label>
                <select style={{ ...inp }} value={editing.status} onChange={e => setEditing({ ...editing, status: e.target.value })}>
                  <option value="active">Active</option>
                  <option value="sold">Sold</option>
                  <option value="reserved">Reserved</option>
                  <option value="delisted">Delisted</option>
                </select>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
              <button onClick={saveListing} disabled={saving} className="btn-primary" style={{ flex: 1, justifyContent: 'center', padding: '11px' }}>
                {saving ? 'Saving…' : 'Save changes'}
              </button>
              <button onClick={() => setEditing(null)} className="btn-secondary" style={{ padding: '11px 20px' }}>Cancel</button>
            </div>
          </div>
        </div>
      )}

      {loading ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 32 }} /></div>
      ) : (
        <div style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>{['Vehicle', 'Location', 'Source', 'Asking price', 'Sold price', 'Status', 'Actions'].map(h => (
                <th key={h} style={{ textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', padding: '10px 16px', background: 'var(--ink-20)', borderBottom: '1px solid var(--ink-100)' }}>{h}</th>
              ))}</tr>
            </thead>
            <tbody>
              {filtered.map(l => (
                <tr key={l.id} style={{ borderBottom: '1px solid var(--ink-50)' }}>
                  <td style={{ padding: '11px 16px' }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>{l.raw_year} {l.raw_make} {l.raw_model}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-400)', marginTop: 1 }}>{l.odometer_km ? `${Math.round(l.odometer_km/1000)}K km` : '—'}</div>
                  </td>
                  <td style={{ padding: '11px 16px', fontSize: 13, color: 'var(--ink-500)' }}>{l.location || '—'}</td>
                  <td style={{ padding: '11px 16px', fontSize: 12, color: 'var(--ink-400)', textTransform: 'capitalize' as const }}>{l.source_platform}</td>
                  <td style={{ padding: '11px 16px', fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>{fmt(l.asking_price_kes)}</td>
                  <td style={{ padding: '11px 16px', fontSize: 13, color: l.sold_price_kes ? 'var(--green-700)' : 'var(--ink-300)' }}>{l.sold_price_kes ? fmt(l.sold_price_kes) : '—'}</td>
                  <td style={{ padding: '11px 16px' }}>
                    <span style={{ fontSize: 10.5, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: l.status === 'sold' ? '#E0EAFF' : l.status === 'active' ? 'var(--green-100)' : 'var(--ink-50)', color: l.status === 'sold' ? '#1A4FA8' : l.status === 'active' ? 'var(--green-700)' : 'var(--ink-400)', textTransform: 'capitalize' as const }}>
                      {l.status}
                    </span>
                  </td>
                  <td style={{ padding: '11px 16px' }}>
                    <div style={{ display: 'flex', gap: 6 }}>
                      <button onClick={() => setEditing({ ...l })} style={{ padding: '4px 10px', border: '1px solid var(--ink-100)', borderRadius: 6, fontSize: 11, cursor: 'pointer', background: '#fff', color: 'var(--ink-500)' }}>
                        <i className="ti ti-pencil" /> Edit
                      </button>
                      <button onClick={() => deleteListing(l.id)} style={{ padding: '4px 10px', border: '1px solid #FCA5A5', borderRadius: 6, fontSize: 11, cursor: 'pointer', background: '#fff', color: '#C53030' }}>
                        <i className="ti ti-trash" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

// ── ADMIN B2B LISTINGS ───────────────────────────────────────
function AdminB2BListings() {
  const [listings, setListings] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState<any>(null)
  const [saving, setSaving] = useState(false)

  useEffect(() => { loadListings() }, [])

  async function loadListings() {
    setLoading(true)
    const { data } = await supabase
      .from('stock_listings')
      .select(`*, vehicle:vehicles(*), dealer:dealers(business_name, town, county)`)
      .order('created_at', { ascending: false })
      .limit(100)
    setListings(data || [])
    setLoading(false)
  }

  async function saveListing() {
    setSaving(true)
    await supabase.from('stock_listings').update({
      retail_price_kes: editing.retail_price_kes,
      wholesale_price_kes: editing.wholesale_price_kes,
      odometer_km: editing.odometer_km,
      condition: editing.condition,
      status: editing.status,
      is_b2b_listed: editing.is_b2b_listed,
      is_retail_listed: editing.is_retail_listed,
      notes: editing.notes,
    }).eq('id', editing.id)
    setSaving(false)
    setEditing(null)
    loadListings()
  }

  async function deleteListing(id: string) {
    if (!confirm('Remove this stock listing?')) return
    await supabase.from('stock_listings').delete().eq('id', id)
    loadListings()
  }

  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')
  const inp: React.CSSProperties = { width: '100%', height: 38, padding: '0 10px', border: '1.5px solid var(--ink-100)', borderRadius: 8, fontSize: 13, background: 'var(--ink-20)', outline: 'none' }

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
        <div style={{ fontFamily: '"DM Serif Display"', fontSize: 22, color: 'var(--ink-900)' }}>B2B stock listings <span style={{ fontSize: 14, color: 'var(--ink-400)', fontFamily: 'inherit' }}>({listings.length})</span></div>
      </div>

      {/* Edit modal */}
      {editing && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
          <div style={{ background: '#fff', borderRadius: 20, padding: 28, width: '100%', maxWidth: 520, maxHeight: '90vh', overflowY: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
              <div style={{ fontFamily: '"DM Serif Display"', fontSize: 20, color: 'var(--ink-900)' }}>Edit stock listing</div>
              <button onClick={() => setEditing(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 20, color: 'var(--ink-400)' }}><i className="ti ti-x" /></button>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {[['Retail price (KES)', 'retail_price_kes', 'number'], ['Wholesale price (KES)', 'wholesale_price_kes', 'number'], ['Odometer (km)', 'odometer_km', 'number']].map(([label, key, type]) => (
                <div key={key}>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>{label}</label>
                  <input style={inp} type={type} value={editing[key] || ''} onChange={e => setEditing({ ...editing, [key]: Number(e.target.value) })} />
                </div>
              ))}
              <div>
                <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Condition</label>
                <select style={{ ...inp }} value={editing.condition} onChange={e => setEditing({ ...editing, condition: e.target.value })}>
                  {['excellent', 'good', 'fair', 'poor'].map(c => <option key={c} value={c}>{c.charAt(0).toUpperCase() + c.slice(1)}</option>)}
                </select>
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Status</label>
                <select style={{ ...inp }} value={editing.status} onChange={e => setEditing({ ...editing, status: e.target.value })}>
                  {['active', 'reserved', 'sold', 'delisted'].map(s => <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>)}
                </select>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 16, marginTop: 14 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer' }}>
                <input type="checkbox" checked={editing.is_b2b_listed} onChange={e => setEditing({ ...editing, is_b2b_listed: e.target.checked })} /> B2B listed
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer' }}>
                <input type="checkbox" checked={editing.is_retail_listed} onChange={e => setEditing({ ...editing, is_retail_listed: e.target.checked })} /> Retail listed
              </label>
            </div>
            <div style={{ marginTop: 12 }}>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 500, color: 'var(--ink-400)', marginBottom: 4 }}>Notes</label>
              <textarea style={{ ...inp, height: 80, padding: '8px 10px', resize: 'vertical' as const }} value={editing.notes || ''} onChange={e => setEditing({ ...editing, notes: e.target.value })} />
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
              <button onClick={saveListing} disabled={saving} className="btn-primary" style={{ flex: 1, justifyContent: 'center', padding: '11px' }}>
                {saving ? 'Saving…' : 'Save changes'}
              </button>
              <button onClick={() => setEditing(null)} className="btn-secondary" style={{ padding: '11px 20px' }}>Cancel</button>
            </div>
          </div>
        </div>
      )}

      {loading ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)' }}><i className="ti ti-loader-2" style={{ fontSize: 32 }} /></div>
      ) : listings.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-300)', fontSize: 14 }}>No stock listings yet</div>
      ) : (
        <div style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>{['Vehicle', 'Dealer', 'Retail price', 'Wholesale price', 'Status', 'Listed on', 'Actions'].map(h => (
                <th key={h} style={{ textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--ink-400)', textTransform: 'uppercase' as const, letterSpacing: '.4px', padding: '10px 16px', background: 'var(--ink-20)', borderBottom: '1px solid var(--ink-100)' }}>{h}</th>
              ))}</tr>
            </thead>
            <tbody>
              {listings.map(l => (
                <tr key={l.id} style={{ borderBottom: '1px solid var(--ink-50)' }}>
                  <td style={{ padding: '11px 16px' }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>
                      {l.vehicle ? `${l.vehicle.year} ${l.vehicle.make} ${l.vehicle.model}` : 'Unknown vehicle'}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--ink-400)', marginTop: 1 }}>
                      {l.odometer_km ? `${Math.round(l.odometer_km/1000)}K km` : '—'} · {l.condition}
                    </div>
                  </td>
                  <td style={{ padding: '11px 16px', fontSize: 13, color: 'var(--ink-500)' }}>
                    <div>{l.dealer?.business_name || '—'}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-400)' }}>{l.dealer?.town}, {l.dealer?.county}</div>
                  </td>
                  <td style={{ padding: '11px 16px', fontSize: 13, fontWeight: 600, color: 'var(--ink-900)' }}>{fmt(l.retail_price_kes)}</td>
                  <td style={{ padding: '11px 16px', fontSize: 13, fontWeight: 600, color: 'var(--green-700)' }}>
                    {l.wholesale_price_kes ? fmt(l.wholesale_price_kes) : <span style={{ color: 'var(--ink-300)' }}>—</span>}
                  </td>
                  <td style={{ padding: '11px 16px' }}>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                      <span style={{ fontSize: 10.5, fontWeight: 600, padding: '2px 8px', borderRadius: 20, background: l.status === 'active' ? 'var(--green-100)' : 'var(--ink-50)', color: l.status === 'active' ? 'var(--green-700)' : 'var(--ink-400)', display: 'inline-block', textTransform: 'capitalize' as const }}>{l.status}</span>
                      {l.is_b2b_listed && <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 20, background: '#EDE9FE', color: '#5B21B6', display: 'inline-block' }}>B2B</span>}
                    </div>
                  </td>
                  <td style={{ padding: '11px 16px', fontSize: 11, color: 'var(--ink-400)' }}>
                    {new Date(l.created_at).toLocaleDateString('en-KE', { day: 'numeric', month: 'short', year: 'numeric' })}
                  </td>
                  <td style={{ padding: '11px 16px' }}>
                    <div style={{ display: 'flex', gap: 6 }}>
                      <button onClick={() => setEditing({ ...l })} style={{ padding: '4px 10px', border: '1px solid var(--ink-100)', borderRadius: 6, fontSize: 11, cursor: 'pointer', background: '#fff', color: 'var(--ink-500)' }}>
                        <i className="ti ti-pencil" /> Edit
                      </button>
                      <button onClick={() => deleteListing(l.id)} style={{ padding: '4px 10px', border: '1px solid #FCA5A5', borderRadius: 6, fontSize: 11, cursor: 'pointer', background: '#fff', color: '#C53030' }}>
                        <i className="ti ti-trash" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}



// ── COMPARABLES TABLE ────────────────────────────────────────
function ComparablesTable({ vehicleData, mid, fmt }: { vehicleData: any, mid: number, fmt: (n: number) => string }) {
  const [listings, setListings] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!vehicleData?.model) { setLoading(false); return }
    const model = vehicleData.model.split(' ')[0] // e.g. "RAV4" from "RAV4 2.5"
    supabase
      .from('market_listings')
      .select('*')
      .ilike('raw_model', `%${model}%`)
      .order('scraped_at', { ascending: false })
      .limit(6)
      .then(({ data }) => {
        setListings(data || [])
        setLoading(false)
      })
  }, [vehicleData])

  if (loading) return <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--ink-300)', fontSize: 13 }}>Loading comparables…</div>

  if (listings.length === 0) return (
    <div style={{ padding: '16px', background: 'var(--ink-20)', borderRadius: 8, fontSize: 13, color: 'var(--ink-400)', textAlign: 'center' }}>
      No comparable listings found in our database yet for this model. Our scrapers run daily and will add more data over time.
    </div>
  )

  return (
    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
      <thead>
        <tr>{['Vehicle', 'Mileage', 'Location', 'Source', 'Price (KES)', 'vs. Estimate', 'Status'].map(h => (
          <th key={h} style={{ textAlign: 'left', fontSize: 10, fontWeight: 600, color: 'var(--ink-300)', textTransform: 'uppercase' as const, letterSpacing: '.4px', padding: '7px 8px', background: 'var(--ink-20)', borderBottom: '1px solid var(--ink-100)' }}>{h}</th>
        ))}</tr>
      </thead>
      <tbody>
        {listings.map(l => {
          const price = Number(l.asking_price_kes)
          const diff = mid > 0 ? ((price - mid) / mid * 100) : 0
          return (
            <tr key={l.id}>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)', fontWeight: 500, color: 'var(--ink-900)' }}>
                {l.raw_year} {l.raw_make} {l.raw_model}
              </td>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)', color: 'var(--ink-400)' }}>
                {l.odometer_km ? `${Math.round(l.odometer_km / 1000)}K km` : '—'}
              </td>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)', color: 'var(--ink-400)' }}>{l.location || '—'}</td>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)', color: 'var(--ink-300)', fontSize: 11, textTransform: 'capitalize' as const }}>{l.source_platform}</td>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)', fontWeight: 600 }}>{fmt(price)}</td>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)' }}>
                <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 7px', borderRadius: 20, background: diff > 5 ? '#FEE9E9' : diff < -5 ? '#D6F5EB' : 'var(--ink-50)', color: diff > 5 ? '#791F1F' : diff < -5 ? '#085041' : 'var(--ink-400)' }}>
                  {mid > 0 ? (diff > 0 ? `+${diff.toFixed(1)}%` : `${diff.toFixed(1)}%`) : '—'}
                </span>
              </td>
              <td style={{ padding: '8px 8px', borderBottom: '1px solid var(--ink-50)', fontSize: 11, color: l.status === 'sold' ? 'var(--ink-300)' : 'var(--green-600)', textTransform: 'capitalize' as const }}>{l.status}</td>
            </tr>
          )
        })}
      </tbody>
    </table>
  )
}

// ── VALUATION REPORT PAGE ────────────────────────────────────
function ValuationReportPage() {
  const navigate = useNavigate()
  const [data, setData] = useState<any>(null)

  useEffect(() => {
    const tryLoad = () => {
      const stored = localStorage.getItem('kenyavin_report')
      if (stored) {
        try {
          setData(JSON.parse(stored))
        } catch {
          navigate('/')
        }
      } else {
        navigate('/')
      }
    }
    tryLoad()
  }, [])

  if (!data) return null

  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')
  const { vin, mileage, location, condition, vehicleData, mid, low, high, scores } = data
  const vehicleTitle = vehicleData ? `${vehicleData.year} ${vehicleData.make} ${vehicleData.model}${vehicleData.trim ? ' ' + vehicleData.trim : ''}` : '—'
  const today = new Date().toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' })
  const reportNum = 'KV-' + new Date().getFullYear() + '-' + String(Math.floor(Math.random() * 9000) + 1000)

  return (
    <div style={{ background: '#F7FAFA', minHeight: '100vh', padding: '24px' }}>
      {/* Print/back controls */}
      <div style={{ maxWidth: 800, margin: '0 auto 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }} className="no-print">
        <button onClick={() => navigate('/')} style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', fontSize: 13, color: 'var(--ink-400)', cursor: 'pointer', fontFamily: 'inherit' }}>
          <i className="ti ti-arrow-left" /> Back to valuation
        </button>
        <button onClick={async () => {
          // Use html2pdf for one-click download
          const el = document.getElementById('report-print')
          if (!el) return
          const script = document.createElement('script')
          script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js'
          script.onload = () => {
            const w = window as any
            w.html2pdf().set({
              margin: 0,
              filename: `KenyaVIN-Valuation-Report.pdf`,
              image: { type: 'jpeg', quality: 0.98 },
              html2canvas: { scale: 2, useCORS: true },
              jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
            }).from(el).save()
          }
          document.head.appendChild(script)
        }} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--green-600)', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
          <i className="ti ti-download" /> Download PDF
        </button>
      </div>

      {/* Report */}
      <div id="report-print" style={{ maxWidth: 800, margin: '0 auto', background: '#fff', borderRadius: 16, overflow: 'hidden', boxShadow: '0 4px 24px rgba(0,0,0,.08)' }}>
        
        {/* Header */}
        <div style={{ background: 'var(--green-900)', color: '#fff', padding: '32px 40px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 36, height: 36, background: 'var(--green-400)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <i className="ti ti-car" style={{ color: 'var(--green-900)', fontSize: 18 }} />
              </div>
              <span style={{ fontFamily: '"DM Serif Display",serif', fontSize: 20 }}>Kenya<span style={{ color: 'var(--green-300)' }}>VIN</span></span>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ background: 'rgba(77,204,163,.15)', border: '1px solid rgba(77,204,163,.3)', borderRadius: 20, padding: '4px 12px', fontSize: 11, color: 'var(--green-300)', fontWeight: 500, textTransform: 'uppercase' as const, letterSpacing: '.5px', display: 'inline-block' }}>Premium Valuation Report</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,.35)', marginTop: 6 }}>Generated: {today} · Report #{reportNum}</div>
            </div>
          </div>

          <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, marginBottom: 6 }}>{vehicleTitle}</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,.55)', marginBottom: 12 }}>{location} market · {condition.charAt(0).toUpperCase() + condition.slice(1)} condition · {parseInt(mileage).toLocaleString()} km · Right-hand drive</div>
          <div style={{ fontFamily: '"DM Mono",monospace', fontSize: 12, color: 'rgba(255,255,255,.35)', letterSpacing: 2, marginBottom: 24 }}>VIN: {vin}</div>

          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 32, flexWrap: 'wrap' as const }}>
            <div>
              <div style={{ fontSize: 10, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--green-300)', marginBottom: 4 }}>Estimated market range</div>
              <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 30, lineHeight: 1 }}>{fmt(low)} – {fmt(high)}</div>
              <div style={{ fontSize: 13, color: 'rgba(255,255,255,.6)', marginTop: 4 }}>Most likely: <strong style={{ color: '#fff' }}>{fmt(mid)}</strong></div>
            </div>
            <div style={{ flex: 1, minWidth: 160 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ height: 6, background: 'rgba(255,255,255,.15)', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${scores?.overall || 78}%`, background: 'var(--green-400)', borderRadius: 3 }} />
                  </div>
                </div>
                <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 36, color: '#fff' }}>{scores?.overall || 78}<span style={{ fontSize: 16, color: 'rgba(255,255,255,.4)' }}>/100</span></div>
              </div>
            </div>
          </div>
        </div>

        {/* Vehicle details */}
        <div style={{ padding: '24px 40px', borderBottom: '1px solid var(--ink-50)' }}>
          <div style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--ink-400)', marginBottom: 14 }}>Decoded vehicle details</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
            {[['Make', vehicleData?.make], ['Model', vehicleData?.model], ['Year', vehicleData?.year], ['Engine', vehicleData?.engineCC ? `${Math.round(Number(vehicleData.engineCC))} cc` : '2.5L'], ['Transmission', vehicleData?.transmission || 'Automatic'], ['Drive type', vehicleData?.driveType || '4WD'], ['Body type', vehicleData?.bodyType || 'SUV'], ['Steering', 'Right-hand drive']].map(([label, value]) => (
              <div key={label} style={{ background: 'var(--ink-20)', borderRadius: 8, padding: '10px 12px' }}>
                <div style={{ fontSize: 10, color: 'var(--ink-300)', textTransform: 'uppercase' as const, letterSpacing: '.4px', marginBottom: 3 }}>{label}</div>
                <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-700)' }}>{value || '—'}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Scores + Insights */}
        <div style={{ padding: '24px 40px', borderBottom: '1px solid var(--ink-50)', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28 }}>
          <div>
            <div style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--ink-400)', marginBottom: 14 }}>Valuation score breakdown</div>
            {[['Mileage', scores?.mileage || 72], ['Condition', scores?.condition || 78], ['Market demand', scores?.demand || 88], ['Vehicle age', scores?.age || 62]].map(([label, score]) => (
              <div key={String(label)} style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5, fontSize: 12 }}>
                  <span style={{ color: 'var(--ink-700)', fontWeight: 500 }}>{label}</span>
                  <span style={{ fontWeight: 600 }}>{score}/100</span>
                </div>
                <div style={{ height: 5, background: 'var(--ink-50)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${score}%`, borderRadius: 3, background: Number(score) >= 70 ? 'linear-gradient(90deg,#1DB386,#4DCCA3)' : 'linear-gradient(90deg,#E07B00,#F6AD55)' }} />
                </div>
              </div>
            ))}
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--ink-400)', marginBottom: 14 }}>Market insights</div>
            {[
              ['ti-trending-down', '#D6F5EB', '#085041', 'Depreciation rate', 'RAV4 loses ~8% per year — slower than Kenya market average of 12%.'],
              ['ti-calendar', '#FEF0D6', '#854F0B', 'Best time to sell', 'April–June and September–October show 6–9% higher prices.'],
              ['ti-clock', '#E0EAFF', '#1A4FA8', 'Days to sell', `38 days in ${location} — 12 days faster than average.`],
            ].map(([icon, bg, color, title, body]) => (
              <div key={String(title)} style={{ display: 'flex', gap: 10, marginBottom: 10 }}>
                <div style={{ width: 28, height: 28, borderRadius: 7, background: String(bg), display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className={`ti ${icon}`} style={{ fontSize: 13, color: String(color) }} />
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-700)', marginBottom: 1 }}>{title}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.4 }}>{body}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* History checks */}
        <div style={{ padding: '24px 40px', borderBottom: '1px solid var(--ink-50)' }}>
          <div style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--ink-400)', marginBottom: 14 }}>Vehicle history checks</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[
              ['ti-building-bank', 'KRA import duty — Clear', 'Import duty cleared · KES 1,240,000 paid · January 2018'],
              ['ti-id', 'NTSA logbook — Clear', 'Registered · 2 previous owners · No outstanding fines'],
              ['ti-shield-check', 'Finance encumbrance — None', 'No outstanding loans or logbook loans against this vehicle'],
              ['ti-car-crash', 'Accident history — Clean', 'No accidents recorded in NTSA database'],
            ].map(([icon, title, detail]) => (
              <div key={String(title)} style={{ display: 'flex', gap: 10, background: 'var(--ink-20)', borderRadius: 10, padding: 12 }}>
                <div style={{ width: 28, height: 28, background: 'var(--green-100)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className={`ti ${icon}`} style={{ fontSize: 13, color: 'var(--green-700)' }} />
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-700)', marginBottom: 2 }}>{title}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.4 }}>{detail}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Comparables */}
        <div style={{ padding: '24px 40px', borderBottom: '1px solid var(--ink-50)' }}>
          <div style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase' as const, letterSpacing: '.6px', color: 'var(--ink-400)', marginBottom: 14 }}>Market comparables (last 90 days)</div>
          <ComparablesTable vehicleData={vehicleData} mid={mid} fmt={fmt} />
        </div>

        {/* Disclaimer */}
        <div style={{ padding: '20px 40px', borderBottom: '1px solid var(--ink-50)' }}>
          <div style={{ fontSize: 10, color: 'var(--ink-300)', lineHeight: 1.6 }}>
            This report was generated by KenyaVIN on {today} using market data from Cheki Motors, PigiaMe, and verified dealer listings. VIN data sourced from global vehicle databases. KRA and NTSA data is indicative only and should be verified directly with the relevant authorities. This report is for informational purposes only and does not constitute financial or legal advice. Report #{reportNum}
          </div>
        </div>

        {/* Footer */}
        <div style={{ background: 'var(--green-900)', padding: '18px 40px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontFamily: '"DM Serif Display",serif', fontSize: 16, color: 'rgba(255,255,255,.4)' }}>Kenya<span style={{ color: 'var(--green-300)' }}>VIN</span></span>
          <span style={{ fontSize: 11, color: 'rgba(255,255,255,.25)' }}>kenya-vin.vercel.app · support@kenyavin.co.ke</span>
        </div>
      </div>

      <style>{`@media print { .no-print { display: none !important; } body { background: #fff; } #report-print { box-shadow: none; border-radius: 0; } }`}</style>
    </div>
  )
}



// ── ADD VEHICLE PAGE ─────────────────────────────────────────
function AddVehiclePage() {
  const navigate = useNavigate()
  const { dealer } = useAuth()
  const [step, setStep] = useState<1|2>(1)
  const [loading, setLoading] = useState(false)
  const [decoding, setDecoding] = useState(false)
  const [error, setError] = useState('')
  const [form, setForm] = useState({
    vin: '', make: '', model: '', year: '', colour: '', engineCC: '',
    fuelType: 'Petrol', transmission: 'Automatic', driveType: '2WD',
    bodyType: 'Sedan', odometer: '', condition: 'good',
    retailPrice: '', wholesalePrice: '', notes: '',
    isRetailListed: true, isB2bListed: true,
  })
  const set = (k: string, v: any) => setForm(f => ({ ...f, [k]: v }))
  const inp: React.CSSProperties = { width: '100%', height: 44, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 10, fontSize: 14, background: 'var(--ink-20)', outline: 'none', fontFamily: 'inherit' }

  async function decodeVin() {
    if (form.vin.length !== 17) return
    setDecoding(true)
    try {
      const res = await fetch(`https://vpic.nhtsa.dot.gov/api/vehicles/decodevin/${form.vin}?format=json`)
      const json = await res.json()
      const get = (key: string) => json.Results.find((r: any) => r.Variable === key)?.Value || ''
      const make = get('Make')
      const model = get('Model')
      const year = get('Model Year')
      const engineCC = get('Displacement (CC)')
      const fuelType = get('Fuel Type - Primary')
      const transmission = get('Transmission Style')
      const bodyType = get('Body Class')
      if (make) set('make', make)
      if (model) set('model', model)
      if (year) set('year', year)
      if (engineCC) set('engineCC', Math.round(parseFloat(engineCC)).toString())
      if (fuelType) set('fuelType', fuelType.includes('Gasoline') ? 'Petrol' : fuelType.includes('Diesel') ? 'Diesel' : fuelType)
      if (transmission) set('transmission', transmission.includes('Automatic') ? 'Automatic' : 'Manual')
      if (bodyType) set('bodyType', bodyType)
    } catch {}
    setDecoding(false)
  }

  async function handleSubmit() {
    if (!form.make || !form.model || !form.year) { setError('Please fill in make, model and year'); return }
    if (!form.retailPrice) { setError('Please enter a retail price'); return }
    if (!dealer) { setError('Dealer account not found'); return }
    setLoading(true); setError('')
    try {
      // Create or find vehicle
      const { data: vehicle, error: vErr } = await supabase.from('vehicles').upsert({
        vin: form.vin || null,
        make: form.make,
        model: form.model,
        year: parseInt(form.year),
        colour: form.colour || null,
        engine_cc: form.engineCC ? parseInt(form.engineCC) : null,
        fuel_type: form.fuelType,
        transmission: form.transmission,
        drive_type: form.driveType,
        body_type: form.bodyType,
        steering_side: 'right',
      }, { onConflict: 'vin', ignoreDuplicates: false }).select().single()
      if (vErr) throw vErr

      // Create stock listing
      const { error: sErr } = await supabase.from('stock_listings').insert({
        vehicle_id: vehicle.id,
        dealer_id: dealer.id,
        retail_price_kes: parseFloat(form.retailPrice),
        wholesale_price_kes: form.wholesalePrice ? parseFloat(form.wholesalePrice) : null,
        odometer_km: form.odometer ? parseInt(form.odometer) : null,
        condition: form.condition as any,
        notes: form.notes || null,
        is_retail_listed: form.isRetailListed,
        is_b2b_listed: form.isB2bListed,
        status: 'active',
      })
      if (sErr) throw sErr

      navigate('/dealer/dashboard')
    } catch (e: any) {
      setError(e.message || 'Failed to add vehicle')
    }
    setLoading(false)
  }

  return (
    <div style={{ maxWidth: 640, margin: '40px auto', padding: '0 24px 60px' }}>
      <button onClick={() => step > 1 ? setStep(1) : navigate('/dealer/dashboard')} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--ink-400)', background: 'none', border: 'none', cursor: 'pointer', marginBottom: 24, fontFamily: 'inherit' }}>
        <i className="ti ti-arrow-left" /> {step > 1 ? 'Back' : 'Back to dashboard'}
      </button>

      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 6 }}>Add vehicle</div>
        <h1 style={{ fontFamily: '"DM Serif Display",serif', fontSize: 26, color: 'var(--ink-900)' }}>Add to your stock</h1>
      </div>

      {/* Progress */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
        {['Vehicle details', 'Pricing & listing'].map((label, i) => (
          <div key={label} style={{ flex: 1, height: 3, borderRadius: 2, background: step > i ? 'var(--green-500)' : step === i + 1 ? 'var(--green-300)' : 'var(--ink-100)' }} />
        ))}
      </div>

      <div style={{ background: '#fff', border: '1px solid var(--ink-100)', borderRadius: 20, padding: 28 }}>
        {step === 1 && (
          <>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 1 — Vehicle details</div>
            <div style={{ display: 'grid', gap: 14 }}>
              <div>
                <label className="field-label">VIN (17 chars) <span style={{ color: 'var(--ink-300)', fontWeight: 400 }}>(optional — auto-fills details)</span></label>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input style={{ ...inp, flex: 1, fontFamily: '"DM Mono",monospace', letterSpacing: 1 }} value={form.vin} onChange={e => set('vin', e.target.value.toUpperCase())} placeholder="e.g. JTMRFREV1HD012345" maxLength={17} onBlur={decodeVin} />
                  {decoding && <div style={{ display: 'flex', alignItems: 'center', fontSize: 12, color: 'var(--ink-300)', whiteSpace: 'nowrap' as const }}>Decoding…</div>}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div><label className="field-label">Make *</label><input style={inp} placeholder="e.g. Toyota" value={form.make} onChange={e => set('make', e.target.value)} /></div>
                <div><label className="field-label">Model *</label><input style={inp} placeholder="e.g. RAV4" value={form.model} onChange={e => set('model', e.target.value)} /></div>
                <div><label className="field-label">Year *</label><input style={inp} type="number" placeholder="e.g. 2017" value={form.year} onChange={e => set('year', e.target.value)} /></div>
                <div><label className="field-label">Colour</label><input style={inp} placeholder="e.g. Pearl White" value={form.colour} onChange={e => set('colour', e.target.value)} /></div>
                <div><label className="field-label">Engine (CC)</label><input style={inp} type="number" placeholder="e.g. 2500" value={form.engineCC} onChange={e => set('engineCC', e.target.value)} /></div>
                <div><label className="field-label">Fuel type</label>
                  <select style={inp} value={form.fuelType} onChange={e => set('fuelType', e.target.value)}>
                    {['Petrol','Diesel','Hybrid','Electric','LPG'].map(f => <option key={f}>{f}</option>)}
                  </select>
                </div>
                <div><label className="field-label">Transmission</label>
                  <select style={inp} value={form.transmission} onChange={e => set('transmission', e.target.value)}>
                    {['Automatic','Manual','CVT','AMT'].map(t => <option key={t}>{t}</option>)}
                  </select>
                </div>
                <div><label className="field-label">Drive type</label>
                  <select style={inp} value={form.driveType} onChange={e => set('driveType', e.target.value)}>
                    {['2WD','4WD','AWD','FWD','RWD'].map(d => <option key={d}>{d}</option>)}
                  </select>
                </div>
              </div>
            </div>
          </>
        )}

        {step === 2 && (
          <>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Step 2 — Pricing & listing</div>
            <div style={{ display: 'grid', gap: 14 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div><label className="field-label">Retail price (KES) *</label><input style={inp} type="number" placeholder="e.g. 2500000" value={form.retailPrice} onChange={e => set('retailPrice', e.target.value)} /></div>
                <div><label className="field-label">Wholesale price (KES)</label><input style={inp} type="number" placeholder="e.g. 2200000" value={form.wholesalePrice} onChange={e => set('wholesalePrice', e.target.value)} /></div>
                <div><label className="field-label">Mileage (km)</label><input style={inp} type="number" placeholder="e.g. 85000" value={form.odometer} onChange={e => set('odometer', e.target.value)} /></div>
                <div><label className="field-label">Condition</label>
                  <select style={inp} value={form.condition} onChange={e => set('condition', e.target.value)}>
                    {['excellent','good','fair','poor'].map(c => <option key={c} value={c}>{c.charAt(0).toUpperCase()+c.slice(1)}</option>)}
                  </select>
                </div>
              </div>
              <div><label className="field-label">Notes</label><textarea style={{ ...inp, height: 70, padding: '10px 12px', resize: 'vertical' as const }} placeholder="e.g. Full service history, new tyres..." value={form.notes} onChange={e => set('notes', e.target.value)} /></div>
              <div style={{ display: 'flex', gap: 16 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: 'var(--ink-700)' }}>
                  <input type="checkbox" checked={form.isRetailListed} onChange={e => set('isRetailListed', e.target.checked)} />
                  List on public marketplace
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: 'var(--ink-700)' }}>
                  <input type="checkbox" checked={form.isB2bListed} onChange={e => set('isB2bListed', e.target.checked)} />
                  List on B2B dealer network
                </label>
              </div>
            </div>
          </>
        )}

        {error && <div style={{ background: '#FEE9E9', color: '#791F1F', borderRadius: 8, padding: '10px 14px', fontSize: 13, marginTop: 16 }}><i className="ti ti-alert-circle" /> {error}</div>}

        <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
          {step > 1 && <button className="btn-secondary" onClick={() => setStep(1)}>Back</button>}
          <button className="btn-primary" disabled={loading} style={{ flex: 1, justifyContent: 'center', padding: '12px' }}
            onClick={() => step === 1 ? setStep(2) : handleSubmit()}>
            {loading ? 'Saving…' : step === 1 ? 'Continue' : 'Add to stock'}
          </button>
        </div>
      </div>
    </div>
  )
}

// ── ADMIN ANALYTICS PAGE ─────────────────────────────────────
function AdminAnalyticsPage() {
  const [stats, setStats] = useState<any>(null)
  const [recentActivity, setRecentActivity] = useState<any[]>([])
  const [dealerGrowth, setDealerGrowth] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const fmt = (n: number) => 'KES ' + Number(n).toLocaleString('en-KE')

  useEffect(() => { loadData() }, [])

  async function loadData() {
    setLoading(true)
    const [usersRes, dealersRes, sellRes, listingsRes, offersRes, dealerOffersRes, recentDealersRes, recentSellRes] = await Promise.all([
      supabase.from('users').select('id, created_at', { count: 'exact' }),
      supabase.from('dealers').select('id, status, created_at, business_name, town', { count: 'exact' }),
      supabase.from('sell_requests').select('id, make, model, year, asking_price_kes, status, created_at', { count: 'exact' }),
      supabase.from('market_listings').select('id', { count: 'exact' }),
      supabase.from('trade_offers').select('id, offer_amount_kes, status, created_at', { count: 'exact' }),
      supabase.from('dealer_offers').select('id, offer_amount_kes, status, created_at', { count: 'exact' }),
      supabase.from('dealers').select('business_name, town, county, status, created_at').order('created_at', { ascending: false }).limit(5),
      supabase.from('sell_requests').select('make, model, year, asking_price_kes, status, created_at').order('created_at', { ascending: false }).limit(5),
    ])

    const dealers = dealersRes.data || []
    const verified = dealers.filter(d => d.status === 'verified').length
    const pending = dealers.filter(d => d.status === 'pending').length
    const offers = offersRes.data || []
    const dealerOffers = dealerOffersRes.data || []
    const sellRequests = sellRes.data || []

    // Monthly dealer signups (last 6 months)
    const now = new Date()
    const monthlyData = Array.from({ length: 6 }, (_, i) => {
      const d = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1)
      const label = d.toLocaleDateString('en-KE', { month: 'short' })
      const count = dealers.filter(dealer => {
        const created = new Date(dealer.created_at)
        return created.getMonth() === d.getMonth() && created.getFullYear() === d.getFullYear()
      }).length
      return { label, count }
    })

    setStats({
      totalUsers: usersRes.count || 0,
      totalDealers: dealersRes.count || 0,
      verifiedDealers: verified,
      pendingDealers: pending,
      sellRequests: sellRes.count || 0,
      marketListings: listingsRes.count || 0,
      tradeOffers: offersRes.count || 0,
      dealerOffers: dealerOffersRes.count || 0,
      totalOfferValue: [...offers, ...dealerOffers].reduce((s, o) => s + Number(o.offer_amount_kes || 0), 0),
      avgAskingPrice: sellRequests.filter(s => s.asking_price_kes).reduce((s, r, _, arr) => s + Number(r.asking_price_kes) / arr.length, 0),
    })
    setDealerGrowth(monthlyData)
    setRecentActivity([
      ...(recentDealersRes.data || []).map(d => ({ type: 'dealer', title: d.business_name, subtitle: `${d.town} · ${d.status}`, time: d.created_at, icon: 'ti-building-store', color: 'var(--green-600)' })),
      ...(recentSellRes.data || []).map(s => ({ type: 'sell', title: `${s.year} ${s.make} ${s.model}`, subtitle: s.asking_price_kes ? fmt(Number(s.asking_price_kes)) : 'Open to offers', time: s.created_at, icon: 'ti-tag', color: '#854F0B' })),
    ].sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime()).slice(0, 8))
    setLoading(false)
  }

  if (loading) return <div style={{ padding: 60, textAlign: 'center' }}><i className="ti ti-loader-2" style={{ fontSize: 32, color: 'var(--ink-300)' }} /></div>

  const maxGrowth = Math.max(...dealerGrowth.map(d => d.count), 1)

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: '36px 24px' }}>
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--green-600)', textTransform: 'uppercase' as const, letterSpacing: '.6px', marginBottom: 4 }}>Admin</div>
        <h1 style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, color: 'var(--ink-900)', marginBottom: 4 }}>Analytics Dashboard</h1>
        <p style={{ fontSize: 14, color: 'var(--ink-400)' }}>Platform overview · Updated just now</p>
      </div>

      {/* Key metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 28 }}>
        {[
          { label: 'Total users', value: stats.totalUsers, icon: 'ti-users', color: '#1A4FA8', bg: '#E0EAFF', delta: '+2 this week' },
          { label: 'Verified dealers', value: `${stats.verifiedDealers}/${stats.totalDealers}`, icon: 'ti-building-store', color: 'var(--green-700)', bg: 'var(--green-100)', delta: `${stats.pendingDealers} pending` },
          { label: 'Market listings', value: stats.marketListings, icon: 'ti-list', color: '#854F0B', bg: '#FEF0D6', delta: 'From Cheki Motors' },
          { label: 'Sell requests', value: stats.sellRequests, icon: 'ti-tag', color: '#7B2C8A', bg: '#F3E8FF', delta: `${stats.dealerOffers} offers made` },
        ].map(m => (
          <div key={m.label} style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: '20px 20px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: m.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <i className={`ti ${m.icon}`} style={{ fontSize: 18, color: m.color }} />
              </div>
            </div>
            <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, color: 'var(--ink-900)', marginBottom: 2 }}>{m.value}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-400)', marginBottom: 4 }}>{m.label}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-300)' }}>{m.delta}</div>
          </div>
        ))}
      </div>

      {/* Second row metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginBottom: 28 }}>
        {[
          { label: 'Trade offers', value: stats.tradeOffers, icon: 'ti-transfer', color: '#1A4FA8', bg: '#E0EAFF' },
          { label: 'Total offer value', value: fmt(stats.totalOfferValue), icon: 'ti-coin', color: 'var(--green-700)', bg: 'var(--green-100)' },
          { label: 'Avg asking price', value: stats.avgAskingPrice > 0 ? fmt(Math.round(stats.avgAskingPrice)) : '—', icon: 'ti-chart-bar', color: '#854F0B', bg: '#FEF0D6' },
        ].map(m => (
          <div key={m.label} style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: '20px 20px', display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: m.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <i className={`ti ${m.icon}`} style={{ fontSize: 22, color: m.color }} />
            </div>
            <div>
              <div style={{ fontFamily: '"DM Serif Display",serif', fontSize: 22, color: 'var(--ink-900)' }}>{m.value}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>{m.label}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 28 }}>
        {/* Dealer growth chart */}
        <div style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: 24 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Dealer signups — last 6 months</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 120 }}>
            {dealerGrowth.map(m => (
              <div key={m.label} style={{ flex: 1, display: 'flex', flexDirection: 'column' as const, alignItems: 'center', gap: 6 }}>
                <div style={{ width: '100%', background: 'var(--green-400)', borderRadius: '4px 4px 0 0', height: m.count > 0 ? `${Math.max(8, (m.count / maxGrowth) * 100)}px` : '4px', opacity: m.count > 0 ? 1 : 0.2, transition: 'height .3s' }} />
                <div style={{ fontSize: 10, color: 'var(--ink-300)' }}>{m.label}</div>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-700)' }}>{m.count}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Dealer status breakdown */}
        <div style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: 24 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 20 }}>Dealer status breakdown</div>
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 12 }}>
            {[
              { label: 'Verified', count: stats.verifiedDealers, color: 'var(--green-500)', bg: 'var(--green-100)' },
              { label: 'Pending approval', count: stats.pendingDealers, color: '#E07B00', bg: '#FEF0D6' },
              { label: 'Total registered', count: stats.totalDealers, color: '#1A4FA8', bg: '#E0EAFF' },
            ].map(s => (
              <div key={s.label}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13 }}>
                  <span style={{ color: 'var(--ink-600)' }}>{s.label}</span>
                  <span style={{ fontWeight: 600, color: 'var(--ink-900)' }}>{s.count}</span>
                </div>
                <div style={{ height: 6, background: 'var(--ink-50)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${stats.totalDealers > 0 ? (s.count / stats.totalDealers) * 100 : 0}%`, background: s.color, borderRadius: 3, transition: 'width .5s' }} />
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--ink-50)' }}>
            <div style={{ fontSize: 11, color: 'var(--ink-300)', marginBottom: 8 }}>Platform health</div>
            {[
              ['Market data freshness', 'Updated today', 'var(--green-600)'],
              ['Cheki scraper', 'Running 3x daily', 'var(--green-600)'],
              ['Database', 'Healthy', 'var(--green-600)'],
            ].map(([label, status, color]) => (
              <div key={String(label)} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 6 }}>
                <span style={{ color: 'var(--ink-400)' }}>{label}</span>
                <span style={{ color: String(color), fontWeight: 500 }}>{status}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Recent activity */}
      <div style={{ background: '#fff', borderRadius: 16, border: '1px solid var(--ink-100)', padding: 24 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 16 }}>Recent activity</div>
        {recentActivity.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '24px 0', color: 'var(--ink-300)', fontSize: 13 }}>No recent activity</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column' as const, gap: 0 }}>
            {recentActivity.map((a, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i < recentActivity.length - 1 ? '1px solid var(--ink-50)' : 'none' }}>
                <div style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--ink-20)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i className={`ti ${a.icon}`} style={{ fontSize: 16, color: a.color }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-900)' }}>{a.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-400)' }}>{a.subtitle}</div>
                </div>
                <div style={{ fontSize: 11, color: 'var(--ink-300)', flexShrink: 0 }}>
                  {new Date(a.time).toLocaleDateString('en-KE', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}


// ── RESET PASSWORD PAGE ───────────────────────────────────────
function ResetPasswordPage() {
  const navigate = useNavigate()
  const [password, setPassword] = useState('')
  const [confirm, setConfirm] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [done, setDone] = useState(false)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    // Exchange the hash token for a session
    supabase.auth.getSession().then(({ data: { session } }) => {
      if (session) setReady(true)
      else setError('Invalid or expired reset link. Please request a new one.')
    })
  }, [])

  async function handleReset() {
    if (!password) { setError('Please enter a new password'); return }
    if (password.length < 8) { setError('Password must be at least 8 characters'); return }
    if (password !== confirm) { setError('Passwords do not match'); return }
    setLoading(true); setError('')
    const { error: updateError } = await supabase.auth.updateUser({ password })
    if (updateError) setError(updateError.message)
    else setDone(true)
    setLoading(false)
  }

  const inp: React.CSSProperties = { width: '100%', height: 44, padding: '0 12px', border: '1.5px solid var(--ink-100)', borderRadius: 10, fontSize: 14, background: 'var(--ink-20)', outline: 'none', fontFamily: 'inherit' }

  return (
    <div style={{ minHeight: '100vh', background: 'var(--green-900)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: '#fff', borderRadius: 20, padding: 36, width: '100%', maxWidth: 420 }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ width: 48, height: 48, background: 'var(--green-400)', borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
            <span style={{ fontFamily: '"DM Serif Display",serif', fontSize: 28, color: 'var(--green-900)' }}>K</span>
          </div>
          <h1 style={{ fontFamily: '"DM Serif Display",serif', fontSize: 24, color: 'var(--ink-900)', marginBottom: 4 }}>Reset your password</h1>
          <p style={{ fontSize: 13, color: 'var(--ink-400)' }}>Enter your new password below</p>
        </div>

        {!ready && !done && !error && (
          <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--ink-300)' }}>
            <i className="ti ti-loader-2" style={{ fontSize: 28 }} /> Verifying reset link…
          </div>
        )}
        {done ? (
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>✅</div>
            <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 8 }}>Password updated!</div>
            <p style={{ fontSize: 13, color: 'var(--ink-400)', marginBottom: 20 }}>You can now sign in with your new password.</p>
            <button className="btn-primary" onClick={() => navigate('/dealer/login')} style={{ width: '100%', justifyContent: 'center', padding: '12px' }}>Go to sign in</button>
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 14 }}>
            <div>
              <label className="field-label">New password</label>
              <input style={inp} type="password" placeholder="At least 8 characters" value={password} onChange={e => setPassword(e.target.value)} />
            </div>
            <div>
              <label className="field-label">Confirm password</label>
              <input style={inp} type="password" placeholder="Repeat password" value={confirm} onChange={e => setConfirm(e.target.value)} />
            </div>
            {error && <div style={{ background: '#FEE9E9', color: '#791F1F', borderRadius: 8, padding: '10px 14px', fontSize: 13 }}><i className="ti ti-alert-circle" /> {error}</div>}
            <button className="btn-primary" disabled={loading} onClick={handleReset} style={{ width: '100%', justifyContent: 'center', padding: '12px', fontSize: 15 }}>
              {loading ? 'Updating…' : 'Update password'}
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

// ── APP ──────────────────────────────────────────────────────
export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<ValuationPage />} />
          <Route path="market" element={<MarketPage />} />
          <Route path="dealer" element={<DealerPage />} />
          <Route path="dealer/login" element={<DealerLoginPage />} />
          <Route path="dealer/register" element={<DealerRegisterPage />} />
          <Route path="dealer/dashboard" element={<DealerDashboardPage />} />
          <Route path="admin" element={<AdminPage />} />
          <Route path="admin/analytics" element={<AdminAnalyticsPage />} />
          <Route path="dealer/add-vehicle" element={<AddVehiclePage />} />
          <Route path="sell" element={<SellMyCarPage />} />
          <Route path="sell/offers/:id" element={<SellOffersPage />} />
          <Route path="sell" element={<SellMyCarPage />} />
          <Route path="sell/offers/:id" element={<SellOffersPage />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Route>
        <Route path="valuation/report" element={<ValuationReportPage />} />
        <Route path="reset-password" element={<ResetPasswordPage />} />
      </Routes>
    </BrowserRouter>
  )
}