/* ============================================================
   Paella — Топ Москвы (реальные блюда: оценки гостей → отзывы → AI)
   ============================================================ */

function CollectionRail({ ctx }) {
  const P = window.PAELLA;
  const railRef = useRef(null);
  const [atStart, setAtStart] = useState(true);
  const [atEnd, setAtEnd] = useState(false);

  const update = () => {
    const el = railRef.current; if (!el) return;
    setAtStart(el.scrollLeft <= 4);
    setAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - 4);
  };
  useEffect(() => { update(); }, []);
  const scrollBy = (dir) => {
    const el = railRef.current; if (!el) return;
    const amount = dir * Math.min(560, el.clientWidth * 0.85);
    const start = el.scrollLeft;
    const target = Math.max(0, Math.min(el.scrollWidth - el.clientWidth, start + amount));
    const t0 = performance.now(), dur = 380;
    const ease = (t) => 1 - Math.pow(1 - t, 3);
    const tick = (now) => {
      const p = Math.min(1, (now - t0) / dur);
      el.scrollLeft = start + (target - start) * ease(p);
      update();
      if (p < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  };

  return (
    <div className="railwrap">
      <button className={"rail-arrow prev" + (atStart ? " hide" : "")} onClick={() => scrollBy(-1)} aria-label="Назад"><Icon name="chevronLeft" size={20} /></button>
      <button className={"rail-arrow next" + (atEnd ? " hide" : "")} onClick={() => scrollBy(1)} aria-label="Вперёд"><Icon name="chevronRight" size={20} /></button>
      <div className="rail" ref={railRef} onScroll={update}>
        {P.COLLECTIONS.map((c, i) => {
          const cover = P.byId(c.ids[0]) || P.dishes[0];
          return (
            <div className="coll" key={i} onClick={() => ctx.openCollection(c)}>
              <DishPhoto src={cover.photo} alt={cover.name} size="lg" />
              <div className="coll-grad" style={{ zIndex: 2 }}></div>
              <div className="coll-body" style={{ zIndex: 3 }}>
                <span className="badge" style={{ background: "rgba(255,255,255,.85)", color: "var(--ink)", marginBottom: 8 }}>{c.ids.length} блюд</span>
                <h4>{c.title}</h4>
                <p>{c.sub}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* честная подпись «почему в топе» по типу сигнала */
function topCaption(d) {
  if (d.ratingPct != null) return `Оценка гостей: ${d.ratingPct}%${d.ratingCount ? ` · ${d.ratingCount} оценок` : ""} · Яндекс.Еда`;
  if (d.reviewMentions >= 3) return d.reviewSnippet ? `«${d.reviewSnippet}»` : `Хвалят в отзывах · ${d.reviewPosPct}% положительных`;
  return `Прогноз Paella ~${d.score} · ${d.cuisine}`;
}

function TopScreen({ ctx }) {
  const P = window.PAELLA;
  const [tcat, setTcat] = useState("all");

  let list = P.dishes.slice();
  if (tcat === "cheap") list = list.filter((d) => d.price && d.price <= 700);
  else if (tcat === "guest") list = list.filter((d) => d.ratingPct != null);
  else if (tcat !== "all") list = list.filter((d) => d.category === tcat);
  list = list.sort((a, b) => b.q - a.q).slice(0, tcat === "all" ? 100 : 30);

  return (
    <div className="fadein wrap">
      <div className="pintro">
        <span className="eyebrow"><Icon name="trophy" size={13} style={{ verticalAlign: "-2px", marginRight: 4 }} />Топ Москвы</span>
        <h1>Топ блюд Москвы</h1>
        <p>Рейтинг конкретных блюд, а не ресторанов — по единой шкале Paella Score 0–100. Реальные оценки гостей (Яндекс.Еда) и отзывы (2ГИС) весят больше всего; где их пока нет — балл помечен как прогноз «~».</p>
      </div>

      {/* collections */}
      <section className="sec" style={{ marginTop: 26 }}>
        <div className="sec-head"><div><h2 className="sec-title">Подборки Paella</h2><p className="sec-sub">Готовые коллекции реальных блюд под повод и настроение</p></div></div>
        <CollectionRail ctx={ctx} />
      </section>

      {/* category tabs */}
      <section className="sec">
        <div className="chips" style={{ marginBottom: 18 }}>
          {P.TOP_CATS.map((c) => (
            <button key={c.key} className={"chip" + (tcat === c.key ? " on" : "")} onClick={() => setTcat(c.key)}>{c.label}</button>
          ))}
        </div>

        <div className="rank">
          {list.map((d, i) => (
            <div key={d.id} className={"rankrow" + (i === 0 ? " top1" : i < 3 ? " top" + (i + 1) : "")} onClick={() => ctx.openDish(d)}>
              <div className="rank-pos">{i + 1}</div>
              <div className="rank-img" style={{ position: "relative", background: "var(--bg-2)" }}><DishPhoto src={d.photo} alt={d.name} /></div>
              <div className="rank-main">
                <div className="rank-name">{d.name}</div>
                <div className="rank-sub">{d.restaurantName} · {d.district}{d.price ? ` · ${d.price} ₽` : ""}</div>
                <div className="rank-reason">{topCaption(d)}</div>
              </div>
              <div className="rank-right">
                <ScoreTag u={uOf(d)} />
                <span className="muted" style={{ fontSize: 12, fontWeight: 600 }}>{scoreCaption(uOf(d))}</span>
              </div>
            </div>
          ))}
        </div>
      </section>

      <div className="note" style={{ marginTop: 24 }}>
        Данные собраны из открытых источников: 2ГИС (рейтинги и отзывы), Яндекс.Карты и Яндекс.Еда (меню, фото, цены и оценки гостей). Фото — только реальные.
      </div>
    </div>
  );
}

/* ---------- Collection detail (full view) ---------- */
function CollectionScreen({ collection, ctx }) {
  const P = window.PAELLA;
  useEffect(() => { window.scrollTo({ top: 0 }); }, []);
  const dishes = collection.ids.map((id) => P.byId(id)).filter(Boolean);
  return (
    <div className="fadein wrap">
      <div className="pintro">
        <button className="btn btn-soft btn-sm" style={{ marginBottom: 14 }} onClick={() => ctx.go("top")}>
          <Icon name="arrowRight" size={16} style={{ transform: "rotate(180deg)" }} />Топ Москвы
        </button>
        <span className="eyebrow">Подборка · {dishes.length} блюд</span>
        <h1>{collection.title}</h1>
        <p>{collection.sub}</p>
      </div>
      <div className="dgrid" style={{ marginTop: 22 }}>
        {dishes.map((d) => <DishCard key={d.id} dish={d} saved={ctx.saved.has(d.id)} onSave={ctx.toggleSave} onOpen={ctx.openDish} />)}
      </div>
    </div>
  );
}

Object.assign(window, { TopScreen, CollectionScreen, CollectionRail });
