// CeyRide — Shared UI Components

// ── FX rate constant — update this when the rate changes significantly ──
const CR_USD_RATE = 320; // LKR per 1 USD (approx)

// Vehicle image — uses real photo if available, striped placeholder otherwise
function VehiclePlaceholder({ type = "Car", color = "#E84800", width = "100%", height = 180, imageUrl, style: extraStyle }) {
  if (imageUrl) {
    return (
      <div style={{ width, height, overflow: 'hidden', borderRadius: 12, background: '#f0ede8', ...extraStyle }}>
        <img
          src={imageUrl}
          alt={type}
          loading="lazy"
          style={{ width: '100%', height: '100%', objectFit: 'contain', objectPosition: 'center', display: 'block', transition: 'transform 0.4s ease' }}
          onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.04)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
          onError={e => { e.currentTarget.style.display = 'none'; }}
        />
      </div>
    );
  }
  const icons = {
    "Car": "🚗", "Van": "🚐", "SUV": "🚙", "Luxury": "🚘",
    "Bus": "🚌", "Three-Wheeler": "🛺", "Tuk": "🛺", "Mini Bus": "🚌",
    "Wedding Hire": "💍", "Lorry / Truck": "🚛"
  };
  const icon = icons[type] || "🚗";
  return (
    <div style={{
      width, height, background: `repeating-linear-gradient(45deg, ${color}11 0px, ${color}11 10px, transparent 10px, transparent 20px)`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      borderRadius: 12, border: `1px solid ${color}22`, position: 'relative', overflow: 'hidden', ...extraStyle
    }}>
      <span style={{ fontSize: 48, marginBottom: 8 }}>{icon}</span>
      <span style={{ fontFamily: 'monospace', fontSize: 11, color: '#969696', letterSpacing: '0.05em' }}>{type} photo</span>
    </div>
  );
}

// Star rating
function Stars({ rating, size = 14 }) {
  return (
    <span style={{ color: '#E84800', fontSize: size, letterSpacing: 1 }}>
      {'★'.repeat(Math.floor(rating))}{'☆'.repeat(5 - Math.floor(rating))}
    </span>
  );
}

// Badge chip
function Badge({ label, color = '#E84800', bg }) {
  return (
    <span style={{
      display: 'inline-block', padding: '3px 10px',
      borderRadius: 999, fontSize: 11, fontWeight: 600,
      background: bg || `${color}18`, color: color,
      letterSpacing: '0.02em'
    }}>{label}</span>
  );
}

