/* ============================================================
   Paella — App shell, routing, global state
   ============================================================ */

const LS_SAVED = "paella_saved_v1";

function useSaved() {
  const [saved, setSaved] = useState(() => {
    try { return new Set(JSON.parse(localStorage.getItem(LS_SAVED) || "[]")); } catch (e) { return new Set(); }
  });
  useEffect(() => {
    try { localStorage.setItem(LS_SAVED, JSON.stringify([...saved])); } catch (e) {}
  }, [saved]);
  const toggle = (id) => setSaved((prev) => {
    const n = new Set(prev);
    n.has(id) ? n.delete(id) : n.add(id);
    return n;
  });
  return [saved, toggle];
}

function Toast({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ position: "fixed", left: "50%", bottom: 104, transform: "translateX(-50%)", zIndex: 120,
      background: "var(--ink)", color: "var(--bg)", padding: "12px 20px", borderRadius: 999, fontWeight: 700, fontSize: 14,
      boxShadow: "var(--sh-lg)", animation: "fadein .25s ease", display: "flex", alignItems: "center", gap: 8 }}>
      <Icon name="check" size={17} />{msg}
    </div>
  );
}

const TOP_NAV = [
  ["home", "Блюда рядом"], ["ai", "AI-подбор"], ["restaurants", "Рестораны"], ["top", "Топ Москвы"], ["passport", "Мои места"], ["methodology", "Методика"], ["about", "О себе"], ["profile", "Профиль"],
];
const BOTTOM_NAV = [
  ["home", "Рядом", "home"], ["restaurants", "Рестораны", "grid"], ["ai", "AI", "sparkles"], ["passport", "Места", "flag"], ["profile", "Профиль", "user"],
];

