/* ============== Minassa Cars — UI primitives ============== */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- price / number formatting (fr) ---------- */
const fmt = (n) => new Intl.NumberFormat('fr-FR').format(Math.round(n));
const MRU = (n) => `${fmt(n)} MRU`;

/* ---------- icon set (lucide-style strokes) ---------- */
function Icon({ name, size = 18, fill = 'none', sw = 1.8, style }) {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill, stroke: 'currentColor',
    strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round', style };
  const I = {
    search: <><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></>,
    heart: <path d="M19 14c1.5-1.5 3-3.3 3-5.5A4.5 4.5 0 0 0 12 5 4.5 4.5 0 0 0 2 8.5c0 2.2 1.5 4 3 5.5l7 7Z"/>,
    star: <path d="m12 2 2.9 6.3 6.8.7-5 4.6 1.4 6.7L12 17.8 5.9 20.3 7.3 13.6l-5-4.6 6.8-.7z"/>,
    location: <><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/></>,
    fuel: <><path d="M3 22V5a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v17"/><path d="M3 12h10"/><path d="M13 8h3l3 3v6a2 2 0 0 1-4 0v-5"/></>,
    gear: <><path d="M6 4v16M6 9h6a3 3 0 0 0 3-3V4M18 4v6"/><circle cx="6" cy="4" r="1.6"/><circle cx="18" cy="4" r="1.6"/><circle cx="6" cy="20" r="1.6"/><circle cx="18" cy="11" r="1.6"/></>,
    road: <><path d="M4 22 7 2M20 22 17 2M12 4v3M12 11v3M12 18v2"/></>,
    calendar: <><rect x="3" y="4" width="18" height="18" rx="3"/><path d="M3 9h18M8 2v4M16 2v4"/></>,
    clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    chevron: <path d="m9 6 6 6-6 6"/>,
    chevronDown: <path d="m6 9 6 6 6-6"/>,
    arrowRight: <><path d="M5 12h14"/><path d="m13 6 6 6-6 6"/></>,
    sliders: <><path d="M4 6h10M18 6h2M4 12h2M10 12h10M4 18h7M15 18h5"/><circle cx="16" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="13" cy="18" r="2"/></>,
    grid: <><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></>,
    car: <><path d="M5 17h14M5 17a2 2 0 1 1-4 0M23 17a2 2 0 1 1-4 0M3 17v-4l2.5-5.5A2 2 0 0 1 7.3 6h9.4a2 2 0 0 1 1.8 1.5L21 13v4M3 13h18"/></>,
    gavel: <><path d="m14 13-7.8 7.8a2 2 0 0 1-2.8-2.8L11.2 10"/><path d="m16 16 6-6M8 8l6-6M9 7l8 8M3 21h9"/></>,
    key: <><circle cx="7.5" cy="15.5" r="4.5"/><path d="m10.5 12.5 8-8M16 4l3 3M19 7l2-2"/></>,
    flame: <path d="M12 22c4 0 7-2.8 7-6.5 0-2.4-1.5-4.3-2.5-5.5-.3 1.5-1.5 2-2 2 0-2-1-5-4-7 .5 3-2 5-3 6.3C9.7 13 8 14 8 16c0 3.7 0 6 4 6Z"/>,
    bolt: <path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z"/>,
    user: <><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></>,
    home: <><path d="M3 11.5 12 4l9 7.5"/><path d="M5 10v10h14V10"/></>,
    phone: <path d="M5 3h4l2 5-3 2a12 12 0 0 0 6 6l2-3 5 2v4a2 2 0 0 1-2 2A17 17 0 0 1 3 5a2 2 0 0 1 2-2Z"/>,
    check: <path d="m4 12 5 5L20 6"/>,
    upload: <><path d="M12 16V4M7 9l5-5 5 5"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/></>,
    shield: <><path d="M12 3 5 6v5c0 5 3 8 7 10 4-2 7-5 7-10V6l-7-3Z"/><path d="m9 12 2 2 4-4"/></>,
    menu: <path d="M3 6h18M3 12h18M3 18h18"/>,
    x: <path d="M6 6 18 18M18 6 6 18"/>,
    plus: <path d="M12 5v14M5 12h14"/>,
    minus: <path d="M5 12h14"/>,
    eye: <><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></>,
    play: <path d="M7 4v16l13-8z" fill="currentColor" stroke="none"/>,
    seat: <><path d="M5 4h4a2 2 0 0 1 2 2v6H7a2 2 0 0 1-2-2V4Z"/><path d="M5 12v4a3 3 0 0 0 3 3h9M19 19v-3"/></>,
    sort: <><path d="M7 4v16M3 8l4-4 4 4M17 20V4M13 16l4 4 4-4"/></>,
    verified: <><path d="m9 12 2 2 4-4"/><path d="M12 2 4 6v6c0 5 8 10 8 10s8-5 8-10V6l-8-4Z"/></>,
  };
  return <svg {...p}>{I[name] || null}</svg>;
}

