/* ============================================================
   app.jsx — shell, navigation, state, session runners
   ============================================================ */
const { useState: aS, useEffect: aE } = React;

const NAV = [
  { key: "dashboard", label: "대시보드", icon: "home" },
  { key: "expressions", label: "표현", icon: "layers" },
  { key: "study", label: "학습", icon: "pen" },
  { key: "review", label: "복습", icon: "repeat" },
  { key: "summary", label: "정리", icon: "folder" },
];

/* shuffle helper */
const shuffle = (a) => { const r = [...a]; for (let i = r.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [r[i], r[j]] = [r[j], r[i]]; } return r; };

/* ---------- Study launcher (choose a session, then run flow) ---------- */
function StudyView({ list, onReview, onSave }) {
  const { Button, Icon, EmptyState } = window.UI;
  const [tab, setTab] = aS("cards");        // cards | word
  const [session, setSession] = aS(null);   // array of exprs being studied
  const [scope, setScope] = aS("all");

  if (session) {
    return <window.Flow.StudyFlow items={session} title="자유 학습" onReview={onReview} onExit={() => setSession(null)} />;
  }

  const tags = window.Store.allTags(list);
  function start() {
    let pool = scope === "all" ? list : list.filter((e) => (e.tags || []).includes(scope));
    if (pool.length) setSession(shuffle(pool));
  }

  return (
    <div>
      <div className="page-head">
        <h1 className="h-xl">학습</h1>
        <div className="muted" style={{ fontSize: 14, marginTop: 2 }}>
          {tab === "cards" ? "모은 표현·단어를 골라 예문 보기 → 직접 작문 → AI 평가로 익혀요" : "아무 단어나 입력해 그 단어로 문장 만드는 연습을 해요"}
        </div>
      </div>

      <div className="seg" style={{ marginBottom: 22 }}>
        <button className={tab === "cards" ? "on" : ""} onClick={() => setTab("cards")}>표현·단어 학습</button>
        <button className={tab === "word" ? "on" : ""} onClick={() => setTab("word")}>단어 작문</button>
      </div>

      {tab === "word" ? (
        <window.WordPractice onSave={onSave} />
      ) : list.length === 0 ? (
        <EmptyState title="학습할 표현이 없어요" sub="먼저 표현이나 단어를 추가해 주세요." />
      ) : (
        <div className="card" style={{ maxWidth: 460 }}>
          <div className="label" style={{ marginBottom: 9 }}>무엇을 학습할까요?</div>
          <div className="row wrap" style={{ gap: 7, marginBottom: 18 }}>
            <button className={"chip" + (scope === "all" ? " on" : "")} onClick={() => setScope("all")}>전체 ({list.length})</button>
            {tags.map((t) => {
              const n = list.filter((e) => (e.tags || []).includes(t)).length;
              return <button key={t} className={"chip" + (scope === t ? " on" : "")} onClick={() => setScope(t)}>{t} ({n})</button>;
            })}
          </div>
          <Button variant="primary" size="lg" block iconRight="arrowRight" onClick={start}>학습 시작</Button>
        </div>
      )}
    </div>
  );
}

