// Shared UI building blocks + i18n + state
const { useState, useEffect, useMemo, useRef, createContext, useContext } = React;

// ---------- i18n ----------
const STRINGS = {
  en: {
    brand: "Daddy's Lab 11+",
    nav_home: "Home",
    nav_tests: "Mock tests",
    nav_dashboard: "Dashboard",
    nav_story: "Our story",
    nav_contact: "Contact",
    login: "Log in",
    signup: "Get started",
    // Hero
    hero_badge: "Built by a data-scientist parent",
    hero_title_a: "Is your child ready for",
    hero_title_b: "the 11+ exam?",
    hero_sub: "Realistic mock exams, instant results, and a clear picture of exactly where your child stands.",
    hero_cta: "Try a free sample",
    hero_cta_2: "See how results work",
    hero_meta_price: "From £3.99 / paper",
    hero_meta_free: "10 free sample questions · no sign-up",
    // Value props
    vp_eyebrow: "Competitiveness",
    vp_title: "Why UK parents love this",
    vp_1_t: "Stop hunting",
    vp_1_b: "No more endless scrolling for cheap practice papers. £3.99 a test set.",
    vp_2_t: "Know instantly",
    vp_2_b: "Auto-graded the second the timer ends. Your child's level — now, not next week.",
    vp_3_t: "Fix what's weak",
    vp_3_b: "Pinpoints weak topics + serves similar questions to drill them.",
    // Pricing compare
    pc_eyebrow: "Price check",
    pc_title: "How we compare with the alternatives.",
    pc_note: "Indicative pricing from public listings, April 2026. Compare before you commit — our packs include the full topic report.",
    pc_hdr_provider: "Provider",
    pc_hdr_single: "Per paper",
    pc_hdr_pack: "Best pack rate",
    pc_hdr_report: "Topic-level report",
    pc_us: "Daddy's Lab 11+",
    pc_atom: "Company A",
    pc_bond: "Company B",
    pc_cgp: "Company C",
    pc_eps: "Company D",
    // Sample section
    sample_eyebrow: "Try before you sign up",
    sample_title: "Ten questions. No account.",
    sample_sub: "Answers and worked solutions unlock when you register — free.",
    sample_cta: "Start sample paper",
    // Story
    story_eyebrow: "Our story",
    story_title: "Built by a data-scientist dad, for his own daughter's 11+.",
    story_body_1: "I'm a working data scientist and father of three. This platform started as a weekend project for my eldest, who was preparing for the 11+.",
    story_body_2: "One problem kept showing up — no one could tell us exactly where she was weak. So I analysed years of past paper data and built the reports I wished we had: per-topic scoring that shows you what to fix next.",
    story_sig: "— Joseph Lee, founder",
    // Footer
    footer_tag: "Daddy's Lab 11+ · Made in London for anxious parents everywhere.",
    // Test UI
    test_q: "Question",
    test_of: "of",
    test_time: "Time left",
    test_flag: "Flag for review",
    test_flagged: "Flagged",
    test_prev: "Previous",
    test_next: "Next",
    test_submit: "Submit paper",
    test_review: "Review answers",
    // Choose mode
    mode_title: "How will your child take this paper?",
    mode_sub: "Pick once — you can't switch mid-paper.",
    mode_online: "Online",
    mode_online_desc: "Take the paper in the browser. Instant, accurate marking.",
    mode_paper: "Print & scan",
    mode_paper_desc: "Print the paper + answer sheet. Scan the sheet at the end — we'll mark it with OCR.",
    mode_recommended: "Recommended",
    mode_go: "Continue",
    // PDF scan
    scan_title: "Upload the answer sheet",
    scan_sub: "Take a clear photo, or scan. One image, or one per page.",
    scan_drop: "Drop image here, or click to browse",
    scan_disclaimer: "Note: marking is done by image recognition, so results may be slightly less accurate than an online test. We recommend the online test when possible.",
    scan_marking: "Marking your paper…",
    scan_step_1: "Reading the answer sheet",
    scan_step_2: "Matching to the answer key",
    scan_step_3: "Building your topic report",
    // Results
    res_title: "Paper complete",
    res_score: "Your score",
    res_rank: "Rank",
    res_percentile: "Percentile",
    res_participants: "participants",
    res_bell_caption: "You scored higher than",
    res_of_students: "of students who took this paper",
    res_topic_title: "Topic breakdown",
    res_topic_sub: "14 Key Stage 2 math topics. Click a row to review.",
    res_qgrid_title: "Answer grid",
    res_qgrid_sub: "Click any question to see the worked solution.",
    res_next_steps: "Next steps",
    res_strengthen: "Topics to strengthen",
    res_strong: "Strong areas",
    // Question review
    rev_correct: "Correct",
    rev_wrong: "Your answer",
    rev_answer: "Answer",
    rev_solution: "Worked solution",
    rev_similar: "Try a similar question",
    rev_back: "Back to results",
    // Dashboard
    dash_hi: "Welcome back",
    dash_credits: "Papers remaining",
    dash_buy: "Buy more papers",
    dash_history: "Your papers",
    dash_trend: "Score trend",
    dash_weakest: "Most-missed topics",
    dash_start: "Start new paper",
  },
  ko: {
    brand: "Daddy's Lab 11+",
    nav_home: "홈",
    nav_tests: "모의고사",
    nav_dashboard: "대시보드",
    nav_story: "이야기",
    nav_contact: "문의",
    login: "로그인",
    signup: "시작하기",
    hero_badge: "데이터 사이언티스트 아빠가 만든",
    hero_title_a: "우리 아이, 11+ 시험",
    hero_title_b: "준비됐을까요?",
    hero_sub: "실전과 같은 모의고사, 즉시 채점, 그리고 아이의 현재 위치를 정확히 보여주는 리포트.",
    hero_cta: "샘플 무료로 풀어보기",
    hero_cta_2: "결과 화면 미리보기",
    hero_meta_price: "모의고사 1회 £3.99부터",
    hero_meta_free: "샘플 10문제 · 가입 불필요",
    vp_eyebrow: "경쟁력",
    vp_title: "영국 부모님들이 이 도구를 선택하는 이유",
    vp_1_t: "찾아 헤맬 필요 없음",
    vp_1_b: "저렴한 연습 시험지 찾아 끝없이 스크롤할 일 없음. 1회 £3.99.",
    vp_2_t: "즉시 결과",
    vp_2_b: "타이머가 끝나는 순간 자동 채점. 다음 주가 아니라 지금 아이의 실력을 확인하세요.",
    vp_3_t: "약점 보강",
    vp_3_b: "약한 유형을 정확히 짚고, 비슷한 문제로 그 유형만 집중 훈련합니다.",
    pc_eyebrow: "가격 비교",
    pc_title: "주요 서비스와 한눈에 비교.",
    pc_note: "2026년 4월 기준 공개 가격 참고치. 결제 전 비교해 보세요. 저희는 유형별 리포트까지 포함된 가격입니다.",
    pc_hdr_provider: "서비스",
    pc_hdr_single: "1회 가격",
    pc_hdr_pack: "묶음 최저가",
    pc_hdr_report: "유형별 리포트",
    pc_us: "Daddy's Lab 11+",
    pc_atom: "A사",
    pc_bond: "B사",
    pc_cgp: "C사",
    pc_eps: "D사",
    sample_eyebrow: "가입 전에 먼저",
    sample_title: "10문제, 계정 없이.",
    sample_sub: "정답과 해설은 무료 가입 후 바로 확인할 수 있습니다.",
    sample_cta: "샘플 풀기",
    story_eyebrow: "만든 이야기",
    story_title: "딸의 11+를 위해 데이터 사이언티스트 아빠가 만든 도구.",
    story_body_1: "세 아이를 둔 현업 데이터 사이언티스트입니다. 큰 딸의 11+ 준비를 위해 주말 프로젝트로 시작했습니다.",
    story_body_2: "반복해서 부딪힌 문제 하나 — 어느 부분이 약한지 정확히 알려주는 곳이 없었습니다. 그래서 수년치 기출 데이터를 분석해, 우리가 필요했던 리포트를 직접 만들었습니다: 다음에 어디를 고쳐야 하는지 보여주는 유형별 점수.",
    story_sig: "— Joseph Lee, 창업자",
    footer_tag: "Daddy's Lab 11+ · 불안한 모든 부모를 위해, 런던에서.",
    test_q: "문제",
    test_of: "/",
    test_time: "남은 시간",
    test_flag: "나중에 다시",
    test_flagged: "표시됨",
    test_prev: "이전",
    test_next: "다음",
    test_submit: "답안 제출",
    test_review: "결과 보기",
    mode_title: "어떻게 시험 볼까요?",
    mode_sub: "한 번만 선택 가능 — 중간에 바꿀 수 없어요.",
    mode_online: "온라인",
    mode_online_desc: "브라우저에서 바로 풉니다. 즉시, 정확하게 채점.",
    mode_paper: "인쇄 & 스캔",
    mode_paper_desc: "시험지와 답지를 인쇄합니다. 다 풀고 답지를 스캔하면 OCR로 채점합니다.",
    mode_recommended: "추천",
    mode_go: "시작",
    scan_title: "답지를 올려주세요",
    scan_sub: "선명한 사진 또는 스캔본. 한 장이든, 페이지별 여러 장이든.",
    scan_drop: "여기에 이미지 드롭, 또는 클릭해서 선택",
    scan_disclaimer: "안내: 이미지 인식으로 채점하므로 결과가 약간 부정확할 수 있습니다. 가능하면 온라인 시험을 권장합니다.",
    scan_marking: "답지를 채점 중…",
    scan_step_1: "답지 이미지 읽는 중",
    scan_step_2: "정답지와 매칭 중",
    scan_step_3: "유형별 리포트 생성 중",
    res_title: "시험 종료",
    res_score: "점수",
    res_rank: "순위",
    res_percentile: "상위",
    res_participants: "명 참여",
    res_bell_caption: "전체 응시자 중 상위",
    res_of_students: "",
    res_topic_title: "유형별 분석",
    res_topic_sub: "Key Stage 2 수학 14개 유형. 행을 눌러 문제 풀이를 확인.",
    res_qgrid_title: "정오표",
    res_qgrid_sub: "문제를 클릭하면 풀이를 볼 수 있어요.",
    res_next_steps: "다음 할 일",
    res_strengthen: "강화할 유형",
    res_strong: "잘하는 유형",
    rev_correct: "정답",
    rev_wrong: "내가 쓴 답",
    rev_answer: "정답",
    rev_solution: "풀이",
    rev_similar: "유사 문제 풀기",
    rev_back: "결과로 돌아가기",
    dash_hi: "어서오세요",
    dash_credits: "남은 시험 횟수",
    dash_buy: "더 구매하기",
    dash_history: "응시 기록",
    dash_trend: "점수 추이",
    dash_weakest: "가장 많이 틀리는 유형",
    dash_start: "새 시험 시작",
  }
};