/* ---------- car photo with graceful fallback ---------- */
function CarPhoto({ src, alt, label = 'صورة سيارة' }) {
  const [err, setErr] = useState(false);
  return (
    <div className="photo" style={{ width: '100%', height: '100%' }}>
      {!err
        ? <img src={src} alt={alt} loading="lazy" onError={() => setErr(true)} />
        : <div className="photo-ph">{label}</div>}
    </div>
  );
}

/* ---------- vendor tier chip ---------- */
const TIER_LABEL = { bronze: 'برونز', silver: 'فضي', gold: 'ذهبي', premium: 'بريميوم' };
function VendorBadge({ tier, label }) {
  return (
    <span className={`vendor ${tier}`}>
      <span className="gem" />
      {label || TIER_LABEL[tier]}
    </span>
  );
}

function Rating({ value }) {
  return <span className="rating"><Icon name="star" size={14} fill="currentColor" sw={0} /> {value.toFixed(1)}</span>;
}

/* ---------- spec chips ---------- */
function Specs({ car, items }) {
  const all = {
    year: ['calendar', car.year],
    km: ['road', car.km != null ? `${fmt(car.km)} km` : null],
    fuel: ['fuel', car.fuel],
    gearbox: ['gear', car.gearbox],
    body: ['car', car.body],
    seats: ['seat', car.seats ? `${car.seats} places` : null],
    city: ['location', car.city],
  };
  const keys = items || ['year', 'km', 'fuel', 'gearbox'];
  return (
    <div className="specrow">
      {keys.map(k => all[k] && all[k][1] != null && (
        <span className="spec" key={k}><Icon name={all[k][0]} size={14} /> {all[k][1]}</span>
      ))}
    </div>
  );
}

/* ---------- favorite heart ---------- */
function Heart({ id }) {
  const [on, setOn] = useState(false);
  return (
    <button className={`heart ${on ? 'on' : ''}`} aria-label="المفضلة"
      onClick={(e) => { e.stopPropagation(); setOn(v => !v); }}>
      <Icon name="heart" size={18} fill={on ? 'currentColor' : 'none'} />
    </button>
  );
}

/* ---------- countdown timer (live) ---------- */
function useCountdown(endsAt) {
  const [left, setLeft] = useState(Math.max(0, endsAt - Date.now()));
  useEffect(() => {
    const t = setInterval(() => setLeft(Math.max(0, endsAt - Date.now())), 1000);
    return () => clearInterval(t);
  }, [endsAt]);
  const s = Math.floor(left / 1000);
  return {
    ms: left,
    d: Math.floor(s / 86400),
    h: Math.floor((s % 86400) / 3600),
    m: Math.floor((s % 3600) / 60),
    s: s % 60,
    ended: left <= 0,
    urgent: left > 0 && left < 10 * 60 * 1000,
  };
}
const pad = (n) => String(n).padStart(2, '0');

function Countdown({ endsAt, compact }) {
  const c = useCountdown(endsAt);
  if (c.ended) return <span className="pill pill-red">انتهت</span>;
  const segs = [];
  if (c.d > 0) segs.push([c.d, 'ي']);
  segs.push([pad(c.h), 'س'], [pad(c.m), 'د']);
  if (c.d === 0) segs.push([pad(c.s), 'ث']);
  if (compact) {
    return (
      <span className={`tnum ${c.urgent ? 'cd-urgent' : ''}`} style={{ fontWeight: 700, fontSize: 13.5, color: c.urgent ? 'var(--red)' : 'var(--ink)' }}>
        {c.d > 0 ? `${c.d}j ` : ''}{pad(c.h)}:{pad(c.m)}{c.d === 0 ? `:${pad(c.s)}` : ''}
      </span>
    );
  }
  return (
    <div className="cd-blocks" style={{ display: 'flex', gap: 8 }}>
      {segs.map(([v, u], i) => (
        <div key={i} className={`cd-block ${c.urgent ? 'urgent' : ''}`}>
          <div className="cd-val tnum">{v}</div>
          <div className="cd-unit">{u}</div>
        </div>
      ))}
    </div>
  );
}

