// Results page — list with map.

function Results({ lang, search, setSearch, go, theme, results, loading, apiError }) {
  const t = COPY[lang];
  const [sort, setSort] = React.useState("distance");
  const [typeFilter, setTypeFilter] = React.useState({ indoor: true, outdoor: true, valet: true });
  const [svcFilter, setSvcFilter] = React.useState({ shuttle: false, valet: false, ev: false, wash: false });
  const [hoverId, setHoverId] = React.useState(null);

  const days = React.useMemo(() => {
    const a = new Date(search.from), b = new Date(search.to);
    return Math.max(1, Math.round((b - a) / (1000 * 60 * 60 * 24)));
  }, [search.from, search.to]);

  const filtered = React.useMemo(() => {
    let list = results.filter(p => p.airport === search.airport);
    list = list.filter(p => typeFilter[p.type]);
    const activeSvc = Object.entries(svcFilter).filter(([_, v]) => v).map(([k]) => k);
    if (activeSvc.length) list = list.filter(p => activeSvc.every(s => p.services.includes(s)));
    // enrich with dynamic pricing
    list = list.map(p => ({ ...p, pricing: computePricing(p, search, days) }));
    switch (sort) {
      case "price": list = [...list].sort((a, b) => a.pricing.perDay - b.pricing.perDay); break;
      case "distance": list = [...list].sort((a, b) => a.distanceKm - b.distanceKm); break;
      case "rating": list = [...list].sort((a, b) => b.rating - a.rating); break;
      default: list = [...list].sort((a, b) => (b.recommended ? 1 : 0) - (a.recommended ? 1 : 0));
    }
    return list;
  }, [results, search, days, sort, typeFilter, svcFilter]);

  return (
    <div style={{ background: theme.subtle, minHeight: "100%" }}>
      {/* sticky search summary bar */}
      <div style={{ background: theme.bg, borderBottom: "1px solid " + theme.border, padding: "16px 56px", position: "sticky", top: 74, zIndex: 5 }}>
        <SearchForm search={search} setSearch={setSearch} onSubmit={() => {}} lang={lang} theme={theme} compact/>
      </div>

      <div style={{ padding: "24px 56px", display: "grid", gridTemplateColumns: "260px 1fr 380px", gap: 24, alignItems: "start" }}>
        {/* FILTERS */}
        <aside style={{
          background: theme.bg, border: "1px solid " + theme.border, borderRadius: 14, padding: 20,
          position: "sticky", top: 180,
        }}>
          <div style={{ fontFamily: theme.fontDisplay, fontSize: 16, fontWeight: 700, color: theme.ink, marginBottom: 16 }}>
            {t.filters}
          </div>
          <FilterGroup title={t.filterType} theme={theme}>
            {["indoor", "outdoor", "valet"].map(k => (
              <CheckRow key={k} checked={typeFilter[k]} onChange={() => setTypeFilter({ ...typeFilter, [k]: !typeFilter[k] })}
                label={{ indoor: t.typeIndoor, outdoor: t.typeOutdoor, valet: t.typeValet }[k]} theme={theme}/>
            ))}
          </FilterGroup>
          <FilterGroup title={t.filterServices} theme={theme}>
            {["shuttle", "valet", "ev", "wash"].map(k => (
              <CheckRow key={k} checked={svcFilter[k]} onChange={() => setSvcFilter({ ...svcFilter, [k]: !svcFilter[k] })}
                label={SERVICE_LABELS[lang][k]} theme={theme} iconName={k}/>
            ))}
          </FilterGroup>
        </aside>

        {/* LIST */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
            <div>
              <div style={{ fontFamily: theme.fontDisplay, fontSize: 22, fontWeight: 700, color: theme.ink, letterSpacing: -0.5 }}>
                {loading ? (lang === "fr" ? "Recherche…" : "Searching…") : `${filtered.length} ${t.resultsTitle}`}
              </div>
              <div style={{ fontSize: 13, color: theme.inkMuted, marginTop: 2 }}>
                {search.airport === "CDG" ? "Paris-Charles de Gaulle" : "Paris-Orly"} · {days} {t.days}
                {apiError && <span style={{ marginLeft: 8, color: "oklch(0.55 0.15 30)" }}>· {lang === "fr" ? "données de démo" : "demo data"}</span>}
              </div>
            </div>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: theme.inkMuted }}>
              {t.sort}:
              <select value={sort} onChange={(e) => setSort(e.target.value)} style={{
                border: "1px solid " + theme.border, borderRadius: 8, padding: "6px 10px",
                fontFamily: "inherit", fontSize: 13, background: theme.bg,
              }}>
                <option value="recommended">{t.sortOptions[0]}</option>
                <option value="price">{t.sortOptions[1]}</option>
                <option value="distance">{t.sortOptions[2]}</option>
                <option value="rating">{t.sortOptions[3]}</option>
              </select>
            </label>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {loading
              ? Array.from({ length: 3 }).map((_, i) => <SkeletonCard key={i} theme={theme}/>)
              : filtered.map((p, i) => (
                  <ResultCard key={p.id} parking={p} seed={i + 20} lang={lang} days={days} theme={theme}
                    onHover={() => setHoverId(p.id)} onLeave={() => setHoverId(null)}
                    onClick={() => go("detail", p.id)}/>
                ))}
          </div>
        </div>

        {/* MAP */}
        <MapCard lang={lang} theme={theme} parkings={filtered} airport={search.airport} hoverId={hoverId} setHoverId={setHoverId} onSelect={(id) => go("detail", id)}/>
      </div>
      <Footer lang={lang} theme={theme}/>
    </div>
  );
}

