/* ============================================================
   app.jsx — main App with view router, auth, API-backed articles + content
   ============================================================ */

const PALETTES = {
  cream:   { brand: "0.42 0.06 50",  accent: "0.58 0.13 40", bg: "0.965 0.012 75", bg2: "0.935 0.018 70" },
  sage:    { brand: "0.42 0.04 140", accent: "0.55 0.10 35", bg: "0.96 0.012 110", bg2: "0.92 0.018 110" },
  navy:    { brand: "0.30 0.04 250", accent: "0.62 0.13 35", bg: "0.96 0.010 80",  bg2: "0.92 0.018 75" },
  rose:    { brand: "0.45 0.08 15",  accent: "0.62 0.14 20", bg: "0.965 0.012 20", bg2: "0.93 0.020 25" },
};

const FONT_PAIRS = {
  serif:  { display: '"Noto Serif Display", serif',         thai: '"IBM Plex Sans Thai", sans-serif',   body: '"IBM Plex Sans Thai", sans-serif' },
  modern: { display: '"DM Serif Display", serif',           thai: '"IBM Plex Sans Thai", sans-serif', body: '"IBM Plex Sans Thai", sans-serif' },
  warm:   { display: '"EB Garamond", serif',                thai: '"Bai Jamjuree", sans-serif',   body: '"Bai Jamjuree", sans-serif' },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "palette": "cream",
  "fontPair": "serif",
  "fontScale": 1,
  "heroLayout": "editorial"
}/*EDITMODE-END*/;

function applyTweaks(t) {
  const root = document.documentElement;
  root.setAttribute("data-theme", t.theme || "light");
  root.style.setProperty("--type-scale", String(t.fontScale ?? 1));

  const p = PALETTES[t.palette] || PALETTES.cream;
  root.style.setProperty("--brand", `oklch(${p.brand})`);
  root.style.setProperty("--accent", `oklch(${p.accent})`);
  if ((t.theme || "light") === "light") {
    root.style.setProperty("--bg", `oklch(${p.bg})`);
    root.style.setProperty("--bg-2", `oklch(${p.bg2})`);
  } else {
    root.style.removeProperty("--bg");
    root.style.removeProperty("--bg-2");
  }

  const f = FONT_PAIRS[t.fontPair] || FONT_PAIRS.serif;
  root.style.setProperty("--font-display", f.display);
  root.style.setProperty("--font-thai-display", f.thai);
  root.style.setProperty("--font-body", f.body);
}