/* ---------- Review (spaced repetition queue) ---------- */
function ReviewView({ list, onReview, goAdd }) {
  const { Button, Icon, EmptyState } = window.UI;
  const Store = window.Store;
  const [running, setRunning] = aS(false);
  const [queue, setQueue] = aS([]);
  const due = Store.dueList(list);

  if (running) {
    return <window.Flow.StudyFlow items={queue} title="오늘의 복습" onReview={onReview} onExit={() => setRunning(false)} />;
  }

  return (
    <div>
      <div className="page-head">
        <h1 className="h-xl">복습</h1>
        <div className="muted" style={{ fontSize: 14, marginTop: 2 }}>망각곡선에 맞춰 오늘 복습할 표현만 모았어요</div>
      </div>
      {due.length === 0 ? (
        <EmptyState icon="check" title="오늘 복습할 표현이 없어요"
          sub="예정된 복습을 모두 마쳤어요. 새 표현을 추가하거나 자유 학습으로 더 연습해 보세요."
          action={<Button variant="ghost" icon="plus" onClick={goAdd}>표현 추가</Button>} />
      ) : (
        <div className="card" style={{ maxWidth: 460 }}>
          <div className="row" style={{ gap: 14, marginBottom: 16 }}>
            <div style={{ width: 46, height: 46, borderRadius: 13, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center" }}>
              <Icon name="flame" size={22} />
            </div>
            <div>
              <div className="h-lg">{due.length}개 표현</div>
              <div className="muted" style={{ fontSize: 14, whiteSpace: "nowrap" }}>오늘 복습 예정</div>
            </div>
          </div>
          <Button variant="primary" size="lg" block iconRight="arrowRight" onClick={() => { setQueue(shuffle(due)); setRunning(true); }}>복습 시작</Button>
        </div>
      )}
    </div>
  );
}

/* ---------- Confirm delete ---------- */
function ConfirmDelete({ expr, onCancel, onConfirm }) {
  const { Button } = window.UI;
  return (
    <window.UI.Modal title="표현 삭제" onClose={onCancel}
      foot={<>
        <Button variant="quiet" onClick={onCancel}>취소</Button>
        <Button variant="primary" onClick={onConfirm} style={{ background: "var(--bad)" }}>삭제</Button>
      </>}>
      <div style={{ fontSize: 15 }}><b>“{expr.expression}”</b> 표현을 삭제할까요? 이 작업은 되돌릴 수 없어요.</div>
    </window.UI.Modal>
  );
}

/* ============================================================
   App
   ============================================================ */
function App() {
  const Store = window.Store;
  const { Icon } = window.UI;
  const [list, setList] = aS(() => Store.load());
  const [view, setView] = aS(() => localStorage.getItem(Store.VIEW_KEY) || "dashboard");
  const [form, setForm] = aS({ open: false, expr: null });
  const [del, setDel] = aS(null);

  aE(() => { Store.persist(list); }, [list]);
  aE(() => { localStorage.setItem(Store.VIEW_KEY, view); }, [view]);

  const due = Store.dueList(list);

  function go(v) { setView(v); if (typeof window !== "undefined") window.scrollTo(0, 0); }

  function saveExpr(data) {
    setList((prev) => {
      if (data.id) return prev.map((e) => (e.id === data.id ? { ...e, ...data } : e));
      return [Store.makeExpression(data), ...prev];
    });
  }
  function reviewExpr(updated) {
    setList((prev) => prev.map((e) => (e.id === updated.id ? updated : e)));
    Store.logStudy(1);
  }
  function removeExpr(expr) { setList((prev) => prev.filter((e) => e.id !== expr.id)); setDel(null); }

  const openForm = (expr) => setForm({ open: true, expr });
  const closeForm = () => setForm({ open: false, expr: null });

  return (
    <div className="app">
      {/* sidebar (desktop) */}
      <aside className="sidebar">
        <div className="brand">
          <div className="brand-mark">C&H</div>
          <div>
            <div className="brand-name">English note</div>
            <div className="brand-sub">나만의 영어 표현 노트</div>
          </div>
        </div>
        <nav className="nav">
          {NAV.map((n) => (
            <button key={n.key} className={"nav-item" + (view === n.key ? " active" : "")} onClick={() => go(n.key)}>
              <Icon name={n.icon} size={18} />
              {n.label}
              {n.key === "review" && due.length > 0 && <span className="nav-badge">{due.length}</span>}
            </button>
          ))}
        </nav>
        <div className="sidebar-foot col" style={{ gap: 10 }}>
          <window.ThemePicker />
          <div style={{ fontSize: 11.5, color: "var(--ink-4)" }}>{window.AI.HAS_LLM ? "AI 연결됨" : "미리보기 모드 · AI 예시 응답"}</div>
        </div>
      </aside>

      {/* main */}
      <main className="main">
        <div className="content">
          {view === "dashboard" && <window.Dashboard list={list} onStartReview={() => go("review")} onAdd={() => { go("expressions"); setTimeout(() => openForm(null), 0); }} goExpressions={() => go("expressions")} />}
          {view === "expressions" && <window.ExpressionsView list={list} onSave={saveExpr} onDelete={setDel} openForm={openForm} formState={form} closeForm={closeForm} />}
          {view === "study" && <StudyView list={list} onReview={reviewExpr} onSave={saveExpr} />}
          {view === "review" && <ReviewView list={list} onReview={reviewExpr} goAdd={() => { go("expressions"); setTimeout(() => openForm(null), 0); }} />}
          {view === "summary" && <window.SummaryView list={list} />}
        </div>
      </main>

      {/* mobile tab bar */}
      <nav className="tabbar">
        {NAV.map((n) => (
          <button key={n.key} className={"tab" + (view === n.key ? " active" : "")} onClick={() => go(n.key)}>
            {n.key === "review" && due.length > 0 && <span className="tab-dot">{due.length}</span>}
            <Icon name={n.icon} size={20} />
            {n.label}
          </button>
        ))}
      </nav>

      {del && <ConfirmDelete expr={del} onCancel={() => setDel(null)} onConfirm={() => removeExpr(del)} />}
    </div>
  );
}

(async () => {
  // 1) access-key gate — renders the login form and stops here if not authed
  if (!window.Auth.ensure()) return;
  // 2) pull this user's data from Notion into the cache before first render
  try {
    await window.Store.syncFromServer();
  } catch (e) {
    console.warn("Notion 동기화 실패 — 로컬 캐시로 시작합니다.", e);
  }
  // 3) mount
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
})();