function App() {
  const P = window.PAELLA;
  const [section, setSection] = useState("home");
  const [restId, setRestId] = useState(null);
  const [collection, setCollection] = useState(null);
  const [dish, setDish] = useState(null);
  const [saved, toggleSave] = useSaved();
  const [contributions, setContributions] = useState([]);
  const [toastMsg, setToastMsg] = useState("");
  const toastTimer = useRef(null);
  const [theme, setTheme] = useState(() => {
    try { return localStorage.getItem("paella_theme") || "light"; } catch (e) { return "light"; }
  });
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("paella_theme", theme); } catch (e) {}
  }, [theme]);
  const toggleTheme = () => {
    document.documentElement.classList.add("theme-anim");
    setTheme((t) => (t === "dark" ? "light" : "dark"));
    requestAnimationFrame(() => requestAnimationFrame(() => document.documentElement.classList.remove("theme-anim")));
  };

  const toast = (m) => {
    setToastMsg(m);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToastMsg(""), 2200);
  };

  const go = (s) => {
    setRestId(null); setCollection(null); setSection(s);
    paellaScrollTo(0);
  };
  const openRest = (rest) => { setCollection(null); setRestId(rest.id); window.scrollTo({ top: 0 }); };
  const closeRest = () => { setRestId(null); window.scrollTo({ top: 0 }); };
  const openCollection = (c) => { setCollection(c); };
  const openDish = (d) => setDish(d);
  const addContribution = (data) => { setContributions((p) => [...p, data]); toast("Отзыв опубликован"); };
  const reviewsFor = () => [];

  const ctx = { go, openRest, closeRest, openCollection, openDish, saved, toggleSave, contributions, addContribution, reviewsFor, toast };

  // body view
  let body;
  if (restId) body = <RealRestaurantDetail rest={P.restById(restId)} onBack={closeRest} />;
  else if (collection) body = <CollectionScreen collection={collection} ctx={ctx} />;
  else if (section === "home") body = <HomeScreen ctx={ctx} />;
  else if (section === "restaurants") body = <RestaurantsScreen ctx={ctx} />;
  else if (section === "top") body = <TopScreen ctx={ctx} />;
  else if (section === "ai") body = <AIScreen ctx={ctx} />;
  else if (section === "add") body = <AddScreen ctx={ctx} />;
  else if (section === "passport") body = <PassportScreen ctx={ctx} />;
  else if (section === "methodology") body = <MethodologyScreen ctx={ctx} />;
  else if (section === "about") body = <AboutScreen ctx={ctx} />;
  else if (section === "profile") body = <ProfileScreen ctx={ctx} />;

  const activeTop = restId ? "restaurants" : collection ? "top" : section;
  const activeBottom = restId ? "restaurants" : collection ? "top" : section;

  return (
    <div className="app">
      {/* header */}
      <header className="hdr">
        <div className="wrap hdr-row">
          <button className="logo" onClick={() => go("home")} aria-label="Paella — на главную">
            <img className="logo-img" src="assets/logo-mark.png" alt="" />
            <span className="logo-word">Pae<b>lla</b></span>
          </button>
          <span className="mvp-pill" title="Реальные данные ресторанов Москвы">● Реальные данные</span>
          <div className="hdr-actions">
            <nav className="hdr-nav">
              {TOP_NAV.map(([k, label]) => (
                <button key={k} className={activeTop === k ? "on" : ""} onClick={() => go(k)}>{label}</button>
              ))}
            </nav>
            <button className="theme-btn" onClick={toggleTheme} aria-label="Сменить тему" title={theme === "dark" ? "Светлая тема" : "Тёмная тема"}>
              <Icon name={theme === "dark" ? "sun" : "moon"} size={18} />
            </button>
            <button className="hdr-fav" onClick={() => go("profile")}>
              <Icon name="bookmark" size={16} fill={saved.size ? "var(--coral)" : "none"} style={{ color: saved.size ? "var(--coral)" : "var(--ink-2)" }} />
              <span className="cnt">{saved.size}</span>
            </button>
          </div>
        </div>
      </header>

      {/* page */}
      <main style={{ paddingTop: 6 }}>{body}</main>

      {/* footer */}
      <footer className="foot">
        <div className="wrap">
          <div className="foot-grid">
            <div style={{ maxWidth: 340 }}>
              <div className="logo" style={{ marginBottom: 12 }}>
                <img className="logo-img" src="assets/logo-mark.png" alt="" />
                <span className="logo-word">Pae<b>lla</b></span>
              </div>
              <p className="serif-i" style={{ fontSize: 20, color: "var(--ink)", margin: "0 0 10px", lineHeight: 1.3 }}>«Поиск блюд, а не ресторанов. А ты поел?»</p>
              <small>Paella · реальные блюда ресторанов Москвы.<br />Автор проекта: Ольга Витальевна Орлова.</small>
            </div>
            <div style={{ display: "flex", gap: 48, flexWrap: "wrap" }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 800, marginBottom: 12, letterSpacing: ".02em" }}>Разделы</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                  {TOP_NAV.map(([k, label]) => <button key={k} onClick={() => go(k)} style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 600, textAlign: "left" }}>{label}</button>)}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 800, marginBottom: 12, letterSpacing: ".02em" }}>Ещё</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                  <button onClick={() => go("add")} style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 600, textAlign: "left" }}>Добавить блюдо</button>
                  <button onClick={() => go("profile")} style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 600, textAlign: "left" }}>Профиль</button>
                </div>
              </div>
            </div>
          </div>
          <div className="divider" style={{ margin: "26px 0 16px" }}></div>
          <small style={{ display: "block" }}>Данные о ресторанах, меню, фото, ценах, оценках гостей и отзывах собраны из открытых источников: 2ГИС, Яндекс.Карты и Яндекс.Еда. Все фото — реальные; если фото блюда нет — показываем логотип Paella с подписью «нет фото». © 2026 Paella.</small>
        </div>
      </footer>

      {/* bottom nav (mobile) */}
      <nav className="bnav">
        {BOTTOM_NAV.map(([k, label, icon]) => k === "ai" ? (
          <button key={k} className={"add" + (activeBottom === k ? " on" : "")} onClick={() => go(k)}>
            <span className="ic-wrap"><Icon name="sparkles" size={23} /></span>
            <span>{label}</span>
          </button>
        ) : (
          <button key={k} className={activeBottom === k ? "on" : ""} onClick={() => go(k)}>
            <span className="ic"><Icon name={icon} size={22} /></span>
            <span>{label}</span>
          </button>
        ))}
      </nav>

      {/* FAB — добавить блюдо */}
      {section !== "add" && (
        <button className="fab" onClick={() => go("add")} aria-label="Добавить блюдо">
          <Icon name="plus" size={22} /><span className="lab">Добавить блюдо</span>
        </button>
      )}

      {/* dish detail (реальные данные) */}
      {dish && <RealDishDetail dish={dish} rest={dish._rest} onClose={() => setDish(null)} onOpenRest={openRest} />}

      {/* toast */}
      <Toast msg={toastMsg} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