const LangContext = createContext({ lang: "en", t: (k) => k, setLang: () => {} });
function useT() { return useContext(LangContext); }

// ---------- 14 KS2 topics ----------
const TOPICS = [
  { id: 1, en: "Four operations", ko: "사칙연산" },
  { id: 2, en: "Number values & sequences", ko: "수 값과 수 배열" },
  { id: 3, en: "Factors & multiples", ko: "약수와 배수" },
  { id: 4, en: "Fractions & decimals", ko: "분수와 소수" },
  { id: 5, en: "Percentages, ratio & proportion", ko: "백분율·비·비례" },
  { id: 6, en: "Algebra & number machines", ko: "대수와 수 기계" },
  { id: 7, en: "Averages & data", ko: "평균과 자료 표현" },
  { id: 8, en: "Measures & scales", ko: "측정과 눈금 읽기" },
  { id: 9, en: "Dates, times & timetables", ko: "날짜·시간·시간표" },
  { id: 10, en: "Lines, angles & bearings", ko: "선·각·방위" },
  { id: 11, en: "2D shapes, perimeter & area", ko: "평면도형·둘레·넓이" },
  { id: 12, en: "3D shapes & volume", ko: "입체도형과 부피" },
  { id: 13, en: "Probability", ko: "확률" },
  { id: 14, en: "Coordinates & transformations", ko: "좌표와 변환" },
];