/* ============================================================
   CAR CARD — three variants:
   variant 'standard' | 'overlay' | 'horizontal'
   ============================================================ */
function CarCard({ car, variant = 'standard', onOpen, priceMode = 'sale' }) {
  const priceEl = priceMode === 'rent'
    ? <><span className="card-price">{MRU(car.daily)}</span><span className="card-price-unit"> / يوم</span></>
    : <span className="card-price">{MRU(car.price)}</span>;

  const open = () => onOpen && onOpen(car);

  if (variant === 'horizontal') {
    return (
      <div className={`carcard horiz ${car.sponsored ? 'sponsored' : ''}`} onClick={open}>
        <div className="carcard-img horiz-img">
          <CarPhoto src={car.photo} alt={`${car.brand} ${car.model}`} />
          <div className="heart-pos"><Heart id={car.id} /></div>
        </div>
        <div className="carcard-body">
          <div className="carcard-head">
            <div>
              <div className="carcard-title">{car.brand} {car.model}</div>
              <div className="carcard-sub">{car.year} · {car.city}</div>
            </div>
            {car.sponsored && <span className="badge-sponsor">Sponsorisé</span>}
          </div>
          <Specs car={car} items={['km', 'fuel', 'gearbox', 'body']} />
          <div className="carcard-foot">
            <div className="price-wrap">{priceEl}</div>
            <VendorBadge tier={car.vendor.tier} />
          </div>
        </div>
      </div>
    );
  }

  if (variant === 'overlay') {
    return (
      <div className="carcard overlay" onClick={open}>
        <div className="carcard-img overlay-img">
          <CarPhoto src={car.photo} alt={`${car.brand} ${car.model}`} />
          <div className="overlay-grad" />
          <div className="overlay-top">
            {car.sponsored && <span className="badge-sponsor">ممول</span>}
            <Heart id={car.id} />
          </div>
          <div className="overlay-bot">
            <div className="carcard-title light">{car.brand} {car.model}</div>
            <div className="overlay-specs">{car.year} · {fmt(car.km)} km · {car.fuel}</div>
            <div className="overlay-price">{priceEl}</div>
          </div>
        </div>
      </div>
    );
  }

  /* standard */
  return (
    <div className={`carcard ${car.sponsored ? 'sponsored' : ''}`} onClick={open}>
      <div className="carcard-img">
        <CarPhoto src={car.photo} alt={`${car.brand} ${car.model}`} />
        <div className="carcard-tags">
          {car.sponsored && <span className="badge-sponsor">ممول</span>}
          {!car.sponsored && car.featured && <span className="pill pill-blue">مميز</span>}
        </div>
        <div className="heart-pos"><Heart id={car.id} /></div>
      </div>
      <div className="carcard-body">
        <div className="carcard-head">
          <div>
            <div className="carcard-title">{car.brand} {car.model}</div>
            <div className="carcard-sub">{car.year} · {car.city}</div>
          </div>
        </div>
        <Specs car={car} items={priceMode === 'rent' ? ['fuel', 'gearbox', 'seats'] : ['km', 'fuel', 'gearbox']} />
        <div className="carcard-foot">
          <div className="price-wrap">{priceEl}</div>
          <VendorBadge tier={car.vendor.tier} />
        </div>
      </div>
    </div>
  );
}

/* ---------- empty state ---------- */
function EmptyState({ title, sub, action, onAction }) {
  return (
    <div className="empty">
      <div className="empty-ico"><Icon name="search" size={26} /></div>
      <div className="empty-title">{title}</div>
      {sub && <div className="empty-sub">{sub}</div>}
      {action && <button className="btn btn-ghost btn-sm" onClick={onAction}>{action}</button>}
    </div>
  );
}

/* ---------- skeleton loading card ---------- */
function SkeletonCard() {
  return (
    <div className="carcard">
      <div className="sk sk-img" />
      <div className="carcard-body">
        <div className="sk sk-line" style={{ width: '70%' }} />
        <div className="sk sk-line" style={{ width: '40%', marginTop: 8 }} />
        <div className="sk sk-line" style={{ width: '90%', marginTop: 16, height: 12 }} />
        <div className="sk sk-line" style={{ width: '55%', marginTop: 18, height: 22 }} />
      </div>
    </div>
  );
}

Object.assign(window, {
  Icon, CarPhoto, VendorBadge, Rating, Specs, Heart,
  Countdown, useCountdown, CarCard, EmptyState, SkeletonCard,
  fmt, MRU, pad, TIER_LABEL,
});
