/* ============================================================
   Paella — «Паспорт мест»: посещённые рестораны + отзывы.
   Карта с флажками + список. Отзывы переносятся сюда автоматически.
   ============================================================ */

const RATE_EMOJI = { fire: "🔥", ok: "🙂", no: "👎" };
const RATE_LABEL = { fire: "Огонь", ok: "Норм", no: "Не зашло" };
const PASS_CUISINE_EMOJI = { "Ресторан": "🍽️", "Бар": "🍷", "Суши": "🍣", "Пицца": "🍕", "Кофе": "☕", "Кафе": "🥐", "Десерты": "🍰", "Завтраки": "🍳", "Бизнес-ланч": "🍱" };
function fmtDate(ts) {
  if (!ts) return "";
  try { return new Date(ts).toLocaleDateString("ru-RU", { day: "numeric", month: "long" }); } catch (e) { return ""; }
}

/* ---------- карта посещённых мест (флажки) ---------- */
function PassportMap({ places, onOpen }) {
  const elRef = useRef(null);
  useEffect(() => {
    if (!window.L || !elRef.current) return;
    const dark = document.documentElement.getAttribute("data-theme") === "dark";
    const map = L.map(elRef.current, { zoomControl: true, scrollWheelZoom: false, attributionControl: true });
    map.attributionControl.setPrefix("");
    const tiles = dark
      ? "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
      : "https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png";
    L.tileLayer(tiles, { maxZoom: 19, subdomains: "abcd", attribution: "© OpenStreetMap, © CARTO" }).addTo(map);
    const pts = [];
    places.forEach((p) => {
      if (p.lat == null || p.lng == null) return;
      const icon = L.divIcon({ className: "flagpin-wrap", html: `<div class="flagpin">🚩</div>`, iconSize: [30, 30], iconAnchor: [6, 28] });
      const m = L.marker([p.lat, p.lng], { icon, riseOnHover: true }).addTo(map);
      m.bindPopup(`<b>${p.name}</b><br>${p.cuisine || ""} · ${p.district || ""}`);
      m.on("click", () => onOpen && onOpen(p.id));
      pts.push([p.lat, p.lng]);
    });
    if (pts.length) map.fitBounds(pts, { padding: [50, 50], maxZoom: 15 });
    else map.setView([55.76, 37.62], 12);
    setTimeout(() => map.invalidateSize(), 60);
    return () => map.remove();
  }, [places.length]);
  return (
    <div className="map-wrap" style={{ height: 460 }}>
      <div ref={elRef} className="map-leaflet" style={{ height: "100%" }}></div>
      <div className="map-legend"><div className="li"><span style={{ fontSize: 15 }}>🚩</span> ваши места · нажмите на флажок</div></div>
    </div>
  );
}

/* ---------- карточка посещённого места ---------- */
function PassportCard({ place, onOpen, onRemove }) {
  const emoji = PASS_CUISINE_EMOJI[place.cuisine] || "🍽️";
  return (
    <article className="rcard" style={{ cursor: "default" }}>
      <div className="rcard-cover" onClick={() => onOpen(place.id)} style={{ cursor: "pointer" }}>
        <SmartImage src={place.imageUrl} emoji={emoji} grad={["oklch(0.6 0.1 130)", "oklch(0.45 0.09 120)"]} alt={place.name} />
        <span className="badge b-olive" style={{ position: "absolute", left: 12, top: 12, zIndex: 3 }}>🚩 посещено</span>
        {place.rating != null && <span className="score float"><Icon name="star" size={13} fill="currentColor" sw={0} style={{ color: "var(--gold)" }} />{Number(place.rating).toFixed(1)}</span>}
      </div>
      <div className="rcard-body">
        <div className="rcard-name">{place.name}</div>
        <div className="rcard-meta">
          <span>{place.cuisine}</span><span className="dot" style={{ width: 3, height: 3, borderRadius: 9, background: "var(--ink-3)" }}></span>
          <span>{place.district}</span>
          <span className="dot" style={{ width: 3, height: 3, borderRadius: 9, background: "var(--ink-3)" }}></span>
          <span>{fmtDate(place.visitedAt)}</span>
        </div>
        {place.reviews && place.reviews.length > 0 ? (
          <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 7 }}>
            {place.reviews.slice(0, 3).map((r, i) => (
              <div key={i} style={{ display: "flex", gap: 8, alignItems: "flex-start", fontSize: 12.5 }}>
                <span style={{ flex: "none", fontSize: 15 }}>{RATE_EMOJI[r.rating] || "🍽️"}</span>
                <div style={{ minWidth: 0 }}>
                  <span style={{ fontWeight: 700 }}>{r.dish}</span>
                  {r.text ? <span style={{ color: "var(--ink-2)" }}> — {r.text}</span> : <span style={{ color: "var(--ink-3)" }}> — {RATE_LABEL[r.rating]}</span>}
                </div>
              </div>
            ))}
            {place.reviews.length > 3 && <div className="muted" style={{ fontSize: 12 }}>и ещё {place.reviews.length - 3} {plural(place.reviews.length - 3, "отзыв", "отзыва", "отзывов")}</div>}
          </div>
        ) : (
          <div className="muted" style={{ fontSize: 12.5, marginTop: 10 }}>Отметка о посещении · отзывов пока нет</div>
        )}
        <div style={{ marginTop: 13, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
          <button className="sec-link" style={{ fontWeight: 700 }} onClick={() => onOpen(place.id)}>Открыть ресторан <Icon name="arrowRight" size={15} /></button>
          <button className="muted" style={{ fontSize: 12.5, fontWeight: 600 }} onClick={() => onRemove(place.id)}>Убрать</button>
        </div>
      </div>
    </article>
  );
}

