// «Наше кафе» — фиксированное меню еды по городам.
// Идея: в каждом городе на ярмарке будет своя кухня — здесь можно заранее
// посмотреть меню города и оформить предзаказ блюд.

const MenuRow = ({ product, onOpen, onAdd }) => (
  <div className="flex items-center gap-3 sm:gap-4 py-3.5 sm:py-4 border-b border-paper-100 last:border-b-0">
    <button onClick={() => onOpen(product)} className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl overflow-hidden shrink-0">
      <ProductVisual product={product} />
    </button>
    <button onClick={() => onOpen(product)} className="flex-1 min-w-0 text-left">
      <div className="font-display font-semibold text-ink-900 text-[15px] sm:text-base leading-snug truncate">{product.title}</div>
      <div className="text-[12px] sm:text-sm text-ink-500 mt-0.5 leading-snug line-clamp-2 hidden sm:block">{product.desc}</div>
      {product.seller ? <div className="text-[11px] text-ink-400 mt-1.5">Готовит: {product.seller}</div> : null}
    </button>
    <div className="text-right shrink-0 flex flex-col items-end gap-1.5">
      <div className="font-display font-bold text-ink-900 text-base sm:text-lg tabular-nums">{fmtPrice(product.price)}</div>
      <button
        onClick={() => onAdd(product)}
        className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full bg-brand-500 text-white text-xs font-semibold hover:bg-brand-600 active:scale-95 transition shadow-soft"
      >
        <Icon name="plus" size={13} /> В заявку
      </button>
    </div>
  </div>
);

const Cafe = ({ navigate, onOpenProduct }) => {
  const { city: globalCity, setCity, addToCart } = useStore();
  const [city, setLocalCity] = useState(globalCity);

  const cityObj = city ? window.DATA.cityById(city) : null;

  // Меню города — все товары категории «food» в этом городе
  const menu = useMemo(() => {
    if (!city) return [];
    return window.DATA.PRODUCTS.filter((p) => p.city === city && p.category === 'food');
  }, [city]);

  const handlePick = (id) => setLocalCity(id);

  const goToCatalog = () => {
    if (city) setCity(city);
    navigate({ name: 'catalog', filters: { category: 'food' } });
  };

  return (
    <div className="max-w-3xl mx-auto px-4 md:px-8 py-6 sm:py-8 md:py-12">

      {/* Hero */}
      <div className="text-center mb-7 sm:mb-10">
        <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-brand-50 border border-brand-100 mb-3">
          <span className="text-base">🍜</span>
          <span className="text-[11px] font-semibold text-brand-700 tracking-wide uppercase">На ярмарке</span>
        </div>
        <h1 className="font-display font-bold text-2xl sm:text-3xl md:text-4xl text-ink-900 tracking-tight mb-2">
          Наше кафе
        </h1>
        <p className="text-ink-500 text-sm sm:text-base max-w-lg mx-auto leading-relaxed">
          В каждом городе — своё меню. Выберите город и посмотрите, что будет на столах — можно сразу оформить предзаказ.
        </p>
      </div>

      {/* City picker */}
      <div className="flex gap-2 overflow-x-auto no-scrollbar pb-1 -mx-4 px-4 sm:mx-0 sm:px-0 sm:flex-wrap sm:justify-center mb-7 sm:mb-9">
        {window.DATA.CITIES.map((c) => (
          <button
            key={c.id}
            onClick={() => handlePick(c.id)}
            className={`shrink-0 inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-sm font-medium border transition active:scale-95 ${
              city === c.id
                ? 'bg-ink-900 text-white border-ink-900'
                : 'bg-white text-ink-700 border-paper-200 hover:border-ink-300'
            }`}
          >
            <span className="text-base leading-none">{c.emoji}</span> {c.name}
          </button>
        ))}
      </div>

      {/* Content */}
      {!city ? (
        <EmptyState
          icon="search"
          title="Выберите город"
          subtitle="Покажем фиксированное меню кафе этого города на ярмарке"
        />
      ) : menu.length === 0 ? (
        <EmptyState
          icon="search"
          title="Меню ещё не готово"
          subtitle={`В ${cityObj?.name || 'этом городе'} меню кафе пока не объявили — загляните позже`}
        />
      ) : (
        <>
          <article className="bg-white rounded-2xl border border-paper-200 overflow-hidden">
            <div
              className="px-4 sm:px-6 py-4 sm:py-5 flex items-center gap-3"
              style={{ background: cityObj?.theme?.tint || '#FFF4EC' }}
            >
              <div
                className="w-11 h-11 sm:w-12 sm:h-12 rounded-2xl bg-white/70 flex items-center justify-center text-xl sm:text-2xl shrink-0"
              >
                🍴
              </div>
              <div className="min-w-0">
                <div className="font-display font-semibold text-base sm:text-lg text-ink-900 leading-tight">
                  Меню кафе · {cityObj?.name}
                </div>
                <p className="text-[12px] sm:text-sm text-ink-600 mt-0.5 leading-snug">{menu.length} {menu.length === 1 ? 'позиция' : 'позиций'} в меню</p>
              </div>
            </div>
            <div className="px-4 sm:px-6">
              {menu.map((d) => (
                <MenuRow key={d.id} product={d} onOpen={onOpenProduct} onAdd={(p) => addToCart(p.id, 1)} />
              ))}
            </div>
          </article>

          <div className="mt-7 sm:mt-9 bg-brand-50 border border-brand-100 rounded-2xl p-4 sm:p-5 flex flex-col sm:flex-row items-center gap-3 sm:gap-4 text-center sm:text-left">
            <div className="flex-1">
              <div className="font-display font-semibold text-ink-900">Хочется попробовать заранее?</div>
              <div className="text-sm text-ink-600 mt-0.5">Можно оформить предзаказ — как и на любой другой товар ярмарки.</div>
            </div>
            <button onClick={goToCatalog} className="btn-primary shrink-0 inline-flex items-center gap-2 whitespace-nowrap">
              Вся еда города <Icon name="arrowRight" size={16} />
            </button>
          </div>
        </>
      )}
    </div>
  );
};

window.Cafe = Cafe;