// Vehicle Card
function VehicleCard({ v, setPage, setSelectedVehicle }) {
  const [hovered, setHovered] = React.useState(false);

  // ── Resolve capability flags — prefer new fields, fall back to legacy ──
  const hasOwnerDriver = !!(v.has_owner_driver ?? v.hasOwnerDriver ?? v.withDriver ?? false);
  const hasSelfDrive   = !!(v.has_self_drive   ?? v.hasSelfDrive   ?? v.selfDrive  ?? true);

  // ── From price — lowest applicable rate ──────────────────────────────
  const selfDrivePrice  = (v.self_drive_price  || v.selfDrivePrice)  > 0 ? (v.self_drive_price  || v.selfDrivePrice)  : null;
  const ownerDrvPrice   = (v.owner_driver_price || v.ownerDriverPrice) > 0 ? (v.owner_driver_price || v.ownerDriverPrice) : null;
  const basePrice       = v.pricePerDay || v.price_per_day || 0;
  const prices          = [selfDrivePrice || basePrice, ownerDrvPrice || basePrice].filter(Boolean);
  const fromPrice       = prices.length ? Math.min(...prices) : basePrice;
  const showFromLabel   = !!(selfDrivePrice || ownerDrvPrice);

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        background: '#fff', borderRadius: 20,
        overflow: 'hidden', cursor: 'pointer',
        boxShadow: hovered ? '0 12px 40px rgba(20,20,19,0.12)' : '0 2px 12px rgba(20,20,19,0.06)',
        transition: 'all 0.25s ease',
        transform: hovered ? 'translateY(-4px)' : 'translateY(0)'
      }}>
      {/* Image */}
      <div style={{ position: 'relative', overflow: 'hidden' }}>
        <VehiclePlaceholder type={v.type} height={180} imageUrl={v.imageUrl} />
        <div style={{
          position: 'absolute', top: 12, left: 12,
          display: 'flex', gap: 6, flexWrap: 'wrap'
        }}>
          <Badge label={v.type} />
          {/* Issue #9 fix — spec-correct badge labels driven by new capability flags */}
          {hasOwnerDriver && <Badge label="👨‍✈️ Driver Included" color="#059669" />}
          {hasSelfDrive   && <Badge label="🚗 Self Drive" color="#2563EB" />}
        </div>
      </div>
      {/* Content */}
      <div style={{ padding: '16px 18px 18px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 16, color: '#141413', letterSpacing: '-0.3px' }}>
              {v.brand} {v.model}
            </div>
            <div style={{ fontSize: 12, color: '#696969', marginTop: 2 }}>
              {v.seats} seats · {v.location}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontWeight: 800, fontSize: 18, color: '#E84800', letterSpacing: '-0.5px' }}>
              {showFromLabel && <span style={{ fontSize: 12, fontWeight: 500, color: '#969696' }}>from </span>}
              Rs. {fromPrice.toLocaleString()}
            </div>
            <div style={{ fontSize: 11, color: '#969696' }}>≈ USD {Math.round(fromPrice / CR_USD_RATE)}/day</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 14 }}>
          <Stars rating={v.rating} />
          <span style={{ fontSize: 12, color: '#696969' }}>{v.rating} ({v.reviews} reviews)</span>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button
            onClick={() => { setSelectedVehicle(v); setPage('detail'); }}
            style={{
              flex: 1, background: 'transparent', border: '1.5px solid #141413',
              borderRadius: 12, padding: '8px 0', fontWeight: 500, fontSize: 13,
              cursor: 'pointer', color: '#141413', transition: 'all 0.2s'
            }}>View Details</button>
          {/* Issue #2 fix — route through mode selector, never directly to booking */}
          <button
            onClick={() => {
              // Auth gate — guests must log in before entering the booking flow
              let session = null;
              try { session = JSON.parse(localStorage.getItem('cr_session')); } catch(e) {}
              if (!session) {
                localStorage.setItem('cr_auth_message', 'Please create an account or log in to book a vehicle.');
                localStorage.setItem('cr_return_page', 'vehicles');
                setPage('login');
                return;
              }
              setSelectedVehicle(v);
              setPage('self-drive-choice');
            }}
            style={{
              flex: 1, background: '#E84800', border: 'none',
              borderRadius: 12, padding: '8px 0', fontWeight: 700, fontSize: 13,
              cursor: 'pointer', color: '#fff', display: 'flex', alignItems: 'center',
              justifyContent: 'center', gap: 6, transition: 'all 0.2s'
            }}>
            Reserve Now
          </button>
        </div>
      </div>
    </div>
  );
}

// Section title component
function SectionTitle({ eyebrow, title, subtitle, center = false }) {
  return (
    <div style={{ marginBottom: 48, textAlign: center ? 'center' : 'left' }}>
      {eyebrow && (
        <div style={{
          fontSize: 12, fontWeight: 700, letterSpacing: '0.08em',
          textTransform: 'uppercase', color: '#E84800',
          marginBottom: 12, display: 'flex', alignItems: 'center',
          justifyContent: center ? 'center' : 'flex-start', gap: 6
        }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#E84800', display: 'inline-block' }} />
          {eyebrow}
        </div>
      )}
      <h2 style={{
        fontSize: 'clamp(28px, 4vw, 42px)', fontWeight: 700, color: '#141413',
        letterSpacing: '-0.03em', margin: 0, marginBottom: subtitle ? 16 : 0,
        lineHeight: 1.15
      }}>{title}</h2>
      {subtitle && (
        <p style={{ fontSize: 16, color: '#696969', lineHeight: 1.6, maxWidth: center ? 540 : '100%', margin: center ? '0 auto' : 0 }}>
          {subtitle}
        </p>
      )}
    </div>
  );
}

Object.assign(window, { VehiclePlaceholder, Stars, Badge, VehicleCard, SectionTitle });
