/* Me2You - Property & Vehicle listings (C2C rentals, houses, cars, bikes) */
/* global React, Icon, Price, CondTag, panelStyle, btnPrimary, btnGhost, btnSmall, LeafletMap, CITY_COORDS */

const { useState, useMemo } = React;

/* --- Property listings: houses, apartments, rooms, student digs --- */
const PROPERTIES = [
  { id:'p1', kind:'rental', type:'Room to share', title:'Single room in 3-bed flat near Wits', monthly:2800, bedrooms:1, bathrooms:1, sqm:14,
    location:'Braamfontein', suburb:'Braamfontein', coords:[-26.1933, 28.0367], seller:'Lerato N.',
    available:'Immediate', furnished:true, students:true, pets:false, deposit:2800, description:'Furnished room in a clean shared flat. 5 min walk to Wits campus. Includes wifi, water and lights. 2 female housemates, both postgrad students.' },
  { id:'p2', kind:'rental', type:'Bachelor flat', title:'Bachelor flat, secure complex Hatfield', monthly:5200, bedrooms:0, bathrooms:1, sqm:32,
    location:'Hatfield', suburb:'Hatfield', coords:[-25.7470, 28.2353], seller:'Pieter V.', available:'1 June', furnished:false, students:true, pets:false, deposit:5200,
    description:'Secure complex, 24-hr access control, parking bay, prepaid electricity. 4 min walk to Tuks main gate.' },
  { id:'p3', kind:'rental', type:'2-bed apartment', title:'Modern 2-bed apartment, Sandton CBD', monthly:13500, bedrooms:2, bathrooms:2, sqm:78,
    location:'Sandton', suburb:'Sandton', coords:[-26.1076, 28.0567], seller:'Grace D.', available:'15 June', furnished:true, students:false, pets:true, deposit:27000,
    description:'High-rise, 12th floor, full city views. Pool, gym, biometric access. Walking distance to Sandton City and Gautrain.' },
  { id:'p4', kind:'rental', type:'Family house', title:'3-bed family home with garden, Soweto', monthly:8500, bedrooms:3, bathrooms:2, sqm:145,
    location:'Soweto', suburb:'Pimville', coords:[-26.2678, 27.8585], seller:'Sipho M.', available:'1 July', furnished:false, students:false, pets:true, deposit:8500,
    description:'Spacious family home, large yard, double garage, prepaid water and lights. Quiet street.' },
  { id:'p5', kind:'rental', type:'Garden cottage', title:'Garden cottage near UCT', monthly:6800, bedrooms:1, bathrooms:1, sqm:42,
    location:'Rondebosch', suburb:'Rondebosch', coords:[-33.9636, 18.4747], seller:'Naledi S.', available:'Immediate', furnished:true, students:true, pets:false, deposit:6800,
    description:'Separate entrance, private patio, full kitchen, fibre wifi included. 8 min from UCT Jammie Shuttle stop.' },
  { id:'p6', kind:'rental', type:'Student commune', title:'Room in 5-bed student commune Stellies', monthly:3400, bedrooms:1, bathrooms:2, sqm:16,
    location:'Stellenbosch', suburb:'Stellenbosch', coords:[-33.9322, 18.8602], seller:'Jan D.', available:'1 February', furnished:true, students:true, pets:false, deposit:3400,
    description:'Mixed-gender student commune, 5 min cycle from Maties. Cleaner once a week, weekly braais, wifi included.' },
  { id:'p7', kind:'sale', type:'2-bed townhouse', title:'2-bed townhouse for sale, secure estate', monthly:0, price:780000, bedrooms:2, bathrooms:1, sqm:84,
    location:'Roodepoort', suburb:'Wilgeheuwel', coords:[-26.1625, 27.8725], seller:'Hennie V.', available:'Negotiable', furnished:false, students:false, pets:true, deposit:0,
    description:'For sale by owner. Secure estate, single garage, small private garden. Levies R 1 240/mo. No agent commission.' },
  { id:'p8', kind:'sale', type:'4-bed house', title:'4-bed family home for sale, ready to move', monthly:0, price:1450000, bedrooms:4, bathrooms:2, sqm:212,
    location:'Pretoria', suburb:'Garsfontein', coords:[-25.8003, 28.3045], seller:'Marco P.', available:'Immediate', furnished:false, students:false, pets:true, deposit:0,
    description:'No agent commission. Private c2c sale. Solar geyser, JoJo tanks, double garage. Title deed in hand.' },
];