function FilterGroup({ title, children, theme }) {
  return (
    <div style={{ marginBottom: 18, paddingBottom: 18, borderBottom: "1px solid " + theme.border }}>
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.6, color: theme.inkMuted, marginBottom: 10 }}>{title}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>{children}</div>
    </div>
  );
}

function CheckRow({ checked, onChange, label, iconName, theme }) {
  return (
    <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", fontSize: 14, color: theme.ink }}>
      <span onClick={onChange} style={{
        width: 18, height: 18, borderRadius: 5, border: "1.5px solid " + (checked ? theme.primary : theme.border),
        background: checked ? theme.primary : theme.bg,
        display: "flex", alignItems: "center", justifyContent: "center",
        transition: "all .15s ease",
      }}>
        {checked && <Icon name="check" size={12} color="#fff" stroke={2.5}/>}
      </span>
      {iconName && <Icon name={iconName} size={14} color={theme.inkMuted}/>}
      <span onClick={onChange}>{label}</span>
    </label>
  );
}

function SkeletonCard({ theme }) {
  return (
    <div style={{ height: 170, background: theme.bg, border: "1px solid " + theme.border, borderRadius: 14,
      backgroundImage: `linear-gradient(90deg, ${theme.bg} 0%, ${theme.subtle} 50%, ${theme.bg} 100%)`,
      backgroundSize: "200% 100%", animation: "shimmer 1.4s infinite linear" }}/>
  );
}

function ResultCard({ parking, seed, lang, days, theme, onHover, onLeave, onClick }) {
  const pricing = parking.pricing || computePricing(parking, null, days);
  const total = pricing.total;
  const occPct = Math.round(pricing.occupancy * 100);
  const isPeak = pricing.season >= 1.2;
  const isHot = pricing.occupancy >= 0.85;
  return (
    <div onMouseEnter={onHover} onMouseLeave={onLeave}
      style={{ background: theme.bg, border: "1px solid " + theme.border, borderRadius: 14, overflow: "hidden",
        display: "grid", gridTemplateColumns: "220px 1fr auto", gap: 0,
        transition: "box-shadow .2s, transform .2s",
        boxShadow: "0 1px 3px rgba(10,20,40,0.04)",
      }}
      onMouseOver={e => e.currentTarget.style.boxShadow = "0 8px 24px rgba(10,30,60,0.1)"}
      onMouseOut={e => e.currentTarget.style.boxShadow = "0 1px 3px rgba(10,20,40,0.04)"}
    >
      <div style={{ position: "relative", padding: 12 }}>
        <PlaceholderImage seed={seed} label={parking.typeLabel[lang].toLowerCase()} height={146} rounded={10}/>
      </div>
      <div style={{ padding: "18px 18px 18px 6px", display: "flex", flexDirection: "column", gap: 6 }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {parking.badges.map(b => <BadgeFor key={b} kind={b} lang={lang}/>)}
        </div>
        <div style={{ fontFamily: theme.fontDisplay, fontSize: 18, fontWeight: 600, color: theme.ink, marginTop: 4 }}>{parking.name}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: theme.inkMuted }}>
          <span style={{ display: "flex", alignItems: "center", gap: 4 }}><Icon name="pin" size={13}/>{parking.distanceKm} km</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span style={{ display: "flex", alignItems: "center", gap: 4 }}><Icon name="shuttle" size={13}/>{parking.shuttleMin === 0 ? (lang === "fr" ? "Sur place" : "On site") : `${parking.shuttleMin} min`}</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>{parking.typeLabel[lang]}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: "auto" }}>
          <Stars value={parking.rating}/>
          <span style={{ fontSize: 12, color: theme.inkMuted }}><b style={{ color: theme.ink }}>{parking.rating}</b> · {parking.reviews.toLocaleString(lang)} {COPY[lang].reviewsCount}</span>
        </div>
      </div>
      <div style={{
        padding: 18, borderLeft: "1px solid " + theme.border,
        display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-end", gap: 8, minWidth: 180,
      }}>
        <div style={{ fontSize: 11, color: theme.inkMuted, textTransform: "uppercase", letterSpacing: 0.6, fontWeight: 600 }}>
          {days} {COPY[lang].days}
        </div>
        <div style={{ fontFamily: theme.fontDisplay, fontSize: 28, fontWeight: 700, color: theme.ink, letterSpacing: -0.5, lineHeight: 1 }}>
          €{total.toFixed(2)}
        </div>
        <div style={{ fontSize: 12, color: theme.inkMuted }}>€{pricing.perDay.toFixed(2)} {COPY[lang].perDay}</div>
        {(isPeak || isHot) && (
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            fontSize: 10, fontWeight: 600, color: "oklch(0.5 0.16 30)",
            background: "oklch(0.97 0.03 40)", padding: "3px 7px", borderRadius: 6,
            whiteSpace: "nowrap",
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 3, background: "oklch(0.62 0.18 30)" }}/>
            {isPeak ? seasonLabel(pricing.month, lang) : occupancyLabel(pricing.occupancy, lang)}
          </div>
        )}
        <div style={{ fontSize: 10, color: theme.inkMuted }}>{occPct}% {lang === "fr" ? "occupé" : "full"}</div>
        <button onClick={onClick} style={{
          background: theme.primary, color: "#fff", border: "none", borderRadius: 10,
          padding: "10px 18px", fontSize: 14, fontWeight: 600, cursor: "pointer", marginTop: 6,
          display: "flex", alignItems: "center", gap: 6,
        }}>
          {COPY[lang].book} <Icon name="arrow" size={14}/>
        </button>
      </div>
    </div>
  );
}