function App() {
  const [view, setView] = React.useState("home");
  const [activeArticle, setActiveArticle] = React.useState(null);
  const [editingArticle, setEditingArticle] = React.useState(null);
  const [editorReturn, setEditorReturn] = React.useState("articles");
  const [teacher, setTeacher] = React.useState(null);
  const [bookingSubject, setBookingSubject] = React.useState("");
  const [articles, setArticles] = React.useState([]);

  // Auth
  const [token, setToken] = React.useState(() => localStorage.getItem('bm_admin') || '');
  const [isAdmin, setIsAdmin] = React.useState(false);

  // Content overrides (courses / teachers / pricing) from API
  const [content, setContent] = React.useState({});

  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  React.useEffect(() => { applyTweaks(t); }, [t]);
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [view, activeArticle?.id]);

  // Handle special URL paths on mount
  React.useEffect(() => {
    const hash = window.location.hash;
    const path = window.location.pathname;
    if (hash === '#admin') {
      window.location.hash = '';
      setView(isAdmin ? 'contentEditor' : 'login');
    } else if (path === '/payment/return') {
      setView('paymentReturn');
    }
  }, []);

  // Validate stored token on mount
  React.useEffect(() => {
    if (!token) return;
    fetch('/api/auth/check', { headers: { 'x-auth-token': token } })
      .then(r => r.json())
      .then(d => {
        if (d.ok) setIsAdmin(true);
        else { localStorage.removeItem('bm_admin'); setToken(''); }
      })
      .catch(() => {});
  }, []);

  // Load articles from server; seed on first run
  React.useEffect(() => {
    fetch('/api/articles')
      .then(r => r.json())
      .then(async data => {
        if (data === null) {
          await fetch('/api/articles/seed', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ articles: SEED_ARTICLES }),
          }).catch(() => {});
          setArticles(SEED_ARTICLES);
        } else {
          setArticles(data);
        }
      })
      .catch(() => setArticles(SEED_ARTICLES));
  }, []);

  // Load content overrides
  React.useEffect(() => {
    fetch('/api/content')
      .then(r => r.json())
      .then(data => setContent(data || {}))
      .catch(() => {});
  }, []);

  const effectiveHero    = content.hero    ? { ...DEFAULT_HERO, ...content.hero } : DEFAULT_HERO;
  const effectiveCourses = content.courses || COURSES;
  const effectiveTeachers = content.teachers || TEACHERS;
  const effectivePricing = content.pricing || DEFAULT_PRICING;
  const effectiveGallery = content.gallery || DEFAULT_GALLERY;
  const effectiveReviews = content.reviews || DEFAULT_REVIEWS;

  // Navigation
  const nav = (target) => {
    if (target === "home") { setView("home"); setTimeout(() => window.scrollTo({ top: 0, behavior: "smooth" }), 30); return; }
    const sections = ["courses", "teachers", "pricing", "contact", "schedule", "gallery", "reviews"];
    if (sections.includes(target)) {
      if (view !== "home") { setView("home"); setTimeout(() => document.getElementById(target)?.scrollIntoView({ behavior: "smooth", block: "start" }), 60); }
      else { document.getElementById(target)?.scrollIntoView({ behavior: "smooth", block: "start" }); }
      return;
    }
    if (target === "booking") { setBookingSubject(""); setView("booking"); return; }
    if (target === "articles") { setView("articles"); return; }
  };

  const openArticle = (a) => { setActiveArticle(a); setView("article"); };

  const newArticle = (returnTo = "articles") => {
    setEditorReturn(returnTo);
    setEditingArticle(null);
    setView("editor");
  };

  const editArticle = (a, returnTo = "articles") => {
    setEditorReturn(returnTo);
    setEditingArticle(a);
    setView("editor");
  };

  const saveArticle = async (draft) => {
    const exists = articles.some(a => a.id === draft.id);
    try {
      const r = await fetch(
        exists ? `/api/articles/${draft.id}` : '/api/articles',
        {
          method: exists ? 'PUT' : 'POST',
          headers: { 'Content-Type': 'application/json', 'x-auth-token': token },
          body: JSON.stringify(draft),
        }
      );
      if (r.ok) {
        setArticles(prev => exists
          ? prev.map(a => a.id === draft.id ? draft : a)
          : [draft, ...prev]);
      }
    } catch (e) {}
    setView(editorReturn);
    setEditingArticle(null);
  };

  const deleteArticle = async (a) => {
    try {
      await fetch(`/api/articles/${a.id}`, { method: 'DELETE', headers: { 'x-auth-token': token } });
      setArticles(prev => prev.filter(p => p.id !== a.id));
    } catch (e) {}
    if (activeArticle?.id === a.id) setActiveArticle(null);
    setEditingArticle(null);
    if (view === "article" || view === "editor") setView(editorReturn);
  };

  const resetArticles = async () => {
    if (!confirm("รีเซ็ตกลับเป็นบทความเริ่มต้น? (บทความที่เพิ่มเองจะหายไป)")) return;
    try {
      await fetch('/api/articles/reset', { method: 'DELETE', headers: { 'x-auth-token': token } });
      await fetch('/api/articles/seed', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ articles: SEED_ARTICLES }),
      });
      setArticles(SEED_ARTICLES);
    } catch (e) {}
  };

  // Auth handlers
  const handleLogin = (newToken) => {
    localStorage.setItem('bm_admin', newToken);
    setToken(newToken);
    setIsAdmin(true);
    setView('contentEditor');
  };

  const handleLogout = async () => {
    try { await fetch('/api/auth/logout', { method: 'POST', headers: { 'x-auth-token': token } }); } catch (e) {}
    localStorage.removeItem('bm_admin');
    setToken('');
    setIsAdmin(false);
    setView('home');
  };

  const bookSubject = (id) => { setBookingSubject(id); setView("booking"); };

  // Active section for nav highlight
  const [activeSection, setActiveSection] = React.useState("home");
  React.useEffect(() => {
    if (view !== "home") { setActiveSection(view); return; }
    const ids = ["home", "courses", "teachers", "pricing", "articles", "contact"];
    const onScroll = () => {
      let curr = "home";
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top < 200) curr = id;
      }
      setActiveSection(curr);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [view]);

  return (
    <>
      <Nav view={activeSection} onNav={nav} />

      {view === "home" && (
        <>
          <Hero layout={t.heroLayout === "bleed" ? "bleed" : t.heroLayout === "stacked" ? "stacked" : "editorial"} onCta={nav} heroContent={effectiveHero} />
          <Marquee />
          <CoursesSection onBook={bookSubject} courses={effectiveCourses} />
          <TeachersSection onSelect={setTeacher} teachers={effectiveTeachers} />
          <ScheduleStrip onBook={() => nav("booking")} />
          <AboutSection />
          <PricingSection onBook={() => nav("booking")} onInstallment={() => setView("payment")} pricing={effectivePricing} />
          <GallerySection gallery={effectiveGallery} />
          <ReviewsSection reviews={effectiveReviews} />
          <ArticlesPreview articles={articles} onOpen={openArticle} onAll={() => nav("articles")} />
          <ContactSection />
        </>
      )}

      {view === "booking" && (
        <BookingFlow presetSubject={bookingSubject} onClose={() => setView("home")} />
      )}

      {view === "payment" && (
        <InstallmentPage courses={effectiveCourses} onClose={() => setView("home")} />
      )}

      {view === "paymentReturn" && (
        <PaymentReturn onHome={() => setView("home")} />
      )}

      {view === "articles" && (
        <ArticlesPage
          articles={articles}
          onOpen={openArticle}
          onNew={() => isAdmin ? newArticle("articles") : setView("login")}
          onAdmin={() => isAdmin ? setView("contentEditor") : setView("login")}
          onBack={() => setView("home")}
          isAdmin={isAdmin}
        />
      )}

      {view === "article" && activeArticle && (
        <ArticleView
          article={articles.find(a => a.id === activeArticle.id) || activeArticle}
          onBack={() => setView("articles")}
          onEdit={a => editArticle(a, "articles")}
        />
      )}

      {view === "editor" && (
        <ArticleEditor
          article={editingArticle}
          onSave={saveArticle}
          onCancel={() => setView(editorReturn)}
          onDelete={deleteArticle}
        />
      )}

      {view === "login" && (
        <AdminLogin
          onSuccess={handleLogin}
          onCancel={() => setView("articles")}
        />
      )}

      {view === "contentEditor" && (
        <ContentEditor
          token={token}
          articles={articles}
          onArticleEdit={a => editArticle(a, "contentEditor")}
          onArticleDelete={deleteArticle}
          onArticleNew={() => newArticle("contentEditor")}
          onArticlesReset={resetArticles}
          onContentSave={setContent}
          onLogout={handleLogout}
          onBack={() => setView("home")}
        />
      )}

      <Footer onNav={nav} />

      {teacher && <TeacherModal teacher={teacher} onClose={() => setTeacher(null)} />}

      <TweaksPanel title="Tweaks" defaultOpen={false}>
        <TweakSection title="โหมดสี">
          <TweakRadio
            label="ธีม"
            value={t.theme}
            options={[
              { value: "light", label: "Light" },
              { value: "dark",  label: "Dark"  },
            ]}
            onChange={(v) => setTweak("theme", v)}
          />
          <TweakSelect
            label="โทนสี"
            value={t.palette}
            options={[
              { value: "cream", label: "Cream / น้ำตาลอุ่น (default)" },
              { value: "sage",  label: "Sage / เขียวเข้ม"  },
              { value: "navy",  label: "Navy / กรมท่า"  },
              { value: "rose",  label: "Rose / ชมพูอุ่น"  },
            ]}
            onChange={(v) => setTweak("palette", v)}
          />
        </TweakSection>

        <TweakSection title="ตัวอักษร">
          <TweakSelect
            label="คู่ฟอนต์"
            value={t.fontPair}
            options={[
              { value: "serif",  label: "Editorial Serif (default)" },
              { value: "modern", label: "Modern (DM Serif + IBM Plex)" },
              { value: "warm",   label: "Warm (Garamond + Bai Jamjuree)" },
            ]}
            onChange={(v) => setTweak("fontPair", v)}
          />
          <TweakSlider
            label="ขนาดตัวอักษร"
            value={Math.round((t.fontScale || 1) * 100)}
            min={85} max={120} step={5}
            unit="%"
            onChange={(v) => setTweak("fontScale", v / 100)}
          />
        </TweakSection>

        <TweakSection title="Hero Layout">
          <TweakRadio
            label="รูปแบบ"
            value={t.heroLayout}
            options={[
              { value: "editorial", label: "Editorial" },
              { value: "stacked",   label: "Centered"  },
              { value: "bleed",     label: "Full-bleed" },
            ]}
            onChange={(v) => setTweak("heroLayout", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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