// src/App.jsx
const { useState, useEffect, createContext, useContext, useCallback } = React;

// ── Global context ────────────────────────────────────────
const AppContext = createContext({});
function useApp() { return useContext(AppContext); }

function App() {
  const [page, setPage]             = useState('home');
  const [articleData, setArticle]   = useState(null);
  const [articleSlug, setArticleSlug] = useState(null);
  const [historyArticleData, setHistoryArticle] = useState(null);
  const [historyArticleSlug, setHistoryArticleSlug] = useState(null);
  const [lang, setLang]             = useState('ru');
  const [theme, setTheme]           = useState('dark');
  const [activeSection, setSection] = useState('hero');
  const [news, setNews]             = useState([]);
  const [newsLoading, setNewsLoading] = useState(true);
  const [newsError, setNewsError]   = useState(null);
  const [newsSource, setNewsSource] = useState(null);
  const [stories, setStories]       = useState([]);
  const [storiesLoading, setStoriesLoading] = useState(true);
  const [storiesError, setStoriesError] = useState(null);
  const [storiesSource, setStoriesSource] = useState(null);

  useEffect(() => {
    const root = document.documentElement;
    if (theme === 'light') root.classList.add('light');
    else root.classList.remove('light');
  }, [theme]);

  const loadNews = useCallback(async () => {
    setNewsLoading(true);
    const { articles, source, error } = await fetchNews();
    setNews(articles);
    setNewsSource(source);
    setNewsError(source === 'error' ? error : null);
    setNewsLoading(false);
  }, []);

  const loadStories = useCallback(async () => {
    setStoriesLoading(true);
    const { stories: items, source, error } = await fetchStories();
    setStories(items);
    setStoriesSource(source);
    setStoriesError(source === 'error' ? error : null);
    setStoriesLoading(false);
  }, []);

  useEffect(() => {
    loadNews();
    loadStories();
  }, [loadNews, loadStories]);

  function clearArticles() {
    setArticle(null);
    setArticleSlug(null);
    setHistoryArticle(null);
    setHistoryArticleSlug(null);
  }

  function applyRoute(pathname) {
    const route = parseRoute(pathname);
    setPage(route.page);
    if (route.page === 'article') {
      setArticleSlug(route.slug);
      setHistoryArticleSlug(null);
      setHistoryArticle(null);
    } else if (route.page === 'history-article') {
      setHistoryArticleSlug(route.slug);
      setArticleSlug(null);
      setArticle(null);
    } else {
      clearArticles();
    }
    if (route.page === 'home') setSection('hero');
  }

  useEffect(() => {
    if ('scrollRestoration' in history) {
      history.scrollRestoration = 'manual';
    }
    applyRoute(window.location.pathname);
    function onPopState() {
      applyRoute(window.location.pathname);
    }
    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, []);

  useEffect(() => {
    window.scrollTo(0, 0);
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
  }, [page, articleSlug, historyArticleSlug]);

  useEffect(() => {
    if (page !== 'article' || !articleSlug || newsLoading) return;
    if (news.length && !findArticleBySlug(news, articleSlug)) {
      setPage('not-found');
      clearArticles();
    }
  }, [page, articleSlug, news, newsLoading]);

  useEffect(() => {
    if (page !== 'history-article' || !historyArticleSlug || storiesLoading) return;
    if (stories.length && !findStoryBySlug(stories, historyArticleSlug)) {
      setPage('not-found');
      clearArticles();
    }
  }, [page, historyArticleSlug, stories, storiesLoading]);

  useEffect(() => {
    if (page !== 'article' || !articleSlug || !news.length) return;
    const found = findArticleBySlug(news, articleSlug);
    if (found) setArticle(found);
  }, [page, articleSlug, news]);

  useEffect(() => {
    if (page !== 'history-article' || !historyArticleSlug || !stories.length) return;
    const found = findStoryBySlug(stories, historyArticleSlug);
    if (found) setHistoryArticle(found);
  }, [page, historyArticleSlug, stories]);

  useEffect(() => {
    const needsRetry = (source) => source === 'fallback' || source === 'error';
    if (!needsRetry(newsSource) && !needsRetry(storiesSource)) return undefined;

    let tries = 0;
    const timer = setInterval(() => {
      tries += 1;
      if (tries > 10) {
        clearInterval(timer);
        return;
      }
      if (needsRetry(newsSource)) loadNews();
      if (needsRetry(storiesSource)) loadStories();
    }, 3000);

    return () => clearInterval(timer);
  }, [newsSource, storiesSource, loadNews, loadStories]);

  useEffect(() => {
    function onFocus() {
      if (newsSource === 'fallback' || newsSource === 'error') loadNews();
      if (storiesSource === 'fallback' || storiesSource === 'error') loadStories();
    }
    window.addEventListener('focus', onFocus);
    return () => window.removeEventListener('focus', onFocus);
  }, [newsSource, storiesSource, loadNews, loadStories]);

  function navigate(p, data) {
    setPage(p);

    if (p === 'article') {
      const item = data && typeof data === 'object' ? data : null;
      const slug = item
        ? getArticleSlug(item, lang)
        : (typeof data === 'string' ? data : articleSlug);

      if (item) setArticle(item);
      setHistoryArticle(null);
      setHistoryArticleSlug(null);
      if (slug) {
        setArticleSlug(slug);
        history.pushState({}, '', routeToPath('article', slug));
      }
    } else if (p === 'history-article') {
      const item = data && typeof data === 'object' ? data : null;
      const slug = item
        ? getStorySlug(item, lang)
        : (typeof data === 'string' ? data : historyArticleSlug);

      if (item) setHistoryArticle(item);
      setArticle(null);
      setArticleSlug(null);
      if (slug) {
        setHistoryArticleSlug(slug);
        history.pushState({}, '', routeToPath('history-article', slug));
      }
    } else if (p === 'news') {
      clearArticles();
      history.pushState({}, '', '/news');
      loadNews();
    } else if (p === 'history') {
      clearArticles();
      history.pushState({}, '', '/history');
      loadStories();
    } else if (p === 'home') {
      clearArticles();
      setSection('hero');
      history.pushState({}, '', '/');
    }

    window.scrollTo(0, 0);
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
  }

  function scrollToSection(sectionId) {
    if (page !== 'home' || window.location.pathname !== '/') {
      history.pushState({}, '', '/');
      setPage('home');
      clearArticles();
    }
    setSection(sectionId);
    window.__navScrollLock = true;
    setTimeout(() => {
      const el = document.getElementById(sectionId);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);

    clearTimeout(window.__navScrollUnlockTimer);
    window.__navScrollUnlockTimer = setTimeout(() => {
      window.__navScrollLock = false;
    }, 750);
  }

  const toggleTheme = () => setTheme(t => t === 'dark' ? 'light' : 'dark');

  const toggleLang = () => {
    setLang((prev) => {
      const next = prev === 'ru' ? 'en' : 'ru';
      if (page === 'article' && articleData) {
        const slug = getArticleSlug(articleData, next);
        if (slug) {
          setArticleSlug(slug);
          history.replaceState({}, '', routeToPath('article', slug));
        }
      }
      if (page === 'history-article' && historyArticleData) {
        const slug = getStorySlug(historyArticleData, next);
        if (slug) {
          setHistoryArticleSlug(slug);
          history.replaceState({}, '', routeToPath('history-article', slug));
        }
      }
      return next;
    });
  };

  const t = I18N[lang];

  return (
    <AppContext.Provider value={{
      lang, theme, toggleTheme, toggleLang, t,
      navigate, scrollToSection, page,
      activeSection, setSection,
      news, newsLoading, newsError, newsSource, loadNews,
      stories, storiesLoading, storiesError, storiesSource, loadStories,
      articleSlug, historyArticleSlug,
    }}>
      <div
        className="site-shell"
        style={{ minHeight: '100vh', background: 'var(--bg)', color: 'var(--text)' }}
      >
        <Nav />
        <main className="site-main">
          {page === 'home'             && <HomePage />}
          {page === 'news'             && <NewsPage />}
          {page === 'history'          && <HistoryPage />}
          {page === 'article'          && <ArticlePage item={articleData} />}
          {page === 'history-article'  && <HistoryArticlePage item={historyArticleData} />}
          {page === 'not-found'        && <NotFoundPage />}
        </main>
        <Footer />
      </div>
    </AppContext.Provider>
  );
}

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