// Stylized map (not a real map) — gridded paper with pins
function MapCard({ lang, theme, parkings, airport, hoverId, setHoverId, onSelect }) {
  return (
    <aside style={{ position: "sticky", top: 180, background: theme.bg, border: "1px solid " + theme.border, borderRadius: 14, overflow: "hidden" }}>
      <div style={{ position: "relative", height: 460, background: "oklch(0.95 0.015 220)" }}>
        {/* grid */}
        <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }} viewBox="0 0 100 100" preserveAspectRatio="none">
          <defs>
            <pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse">
              <path d="M 10 0 L 0 0 0 10" fill="none" stroke="oklch(0.88 0.02 220)" strokeWidth="0.2"/>
            </pattern>
          </defs>
          <rect width="100" height="100" fill="url(#grid)"/>
          {/* river/road swoop */}
          <path d="M-5 60 C 30 40, 70 70, 105 35" stroke="oklch(0.83 0.04 220)" strokeWidth="1.6" fill="none"/>
          <path d="M-5 85 C 40 65, 60 80, 105 55" stroke="oklch(0.82 0.05 140)" strokeWidth="0.6" fill="none" strokeDasharray="1 1.4"/>
        </svg>
        {/* airport marker */}
        <div style={{
          position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)",
          display: "flex", alignItems: "center", gap: 6,
          background: theme.ink, color: theme.bg,
          padding: "5px 10px", borderRadius: 999, fontSize: 11, fontWeight: 700,
          boxShadow: "0 6px 16px rgba(0,0,0,0.15)",
        }}>
          <Icon name="plane" size={12}/> {airport}
        </div>
        {/* parking pins */}
        {parkings.map((p, i) => {
          const active = hoverId === p.id;
          return (
            <button key={p.id}
              onMouseEnter={() => setHoverId(p.id)} onMouseLeave={() => setHoverId(null)}
              onClick={() => onSelect(p.id)}
              style={{
                position: "absolute", left: `${p.coords.x}%`, top: `${p.coords.y}%`,
                transform: "translate(-50%, -100%)",
                border: "none", background: active ? theme.ink : theme.primary, color: "#fff",
                borderRadius: 12, padding: "5px 9px", fontSize: 11, fontWeight: 700,
                cursor: "pointer",
                boxShadow: active ? "0 10px 24px rgba(0,0,0,0.25)" : "0 4px 10px rgba(0,0,0,0.15)",
                transition: "all .15s ease",
                zIndex: active ? 3 : 2,
              }}>
              €{(p.pricing ? p.pricing.perDay : p.pricePerDay).toFixed(0)}
            </button>
          );
        })}
      </div>
      <div style={{ padding: "12px 14px", fontSize: 11, color: theme.inkMuted, display: "flex", alignItems: "center", gap: 6 }}>
        <Icon name="pin" size={12}/> {lang === "fr" ? "Carte indicative" : "Indicative map"} — {parkings.length} {COPY[lang].resultsTitle}
      </div>
    </aside>
  );
}

Object.assign(window, { Results });