function topicName(topic, lang) {
  return lang === "ko" ? topic.ko : topic.en;
}

// ---------- Small UI components ----------
function Logo({ size = 22 }) {
  // Original wordmark: two concentric geometric shapes + "11+"
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden>
        <rect x="2" y="2" width="28" height="28" rx="6" fill="var(--ink-1)" />
        <text x="16" y="21" textAnchor="middle" fontFamily="IBM Plex Serif" fontSize="13" fontWeight="500" fill="var(--paper)">11+</text>
      </svg>
      <span style={{ fontFamily: "var(--font-serif)", fontSize: 17, letterSpacing: "-0.01em" }}>
        Daddy's Lab <span style={{ color: "var(--indigo)" }}>11+</span>
      </span>
    </div>
  );
}

function Nav({ view, setView, isLoggedIn, onLogin, onSignup, onLogout, userName }) {
  const { t, lang, setLang } = useT();
  const items = [
    { id: "home", label: t("nav_home"), gated: false },
    { id: "tests", label: t("nav_tests"), gated: true },
    { id: "dashboard", label: t("nav_dashboard"), gated: true },
    { id: "story", label: t("nav_story"), gated: false },
    { id: "contact", label: t("nav_contact"), gated: false, anchor: "contact" },
  ].filter(it => !it.gated || isLoggedIn);

  // Anchor-style nav items (e.g. Contact) live as a section on the
  // landing page. Clicking them sends the user back to home if needed
  // and smooth-scrolls to the section.
  function onNavClick(it) {
    if (it.anchor) {
      if (view !== "home") setView("home");
      // Wait one tick so the home view actually mounts before scrolling.
      setTimeout(() => {
        const el = document.getElementById(it.anchor);
        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      }, view === "home" ? 0 : 80);
      return;
    }
    setView(it.id);
  }
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: "color-mix(in oklab, var(--paper) 92%, transparent)",
      backdropFilter: "blur(8px)",
      borderBottom: "1px solid var(--line)"
    }}>
      <div style={{
        maxWidth: 1240, margin: "0 auto", padding: "14px 28px",
        display: "flex", alignItems: "center", gap: 28,
      }}>
        <a href="#" onClick={(e) => { e.preventDefault(); setView("home"); }} style={{ textDecoration: "none" }}>
          <Logo />
        </a>
        <nav style={{ display: "flex", gap: 4, marginLeft: 12 }}>
          {items.map((it) => (
            <button
              key={it.id}
              onClick={() => onNavClick(it)}
              style={{
                border: "none", background: "transparent", cursor: "pointer",
                padding: "8px 12px", borderRadius: 6,
                fontSize: 14, color: view === it.id ? "var(--ink-1)" : "var(--ink-3)",
                fontWeight: view === it.id ? 500 : 400,
                fontFamily: "inherit",
              }}
            >
              {it.label}
            </button>
          ))}
        </nav>
        <div style={{ flex: 1 }} />
        {isLoggedIn && userName && (
          <div style={{
            fontFamily: "var(--font-serif)", fontSize: 14, color: "var(--ink-2)",
            fontStyle: "italic", marginRight: 4, letterSpacing: "-0.01em",
            display: "flex", alignItems: "center", gap: 6,
          }}>
            <span style={{ fontSize: 16 }}>👋</span>
            {lang === "ko" ? `${userName}님, 환영합니다!` : `Greetings, ${userName}!`}
          </div>
        )}
        <div style={{
          display: "flex", alignItems: "center", gap: 2,
          background: "var(--paper-2)", border: "1px solid var(--line)",
          borderRadius: 999, padding: 2, fontSize: 12, fontFamily: "var(--font-mono)"
        }}>
          {["en", "ko"].map(l => (
            <button key={l} onClick={() => setLang(l)}
              style={{
                border: "none", cursor: "pointer",
                padding: "5px 11px", borderRadius: 999,
                background: lang === l ? "var(--ink-1)" : "transparent",
                color: lang === l ? "var(--paper)" : "var(--ink-3)",
                fontFamily: "inherit", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase",
              }}>
              {l}
            </button>
          ))}
        </div>
        <button className="btn btn-ghost" style={{ padding: "8px 14px" }} onClick={isLoggedIn ? onLogout : onLogin}>
          {isLoggedIn ? (lang === "ko" ? "로그아웃" : "Log out") : t("login")}
        </button>
        {!isLoggedIn && <button className="btn btn-dark" style={{ padding: "8px 14px" }} onClick={onSignup}>{t("signup")}</button>}
      </div>
    </header>
  );
}

function Footer() {
  const { t } = useT();
  return (
    <footer style={{
      borderTop: "1px solid var(--line)", marginTop: 80, padding: "32px 28px",
      background: "var(--paper-2)"
    }}>
      <div style={{
        maxWidth: 1240, margin: "0 auto",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        fontSize: 13, color: "var(--ink-3)"
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <Logo size={18} />
          <a href="privacy.html" target="_blank" style={{ fontSize: 12, color: "var(--ink-4)", textDecoration: "none", fontFamily: "var(--font-mono)" }}>Privacy Policy</a>
        </div>
        <div className="mono" style={{ fontSize: 11, letterSpacing: "0.04em" }}>{t("footer_tag")}</div>
      </div>
    </footer>
  );
}

// export to window
Object.assign(window, {
  STRINGS, LangContext, useT, TOPICS, topicName, Logo, Nav, Footer,
  React_useState: useState, React_useEffect: useEffect,
});