/* --- Vehicle listings: cars, bikes, scooters --- */
const VEHICLES = [
  { id:'v1', kind:'car', title:'Toyota Etios 1.5 Xs', year:2018, mileage:78500, price:128000, fuel:'Petrol', transmission:'Manual',
    location:'Soweto', coords:[-26.2678, 27.8585], seller:'Sipho M.', description:'One owner, full service history at Toyota, just had major service. Aircon ice cold. Selling because upgrading.' },
  { id:'v2', kind:'car', title:'VW Polo Vivo 1.4 Trendline', year:2020, mileage:42100, price:165000, fuel:'Petrol', transmission:'Manual',
    location:'Pretoria', coords:[-25.7479, 28.2293], seller:'Lerato N.', description:'Pristine condition, female-driven, never been in an accident. Service plan valid until Oct 2026.' },
  { id:'v3', kind:'car', title:'Ford Ranger 2.2 XLS double cab', year:2017, mileage:142000, price:285000, fuel:'Diesel', transmission:'Manual',
    location:'Nelspruit', coords:[-25.4753, 30.9694], seller:'David L.', description:'Bakkie in great shape. Tow bar, bull bar, canopy included. New tyres last month.' },
  { id:'v4', kind:'car', title:'Hyundai i10 1.1 Motion', year:2015, mileage:98700, price:75000, fuel:'Petrol', transmission:'Manual',
    location:'Cape Town', coords:[-33.9249, 18.4241], seller:'Naledi S.', description:'Perfect first car or student car. Light on fuel, cheap to insure, papers up to date.' },
  { id:'v5', kind:'bike', title:'Honda CBR 125 sport bike', year:2019, mileage:18400, price:24000, fuel:'Petrol', transmission:'Manual',
    location:'Johannesburg', coords:[-26.2041, 28.0473], seller:'Mandla K.', description:'Lightweight learner bike, full service history. Helmet and jacket included if you collect.' },
  { id:'v6', kind:'scooter', title:'Vespa Primavera 150', year:2021, mileage:6200, price:48000, fuel:'Petrol', transmission:'Auto',
    location:'Sandton', coords:[-26.1076, 28.0567], seller:'Tumi B.', description:'Like-new condition, only used on weekends. Top box included. Pink, very cool.' },
  { id:'v7', kind:'bike', title:'Mountain bike, 26", aluminium', year:2022, mileage:0, price:3200, fuel:'-', transmission:'21-speed',
    location:'Rustenburg', coords:[-25.6672, 27.2424], seller:'Chris N.', description:'21-speed Shimano, hydraulic disc brakes. Used a handful of times. Trail-ready.' },
];