function PassportScreen({ ctx }) {
  const V = useVisited();
  const P = window.PAELLA;
  const [view, setView] = useState("list"); // list | map
  const places = V.list();
  const reviewCount = V.reviewCount();
  const districts = new Set(places.map((p) => p.district)).size;
  const cuisineFreq = {};
  places.forEach((p) => { cuisineFreq[p.cuisine] = (cuisineFreq[p.cuisine] || 0) + 1; });
  const topCuisine = Object.keys(cuisineFreq).sort((a, b) => cuisineFreq[b] - cuisineFreq[a])[0] || "—";

  const openRest = (id) => { const r = P.restById(id); if (r) ctx.openRest(r); };
  const share = () => {
    const txt = `Мой Паспорт Paella: ${places.length} ${plural(places.length, "место", "места", "мест")}, ${reviewCount} ${plural(reviewCount, "отзыв", "отзыва", "отзывов")} в ${districts} ${plural(districts, "районе", "районах", "районах")} Москвы 🚩`;
    try { navigator.clipboard && navigator.clipboard.writeText(txt); } catch (e) {}
    ctx.toast("Скопировано — поделитесь с друзьями!");
  };

  const STATS = [
    [places.length, "мест посещено"],
    [reviewCount, "отзывов о блюдах"],
    [districts, "районов Москвы"],
    [topCuisine, "любимая кухня"],
  ];

  return (
    <div className="fadein wrap">
      <div className="pintro">
        <span className="eyebrow"><Icon name="flag" size={13} style={{ verticalAlign: "-2px", marginRight: 4 }} />Паспорт мест</span>
        <h1>Где вы уже побывали</h1>
        <p>Отмечайте рестораны и кафе, где были, ставьте флажки на карте Москвы и сохраняйте впечатления о блюдах. Ваши оценки автоматически попадают сюда — собирайте свою личную гастрокарту города и делитесь с друзьями.</p>
      </div>

      {places.length === 0 ? (
        <div style={{ marginTop: 10 }}>
          <EmptyState emoji="🚩" title="Паспорт пока пуст" text="Откройте любой ресторан и нажмите «Я здесь был», а в карточке блюда поставьте оценку — место и отзыв появятся здесь." />
          <div className="row" style={{ justifyContent: "center", marginTop: 14 }}>
            <button className="btn btn-pri" onClick={() => ctx.go("restaurants")}><Icon name="grid" size={18} />Выбрать ресторан</button>
          </div>
        </div>
      ) : (
        <>
          <div className="stat-grid" style={{ marginTop: 4, marginBottom: 18 }}>
            {STATS.map((s, i) => <div className="stat" key={i}><div className="v" style={{ fontSize: typeof s[0] === "string" ? 19 : undefined }}>{s[0]}</div><div className="l">{s[1]}</div></div>)}
          </div>

          <div className="row" style={{ justifyContent: "space-between", flexWrap: "wrap", gap: 10, marginBottom: 18 }}>
            <div className="viewtoggle">
              <button className={view === "list" ? "on" : ""} onClick={() => setView("list")}><Icon name="grid" size={15} />Список</button>
              <button className={view === "map" ? "on" : ""} onClick={() => setView("map")}><Icon name="pin" size={15} />Карта</button>
            </div>
            <button className="btn btn-soft btn-sm" onClick={share}><Icon name="share" size={15} />Поделиться</button>
          </div>

          {view === "map" ? (
            <PassportMap places={places} onOpen={openRest} />
          ) : (
            <div className="rgrid">
              {places.map((p) => <PassportCard key={p.id} place={p} onOpen={openRest} onRemove={(id) => V.remove(id)} />)}
            </div>
          )}
        </>
      )}
    </div>
  );
}

Object.assign(window, { PassportScreen });
