// 영어문법학습 — 메인 앱 (라우팅 + 상태 관리)

const { useEffect, useState, useCallback, useMemo } = React;

// ----------------------------------------------------------------
// 라우팅 (해시 기반)
//   #/                — 홈
//   #/chapter/:id     — 챕터 상세 (시작 전)
//   #/quiz/:id        — 퀴즈
//   #/grammar         — 전체 문법 모아보기
//   #/admin           — 관리자
// ----------------------------------------------------------------
function useHashRoute() {
  const [hash, setHash] = useState(window.location.hash || "#/");
  useEffect(() => {
    const onChange = () => setHash(window.location.hash || "#/");
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  const navigate = useCallback((to) => {
    window.location.hash = to;
  }, []);
  return [hash, navigate];
}

function parseRoute(hash) {
  const path = hash.replace(/^#\/?/, "");
  const [head, ...rest] = path.split("/");
  return { head: head || "home", rest };
}

// ----------------------------------------------------------------
// 메인 App
// ----------------------------------------------------------------
function App() {
  const [chapters, setChapters] = useState([]);
  const [progress, setProgress] = useState({});
  const [user, setUser] = useState(null);
  const [authLoaded, setAuthLoaded] = useState(false);
  const [loading, setLoading] = useState(true);
  const [completionData, setCompletionData] = useState(null);

  const [hash, navigate] = useHashRoute();
  const route = useMemo(() => parseRoute(hash), [hash]);

  // 챕터 구독 (Firebase 또는 localStorage)
  useEffect(() => {
    setLoading(true);
    const unsub = QuizDB.subscribeChapters((data) => {
      setChapters(data);
      setLoading(false);
    });
    return unsub;
  }, []);

  // 진행도 로드 (localStorage)
  useEffect(() => {
    setProgress(QuizDB.loadProgress());
    const handler = () => setProgress(QuizDB.loadProgress());
    window.addEventListener("storage", handler);
    return () => window.removeEventListener("storage", handler);
  }, []);

  // Auth 구독
  useEffect(() => {
    const unsub = QuizDB.onAuthChange((u) => {
      setUser(u);
      setAuthLoaded(true);
    });
    return unsub;
  }, []);

  // 현재 챕터 (라우트로부터)
  const currentChapter = useMemo(() => {
    if (!route.rest[0]) return null;
    return chapters.find(c => c.id === route.rest[0]);
  }, [chapters, route]);

  const currentChapterIndex = useMemo(() => {
    if (!currentChapter) return -1;
    return chapters.findIndex(c => c.id === currentChapter.id);
  }, [chapters, currentChapter]);

  // 네비게이션 헬퍼
  const goHome = () => navigate("#/");
  const goChapter = (id) => navigate("#/chapter/" + id);
  const goQuiz = (id) => navigate("#/quiz/" + id);
  const goGrammar = () => navigate("#/grammar");
  const goAdmin = () => navigate("#/admin");

  // ────────────────────────────────────────────────────────
  // 퀴즈 완료 핸들러
  // ────────────────────────────────────────────────────────
  function handleQuizComplete(result) {
    if (currentChapter) {
      const newProgress = QuizDB.markChapterCompleted(currentChapter.id, result.score, result.total);
      setProgress({ ...newProgress });
    }
    setCompletionData({ chapter: currentChapter, result });
  }

  function handleCompletionBackHome() {
    setCompletionData(null);
    goHome();
  }
  function handleCompletionRetry() {
    const id = completionData?.chapter?.id;
    setCompletionData(null);
    if (id) {
      // 같은 챕터 다시
      goQuiz(id);
    }
  }

  // ────────────────────────────────────────────────────────
  // 로딩 / 빈 상태
  // ────────────────────────────────────────────────────────
  if (loading && chapters.length === 0) {
    return (
      <div className="app-shell">
        <div className="app-container" style={{ alignItems: "center", justifyContent: "center", paddingTop: 80 }}>
          <div style={{ color: "var(--text-muted)" }}>불러오는 중...</div>
        </div>
      </div>
    );
  }

  // ────────────────────────────────────────────────────────
  // 화면 라우팅
  // ────────────────────────────────────────────────────────
  let screen;

  // 완료 화면이 활성화되면 모든 다른 화면보다 우선
  if (completionData) {
    screen = (
      <CompletionScreen
        chapter={completionData.chapter}
        result={completionData.result}
        onBackHome={handleCompletionBackHome}
        onRetry={handleCompletionRetry}
      />
    );
  } else if (route.head === "quiz" && currentChapter) {
    screen = (
      <QuizScreen
        chapter={currentChapter}
        chapterIndex={currentChapterIndex}
        onExit={() => goChapter(currentChapter.id)}
        onComplete={handleQuizComplete}
      />
    );
  } else if (route.head === "chapter" && currentChapter) {
    screen = (
      <ChapterDetailScreen
        chapter={currentChapter}
        chapterIndex={currentChapterIndex}
        progress={progress[currentChapter.id]}
        onBack={goHome}
        onStart={() => goQuiz(currentChapter.id)}
        onStudy={goGrammar}
      />
    );
  } else if (route.head === "grammar") {
    screen = (
      <GrammarRefScreen chapters={chapters} onBack={goHome} />
    );
  } else if (route.head === "admin") {
    if (!authLoaded) {
      screen = <div style={{ color: "var(--text-muted)", padding: 40 }}>인증 확인 중...</div>;
    } else if (!user) {
      screen = (
        <AdminLoginScreen
          onBack={goHome}
          onSignIn={() => QuizDB.signInWithGoogle()}
          useFirebase={QuizDB.USE_FIREBASE}
        />
      );
    } else if (!user.isAdmin) {
      screen = (
        <div className="fade-in" style={{ paddingTop: 40, textAlign: "center" }}>
          <button className="btn btn-soft btn-sm" onClick={goHome}>
            <Icon name="arrow-left" size={14} /> 홈으로
          </button>
          <div style={{ marginTop: 60, fontSize: 18, color: "var(--text)" }}>
            <Icon name="lock" size={32} />
            <div style={{ marginTop: 16, fontWeight: 700 }}>관리자 권한이 없습니다</div>
            <div style={{ marginTop: 8, color: "var(--text-soft)", fontSize: 14 }}>
              로그인된 계정: {user.email}<br/>
              <code style={{ fontSize: 11 }}>ADMIN_EMAILS</code>에 이 이메일을 추가해주세요.
            </div>
            <button
              className="btn btn-soft"
              style={{ marginTop: 20 }}
              onClick={() => QuizDB.signOut()}
            >
              <Icon name="log-out" size={14} /> 로그아웃
            </button>
          </div>
        </div>
      );
    } else {
      screen = (
        <AdminScreen
          chapters={chapters}
          user={user}
          onBack={goHome}
          onSignOut={() => QuizDB.signOut()}
          onReload={() => {/* 구독으로 자동 갱신 */}}
        />
      );
    }
  } else {
    // home (default)
    screen = (
      <HomeScreen
        chapters={chapters}
        progress={progress}
        onOpenChapter={(id) => goChapter(id)}
        onOpenGrammar={goGrammar}
      />
    );
  }

  // ────────────────────────────────────────────────────────
  // 상단 바 — 퀴즈 화면에서는 숨김 (자체 상단바 사용)
  // ────────────────────────────────────────────────────────
  const hideTopBar = (route.head === "quiz" && !completionData);

  const topRight = (
    <>
      {user?.isAdmin && (
        <button className="stat-chip" onClick={goAdmin} title="관리자">
          <Icon name="settings" size={14} /> 관리
        </button>
      )}
      {!user && route.head !== "admin" && (
        <button
          className="stat-chip"
          onClick={goAdmin}
          title="관리자 로그인"
          style={{ opacity: 0.6 }}
        >
          <Icon name="lock" size={12} />
        </button>
      )}
    </>
  );

  return (
    <div className="app-shell">
      {!hideTopBar && (
        <TopBar
          user={user}
          onTitleClick={goHome}
          rightSlot={topRight}
        />
      )}
      <div className="app-container">
        {screen}
      </div>
    </div>
  );
}

// 마운트
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