/* ============================================================
   PROPERTY GRID & FILTERS
============================================================== */
function PropertyBrowse({ onSelect }) {
  const [intent, setIntent] = useState('rent'); // rent | buy | student
  const [maxRent, setMaxRent] = useState(8000);
  const [maxPrice, setMaxPrice] = useState(2000000);
  const [bedrooms, setBedrooms] = useState(0);
  const [view, setView] = useState('grid');

  const filtered = useMemo(() => {
    let list = PROPERTIES;
    if (intent === 'rent') list = list.filter(p => p.kind === 'rental');
    else if (intent === 'buy') list = list.filter(p => p.kind === 'sale');
    else if (intent === 'student') list = list.filter(p => p.students);
    if (intent === 'rent' || intent === 'student') list = list.filter(p => p.monthly <= maxRent);
    if (intent === 'buy') list = list.filter(p => (p.price || 0) <= maxPrice);
    if (bedrooms > 0) list = list.filter(p => p.bedrooms >= bedrooms);
    return list;
  }, [intent, maxRent, maxPrice, bedrooms]);

  const mapMarkers = filtered.map(p => ({
    lat: p.coords[0], lng: p.coords[1],
    label: p.kind === 'sale' ? 'R' : (p.students ? 'S' : '$'),
    color: p.kind === 'sale' ? '#2D7AC7' : (p.students ? '#2F9E5A' : '#F89A1F'),
    popup: `<b>${p.title}</b><br/>${p.kind === 'sale' ? 'R ' + (p.price/1000).toFixed(0) + 'k' : 'R ' + p.monthly.toLocaleString('en-ZA') + '/mo'}<br/>${p.bedrooms} bed - ${p.bathrooms} bath - ${p.sqm} m2`,
  }));

  return (
    <div>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:16,flexWrap:'wrap',gap:12}}>
        <div>
          <h2 style={{margin:0}}>Houses, rooms & apartments</h2>
          <p style={{color:'var(--ink-500)',fontSize:13,margin:'4px 0 0'}}>
            Direct from owners. No agent commission. {filtered.length} listings.
          </p>
        </div>
        <div style={{display:'flex',gap:2,padding:4,background:'var(--ink-100)',borderRadius:999}}>
          <button onClick={() => setView('grid')} style={viewBtn(view==='grid')}>Grid</button>
          <button onClick={() => setView('map')} style={viewBtn(view==='map')}>Map</button>
        </div>
      </div>

      {/* Intent tabs */}
      <div style={{display:'flex',gap:8,marginBottom:16,overflow:'auto'}}>
        {[
          { key:'rent', label:'To rent', icon:'home' },
          { key:'buy', label:'To buy', icon:'tag' },
          { key:'student', label:'Student rooms', icon:'user-round' },
        ].map(i => (
          <button key={i.key} onClick={() => setIntent(i.key)} style={{
            padding:'10px 18px',borderRadius:'var(--radius-pill)',cursor:'pointer',
            display:'inline-flex',alignItems:'center',gap:8,
            fontFamily:'var(--font-body)',fontWeight:600,fontSize:14,
            background: intent===i.key ? 'var(--ink-900)' : 'var(--paper)',
            color: intent===i.key ? 'white' : 'var(--ink-900)',
            border: '1.5px solid ' + (intent===i.key ? 'var(--ink-900)' : 'var(--ink-200)'),
          }}>
            <Icon name={i.icon} size={16}/> {i.label}
          </button>
        ))}
      </div>

      {/* Filters */}
      <div style={{...panelStyle,padding:16,display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:16,alignItems:'center',marginBottom:16}}>
        {(intent === 'rent' || intent === 'student') ? (
          <div>
            <label style={filterLabel}>Max monthly rent</label>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <input type="range" min={1500} max={20000} step={500} value={maxRent} onChange={e => setMaxRent(+e.target.value)}
                style={{flex:1,accentColor:'var(--brand-orange)'}}/>
              <span style={{fontFamily:'var(--font-mono)',fontWeight:700,fontSize:13,minWidth:80,textAlign:'right'}}>R {maxRent.toLocaleString('en-ZA')}</span>
            </div>
          </div>
        ) : (
          <div>
            <label style={filterLabel}>Max price</label>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <input type="range" min={300000} max={3000000} step={50000} value={maxPrice} onChange={e => setMaxPrice(+e.target.value)}
                style={{flex:1,accentColor:'var(--brand-orange)'}}/>
              <span style={{fontFamily:'var(--font-mono)',fontWeight:700,fontSize:13,minWidth:80,textAlign:'right'}}>R {(maxPrice/1000).toFixed(0)}k</span>
            </div>
          </div>
        )}
        <div>
          <label style={filterLabel}>Bedrooms</label>
          <div style={{display:'flex',gap:4}}>
            {[0,1,2,3,4].map(n => (
              <button key={n} onClick={() => setBedrooms(n)} style={{
                flex:1,padding:'8px',borderRadius:8,cursor:'pointer',border:'none',
                fontFamily:'var(--font-body)',fontWeight:700,fontSize:13,
                background: bedrooms===n ? 'var(--brand-orange)' : 'var(--ink-100)',
                color: bedrooms===n ? 'white' : 'var(--ink-700)',
              }}>{n === 0 ? 'Any' : n + '+'}</button>
            ))}
          </div>
        </div>
        <div>
          <label style={filterLabel}>Quick filters</label>
          <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
            <span style={chipStyle}>Furnished</span>
            <span style={chipStyle}>Pets ok</span>
            <span style={chipStyle}>Parking</span>
          </div>
        </div>
      </div>

      {view === 'map' && (
        <div style={{...panelStyle,padding:0,overflow:'hidden',marginBottom:16}}>
          <LeafletMap center={[-26.2041, 28.0473]} zoom={6} height={400} markers={mapMarkers}/>
        </div>
      )}

      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))',gap:16}}>
        {filtered.map(p => <PropertyCard key={p.id} property={p} onClick={() => onSelect && onSelect(p)}/>)}
      </div>
    </div>
  );
}

function PropertyCard({ property, onClick }) {
  const [hovered, setHovered] = useState(false);
  const [liked, setLiked] = useState(false);
  return (
    <article onClick={onClick}
      onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
      style={{
        background:'var(--paper)',borderRadius:'var(--radius-lg)',
        border:'1px solid var(--ink-200)',
        boxShadow: hovered ? 'var(--shadow-md)' : 'var(--shadow-sm)',
        cursor:'pointer',transition:'all .2s cubic-bezier(.2,.7,.3,1)',
        transform: hovered ? 'translateY(-3px)' : 'none',
        overflow:'hidden',position:'relative'
      }}>
      <div style={{position:'absolute',top:12,right:12,zIndex:2,display:'flex',gap:6}}>
        {property.students && (
          <span style={{background:'var(--success)',color:'white',fontSize:10,fontWeight:800,padding:'4px 8px',borderRadius:999,letterSpacing:'.04em'}}>STUDENT</span>
        )}
        {property.kind === 'sale' && (
          <span style={{background:'var(--info)',color:'white',fontSize:10,fontWeight:800,padding:'4px 8px',borderRadius:999,letterSpacing:'.04em'}}>FOR SALE</span>
        )}
        <button onClick={e => { e.stopPropagation(); setLiked(!liked); }}
          style={{width:32,height:32,borderRadius:'50%',border:'none',cursor:'pointer',
            background:'rgba(255,255,255,.92)',backdropFilter:'blur(8px)',
            display:'flex',alignItems:'center',justifyContent:'center',
            color: liked ? 'var(--danger)' : 'var(--ink-400)'}}>
          <Icon name="heart" size={14} fill={liked ? 'currentColor' : 'none'}/>
        </button>
      </div>
      <div style={{aspectRatio:'4/3',backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center',position:'relative'}}>
        <div style={{position:'absolute',bottom:8,left:8,
          background:'rgba(255,255,255,.92)',backdropFilter:'blur(8px)',
          padding:'4px 10px',borderRadius:999,fontSize:11,fontWeight:700,
          fontFamily:'var(--font-body)',color:'var(--ink-700)'}}>
          {property.type}
        </div>
      </div>
      <div style={{padding:16}}>
        <h3 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16,margin:0,lineHeight:1.25}}>{property.title}</h3>
        <div style={{fontSize:12,color:'var(--ink-500)',display:'flex',alignItems:'center',gap:4,marginTop:4}}>
          <Icon name="map-pin" size={11} stroke={2.4}/> {property.suburb}, {property.location}
        </div>
        <div style={{display:'flex',gap:12,marginTop:10,fontSize:12,color:'var(--ink-700)',fontFamily:'var(--font-body)',fontWeight:600}}>
          <span>{property.bedrooms === 0 ? 'Bachelor' : property.bedrooms + ' bed'}</span>
          <span> - </span>
          <span>{property.bathrooms} bath</span>
          <span> - </span>
          <span>{property.sqm} m2</span>
        </div>
        <div style={{marginTop:12,display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
          {property.kind === 'sale' ? (
            <Price amount={(property.price/1000).toFixed(0) + 'k'}/>
          ) : (
            <div>
              <Price amount={property.monthly}/>
              <span style={{fontSize:12,color:'var(--ink-500)',marginLeft:4}}>/mo</span>
            </div>
          )}
          <div style={{fontSize:11,color:'var(--ink-500)'}}>{property.available}</div>
        </div>
      </div>
    </article>
  );
}

/* ============================================================
   PROPERTY DETAIL PAGE
============================================================== */
function PropertyDetail({ property, onBack, onMessage }) {
  if (!property) return null;
  return (
    <div>
      <button onClick={onBack} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
        <Icon name="arrow-left" size={16}/> Back to listings
      </button>
      <div style={{display:'grid',gridTemplateColumns:'1.5fr 1fr',gap:32}}>
        <div>
          <div style={{aspectRatio:'4/3',borderRadius:'var(--radius-lg)',backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center',border:'1px solid var(--ink-200)'}}/>
          <div style={{display:'flex',gap:8,marginTop:12}}>
            {[1,2,3,4].map(i => (
              <div key={i} style={{flex:1,aspectRatio:'4/3',borderRadius:10,backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',cursor:'pointer',opacity: i === 1 ? 1 : 0.7,border: i === 1 ? '2px solid var(--brand-orange)' : '1px solid var(--ink-200)'}}/>
            ))}
          </div>

          <div style={{marginTop:24}}>
            <h2 style={{marginBottom:12}}>About this place</h2>
            <p style={{fontSize:15,lineHeight:1.6,color:'var(--ink-700)'}}>{property.description}</p>
          </div>

          <div style={{marginTop:24}}>
            <h2 style={{marginBottom:12}}>Features</h2>
            <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:8}}>
              {[
                { icon:'home', label: property.furnished ? 'Furnished' : 'Unfurnished' },
                { icon:'shield-check', label: 'Secure parking' },
                { icon: property.pets ? 'check' : 'x', label: property.pets ? 'Pets allowed' : 'No pets' },
                { icon: property.students ? 'user-round' : 'home', label: property.students ? 'Student-friendly' : 'Quiet area' },
                { icon:'wallet', label: 'Prepaid utilities' },
                { icon:'map-pin', label: property.sqm + ' m2 floor area' },
              ].map((f,i) => (
                <div key={i} style={{display:'flex',alignItems:'center',gap:10,padding:'10px 12px',background:'var(--ink-50)',borderRadius:10}}>
                  <Icon name={f.icon} size={16}/> <span style={{fontSize:13,fontWeight:600}}>{f.label}</span>
                </div>
              ))}
            </div>
          </div>

          <div style={{marginTop:24}}>
            <h2 style={{marginBottom:12}}>Location</h2>
            <div style={{...panelStyle,padding:0,overflow:'hidden'}}>
              <LeafletMap center={property.coords} zoom={14} height={280}
                markers={[{ lat: property.coords[0], lng: property.coords[1], label: property.kind === 'sale' ? 'R' : '$', color:'#F89A1F', popup: property.title }]}/>
            </div>
          </div>
        </div>

        <div>
          <div style={{...panelStyle,padding:20}}>
            <div style={{fontSize:12,color:'var(--ink-500)',fontWeight:700,letterSpacing:'.06em',textTransform:'uppercase'}}>{property.type}</div>
            <h1 style={{margin:'8px 0',fontSize:24,lineHeight:1.2}}>{property.title}</h1>
            <div style={{fontSize:13,color:'var(--ink-500)',display:'flex',alignItems:'center',gap:4,marginBottom:16}}>
              <Icon name="map-pin" size={13}/> {property.suburb}, {property.location}
            </div>

            {property.kind === 'sale' ? (
              <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:32,color:'var(--ink-900)'}}>
                R {(property.price/1000).toFixed(0)}k
                <div style={{fontSize:11,color:'var(--ink-500)',fontWeight:400,marginTop:4}}>Once-off purchase - No agent commission</div>
              </div>
            ) : (
              <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:32,color:'var(--ink-900)'}}>
                R {property.monthly.toLocaleString('en-ZA')}
                <span style={{fontSize:14,color:'var(--ink-500)',fontWeight:500}}>/month</span>
                <div style={{fontSize:11,color:'var(--ink-500)',fontWeight:400,marginTop:4}}>Deposit: R {property.deposit.toLocaleString('en-ZA')}</div>
              </div>
            )}

            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8,margin:'20px 0',padding:'12px 0',borderTop:'1px solid var(--ink-100)',borderBottom:'1px solid var(--ink-100)'}}>
              <div style={{textAlign:'center'}}>
                <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:18}}>{property.bedrooms || '-'}</div>
                <div style={{fontSize:11,color:'var(--ink-500)'}}>Bedrooms</div>
              </div>
              <div style={{textAlign:'center'}}>
                <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:18}}>{property.bathrooms}</div>
                <div style={{fontSize:11,color:'var(--ink-500)'}}>Bathrooms</div>
              </div>
              <div style={{textAlign:'center'}}>
                <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:18}}>{property.sqm}</div>
                <div style={{fontSize:11,color:'var(--ink-500)'}}>m2</div>
              </div>
            </div>

            <div style={{background:'var(--success-100)',padding:12,borderRadius:10,display:'flex',gap:8,alignItems:'start',marginBottom:16}}>
              <Icon name="shield-check" size={16}/>
              <div style={{fontSize:12,color:'var(--status-paid-fg)',fontWeight:600}}>
                Deposit held in Me2You escrow until move-in date confirmed. No fake landlord scams.
              </div>
            </div>

            <button onClick={onMessage} style={{...btnPrimary,width:'100%',justifyContent:'center',padding:'14px'}}>
              <Icon name="message-circle" size={18}/> Message {property.seller}
            </button>
            <button style={{...btnGhost,width:'100%',justifyContent:'center',padding:'12px',marginTop:8}}>
              <Icon name="phone" size={16}/> Schedule viewing
            </button>
          </div>

          <div style={{...panelStyle,marginTop:16,padding:16,display:'flex',alignItems:'center',gap:12}}>
            <div style={{width:44,height:44,borderRadius:999,background:'var(--brand-orange-100)',
              display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',
              fontWeight:700,fontSize:16,color:'var(--brand-orange-700)'}}>{property.seller.charAt(0)}</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:700,fontSize:14}}>{property.seller}</div>
              <div style={{fontSize:12,color:'var(--ink-500)'}}>Owner - Joined Feb 2026</div>
            </div>
            <button style={{...btnSmall,fontSize:12}}>View profile</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   VEHICLE BROWSE
============================================================== */
function VehicleBrowse({ onSelect }) {
  const [type, setType] = useState('all');
  const [maxPrice, setMaxPrice] = useState(300000);
  const [view, setView] = useState('grid');

  const filtered = useMemo(() => {
    let list = VEHICLES;
    if (type !== 'all') list = list.filter(v => v.kind === type);
    list = list.filter(v => v.price <= maxPrice);
    return list;
  }, [type, maxPrice]);

  const mapMarkers = filtered.map(v => ({
    lat: v.coords[0], lng: v.coords[1],
    label: v.kind === 'car' ? 'C' : (v.kind === 'bike' ? 'B' : 'S'),
    color: '#F89A1F',
    popup: `<b>${v.title}</b><br/>${v.year} - R ${v.price.toLocaleString('en-ZA')}<br/>${v.mileage.toLocaleString('en-ZA')} km`,
  }));

  return (
    <div>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:16,flexWrap:'wrap',gap:12}}>
        <div>
          <h2 style={{margin:0}}>Cars, bikes & scooters</h2>
          <p style={{color:'var(--ink-500)',fontSize:13,margin:'4px 0 0'}}>
            Informal C2C vehicle sales. {filtered.length} listings.
          </p>
        </div>
        <div style={{display:'flex',gap:2,padding:4,background:'var(--ink-100)',borderRadius:999}}>
          <button onClick={() => setView('grid')} style={viewBtn(view==='grid')}>Grid</button>
          <button onClick={() => setView('map')} style={viewBtn(view==='map')}>Map</button>
        </div>
      </div>

      <div style={{display:'flex',gap:8,marginBottom:16,overflow:'auto'}}>
        {[
          { key:'all', label:'All vehicles' },
          { key:'car', label:'Cars' },
          { key:'bike', label:'Bikes' },
          { key:'scooter', label:'Scooters' },
        ].map(t => (
          <button key={t.key} onClick={() => setType(t.key)} style={{
            padding:'10px 18px',borderRadius:'var(--radius-pill)',cursor:'pointer',
            fontFamily:'var(--font-body)',fontWeight:600,fontSize:14,
            background: type===t.key ? 'var(--ink-900)' : 'var(--paper)',
            color: type===t.key ? 'white' : 'var(--ink-900)',
            border: '1.5px solid ' + (type===t.key ? 'var(--ink-900)' : 'var(--ink-200)'),
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{...panelStyle,padding:16,marginBottom:16}}>
        <label style={filterLabel}>Max price</label>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <input type="range" min={2000} max={500000} step={5000} value={maxPrice} onChange={e => setMaxPrice(+e.target.value)}
            style={{flex:1,accentColor:'var(--brand-orange)'}}/>
          <span style={{fontFamily:'var(--font-mono)',fontWeight:700,fontSize:13,minWidth:90,textAlign:'right'}}>R {maxPrice.toLocaleString('en-ZA')}</span>
        </div>
      </div>

      {view === 'map' && (
        <div style={{...panelStyle,padding:0,overflow:'hidden',marginBottom:16}}>
          <LeafletMap center={[-26.2041, 28.0473]} zoom={6} height={400} markers={mapMarkers}/>
        </div>
      )}

      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))',gap:16}}>
        {filtered.map(v => <VehicleCard key={v.id} vehicle={v} onClick={() => onSelect && onSelect(v)}/>)}
      </div>
    </div>
  );
}

function VehicleCard({ vehicle, onClick }) {
  const [hovered, setHovered] = useState(false);
  return (
    <article onClick={onClick}
      onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
      style={{
        background:'var(--paper)',borderRadius:'var(--radius-lg)',
        border:'1px solid var(--ink-200)',
        boxShadow: hovered ? 'var(--shadow-md)' : 'var(--shadow-sm)',
        cursor:'pointer',transition:'all .2s cubic-bezier(.2,.7,.3,1)',
        transform: hovered ? 'translateY(-3px)' : 'none',
        overflow:'hidden',position:'relative'
      }}>
      <div style={{aspectRatio:'4/3',backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center',position:'relative'}}>
        <div style={{position:'absolute',top:12,left:12,
          background:'rgba(255,255,255,.92)',backdropFilter:'blur(8px)',
          padding:'4px 10px',borderRadius:999,fontSize:11,fontWeight:700,
          fontFamily:'var(--font-body)',color:'var(--ink-700)',textTransform:'uppercase',letterSpacing:'.04em'}}>
          {vehicle.year} {vehicle.kind}
        </div>
      </div>
      <div style={{padding:16}}>
        <h3 style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16,margin:0,lineHeight:1.25}}>{vehicle.title}</h3>
        <div style={{display:'flex',gap:8,marginTop:8,fontSize:12,color:'var(--ink-700)',fontFamily:'var(--font-body)',fontWeight:600,flexWrap:'wrap'}}>
          <span>{vehicle.mileage.toLocaleString('en-ZA')} km</span>
          <span> - </span>
          <span>{vehicle.fuel}</span>
          <span> - </span>
          <span>{vehicle.transmission}</span>
        </div>
        <div style={{fontSize:12,color:'var(--ink-500)',display:'flex',alignItems:'center',gap:4,marginTop:6}}>
          <Icon name="map-pin" size={11} stroke={2.4}/> {vehicle.location} - {vehicle.seller}
        </div>
        <div style={{marginTop:12,display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
          <Price amount={vehicle.price}/>
          <span style={{fontSize:11,color:'var(--ink-500)'}}>No agent commission</span>
        </div>
      </div>
    </article>
  );
}

/* --- shared mini-styles --- */
const viewBtn = (active) => ({
  padding:'6px 14px',borderRadius:999,border:'none',cursor:'pointer',
  fontFamily:'var(--font-body)',fontWeight:600,fontSize:12,
  background: active ? 'var(--paper)' : 'transparent',
  color: active ? 'var(--ink-900)' : 'var(--ink-500)',
  boxShadow: active ? 'var(--shadow-xs)' : 'none'
});
const filterLabel = {display:'block',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:600,color:'var(--ink-500)',textTransform:'uppercase',letterSpacing:'.06em',marginBottom:8};
const chipStyle = {padding:'4px 10px',borderRadius:999,background:'var(--ink-100)',fontSize:11,fontFamily:'var(--font-body)',fontWeight:600,color:'var(--ink-700)'};

/* ============================================================
   VEHICLE DETAIL
============================================================== */
function VehicleDetail({ vehicle, onBack, onMessage }) {
 if (!vehicle) return null;
 return (
 <div>
 <button onClick={onBack} style={{...btnSmall,border:'none',color:'var(--ink-500)',padding:'8px 0',marginBottom:12}}>
 <Icon name="arrow-left" size={16}/> Back to vehicles
 </button>
 <div style={{display:'grid',gridTemplateColumns:'1.5fr 1fr',gap:32}}>
 <div>
 <div style={{aspectRatio:'4/3',borderRadius:'var(--radius-lg)',backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',backgroundPosition:'center',border:'1px solid var(--ink-200)'}}/>
 <div style={{display:'flex',gap:8,marginTop:12}}>
 {[1,2,3,4,5].map(i => (
 <div key={i} style={{flex:1,aspectRatio:'4/3',borderRadius:10,backgroundImage:'url(assets/me2you.jpg)',backgroundSize:'cover',cursor:'pointer',opacity: i === 1 ? 1 : 0.6,border: i === 1 ? '2px solid var(--brand-orange)' : '1px solid var(--ink-200)'}}/>
 ))}
 </div>

 <div style={{marginTop:24}}>
 <h2 style={{marginBottom:12}}>About this {vehicle.kind}</h2>
 <p style={{fontSize:15,lineHeight:1.6,color:'var(--ink-700)'}}>{vehicle.description}</p>
 </div>

 <div style={{marginTop:24}}>
 <h2 style={{marginBottom:12}}>Specifications</h2>
 <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:12}}>
 {[
 { label:'Year', value:vehicle.year },
 { label:'Mileage', value: vehicle.mileage > 0 ? vehicle.mileage.toLocaleString('en-ZA') + ' km' : '-' },
 { label:'Fuel', value:vehicle.fuel },
 { label:'Transmission', value:vehicle.transmission },
 { label:'Type', value: vehicle.kind.charAt(0).toUpperCase() + vehicle.kind.slice(1) },
 { label:'Location', value:vehicle.location },
 ].map((s,i) => (
 <div key={i} style={{padding:'12px 14px',background:'var(--ink-50)',borderRadius:10}}>
 <div style={{fontSize:11,color:'var(--ink-500)',fontFamily:'var(--font-mono)',letterSpacing:'.06em',textTransform:'uppercase'}}>{s.label}</div>
 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:16,marginTop:2}}>{s.value}</div>
 </div>
 ))}
 </div>
 </div>

 <div style={{marginTop:24}}>
 <h2 style={{marginBottom:12}}>Location</h2>
 <div style={{...panelStyle,padding:0,overflow:'hidden'}}>
 <LeafletMap center={vehicle.coords} zoom={11} height={260}
 markers={[{ lat: vehicle.coords[0], lng: vehicle.coords[1], label:'V', color:'#F89A1F', popup: vehicle.title }]}/>
 </div>
 </div>
 </div>

 <div>
 <div style={{...panelStyle,padding:20}}>
 <div style={{fontSize:12,color:'var(--ink-500)',fontWeight:700,letterSpacing:'.06em',textTransform:'uppercase'}}>{vehicle.year} {vehicle.kind}</div>
 <h1 style={{margin:'8px 0',fontSize:24,lineHeight:1.2}}>{vehicle.title}</h1>
 <div style={{fontSize:13,color:'var(--ink-500)',display:'flex',alignItems:'center',gap:4,marginBottom:16}}>
 <Icon name="map-pin" size={13}/> {vehicle.location}
 </div>

 <div style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:32,color:'var(--ink-900)'}}>
 R {vehicle.price.toLocaleString('en-ZA')}
 <div style={{fontSize:11,color:'var(--ink-500)',fontWeight:400,marginTop:4}}>Direct seller - No agent commission</div>
 </div>

 <div style={{background:'var(--success-100)',padding:12,borderRadius:10,display:'flex',gap:8,alignItems:'start',marginTop:16,marginBottom:16}}>
 <Icon name="shield-check" size={16}/>
 <div style={{fontSize:12,color:'var(--status-paid-fg)',fontWeight:600}}>
 Deposit held in Me2You escrow until ownership transfer confirmed. NaTIS / V&L verified.
 </div>
 </div>

 <button onClick={onMessage} style={{...btnPrimary,width:'100%',justifyContent:'center',padding:'14px'}}>
 <Icon name="message-circle" size={18}/> Message {vehicle.seller}
 </button>
 <button style={{...btnGhost,width:'100%',justifyContent:'center',padding:'12px',marginTop:8}}>
 <Icon name="phone" size={16}/> Schedule test drive
 </button>
 <button style={{...btnGhost,width:'100%',justifyContent:'center',padding:'12px',marginTop:8,color:'var(--danger)',borderColor:'transparent'}}>
 <Icon name="triangle-alert" size={16}/> Report this listing
 </button>
 </div>

 <div style={{...panelStyle,marginTop:16,padding:16,display:'flex',alignItems:'center',gap:12}}>
 <div style={{width:44,height:44,borderRadius:999,background:'var(--brand-orange-100)',
 display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',
 fontWeight:700,fontSize:16,color:'var(--brand-orange-700)'}}>{vehicle.seller.charAt(0)}</div>
 <div style={{flex:1}}>
 <div style={{fontWeight:700,fontSize:14,display:'flex',alignItems:'center',gap:6}}>{vehicle.seller} <VerifiedBadge size={12}/></div>
 <div style={{fontSize:12,color:'var(--ink-500)'}}>Owner - NaTIS confirmed</div>
 </div>
 <button style={{...btnSmall,fontSize:12}}>View profile</button>
 </div>
 </div>
 </div>
 </div>
 );
}

Object.assign(window, { PropertyBrowse, PropertyDetail, VehicleBrowse, VehicleCard, VehicleDetail, PROPERTIES, VEHICLES });
