// Main app — router, theme tokens, tweaks
const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "th",
  "accent": "gold",
  "heroStyle": "cinematic"
}/*EDITMODE-END*/;

// ─── Routing: page ⇄ URL path ──────────────────────────────────────
const PAGE_PATHS = { home: "", about: "about", people: "people", calendar: "calendar", dailyDhamma: "daily-dhamma", bergen: "bergen", donate: "donate", contact: "contact", events: "events", gallery: "gallery" };
const PATH_PAGES = { "": "home", about: "about", people: "people", calendar: "calendar", "daily-dhamma": "dailyDhamma", bergen: "bergen", donate: "donate", contact: "contact", events: "events", gallery: "gallery" };
const SITE_ORIGIN = "https://watthainorway.com/";

function routeBase() {
  const p = window.location.pathname;
  return p.endsWith("/") ? p : p.replace(/[^/]*$/, "");
}
function parseLocation() {
  const base = routeBase();
  let seg = window.location.pathname.slice(base.length).replace(/^\//, "").replace(/\/$/, "");
  if (!seg) return { page: "home", eventSlug: null };
  if (seg.indexOf("events/") === 0) {
    const slug = seg.slice("events/".length);
    return slug ? { page: "eventDetail", eventSlug: slug } : { page: "events", eventSlug: null };
  }
  return { page: PATH_PAGES[seg] || "home", eventSlug: null };
}
function pageFromLocation() {
  return parseLocation().page;
}

// Per-page SEO copy (Thai primary, Norwegian local, English international). Drives <title>, description, canonical, OG.
const PAGE_SEO = {
  home: {
    th: { title: "วัดไทยนอร์เวย์ · Wat Thai Norway — วัดพุทธไทยในนอร์เวย์", desc: "วัดพุทธไทยและศูนย์รวมชุมชนในนอร์เวย์ แบ่งปันธรรมะ วัฒนธรรมไทย การทำบุญ สมาธิ และกิจกรรมชุมชน ที่ Frogner ใกล้ออสโล" },
    no: { title: "Wat Thai Norge | Thailandsk buddhisttempel i Norge", desc: "Et thailandsk buddhisttempel og fellesskapssenter i Norge — buddhisme, thai-kultur, meritter, meditasjon og fellesskapsaktiviteter." },
    en: { title: "Wat Thai Norway | Thai Buddhist Temple and Community in Norway", desc: "Wat Thai Norway is a Thai Buddhist temple and community center in Norway, sharing Buddhist practice, Thai culture, merit-making, meditation, and community activities." },
  },
  about: {
    th: { title: "ประวัติวัด · วัดไทยนอร์เวย์", desc: "ประวัติความเป็นมาของวัดไทยนอร์เวย์ ตั้งแต่ก่อตั้งจนถึงปัจจุบัน" },
    no: { title: "Om oss · Wat Thai Norge", desc: "Historien om Wat Thai Norge fra grunnleggelsen til i dag." },
    en: { title: "Temple History · Wat Thai Norway", desc: "The history of Wat Thai Norway from its founding to today." },
  },
  people: {
    th: { title: "คณะสงฆ์และกรรมการ · วัดไทยนอร์เวย์", desc: "คณะสงฆ์และคณะกรรมการบริหารวัดไทยนอร์เวย์" },
    no: { title: "Munker og styre · Wat Thai Norge", desc: "Munkene og styret ved Wat Thai Norge." },
    en: { title: "Monks and Committee · Wat Thai Norway", desc: "Monks and committee members serving Wat Thai Norway." },
  },
  calendar: {
    th: { title: "ปฏิทินกิจกรรม · วัดไทยนอร์เวย์", desc: "ปฏิทินวันพระ งานบุญประเพณี และกิจกรรมของวัดไทยนอร์เวย์" },
    no: { title: "Kalender · Wat Thai Norge", desc: "Kalender med helligdager, seremonier og arrangementer ved Wat Thai Norge." },
    en: { title: "Calendar · Wat Thai Norway", desc: "Holy days, ceremonies and community events at Wat Thai Norway." },
  },
  dailyDhamma: {
    th: { title: "ธรรมประจำวัน · วัดไทยนอร์เวย์", desc: "ธรรมประจำวันเจ็ดวันและบทความธรรมะสำหรับชีวิตในนอร์เวย์ — ครอบครัว งาน ฤดูหนาว และการมาวัดครั้งแรก" },
    no: { title: "Dagens dharma · Wat Thai Norge", desc: "Ukentlig dharma og artikler for thailendere i Norge — familie, jobb, vinter og første tempelbesøk." },
    en: { title: "Daily Dhamma · Wat Thai Norway", desc: "Seven-day Dhamma and longer articles for life in Norway — family, work, winter and your first temple visit." },
  },
  bergen: {
    th: { title: "วัดไทยเบอร์เกน · วัดไทยนอร์เวย์", desc: "ข่าว กิจกรรม และ Facebook ของวัดไทยเบอร์เกน สาขาในเครือข่ายวัดไทยนอร์เวย์" },
    no: { title: "Wat Thai Bergen · Wat Thai Norge", desc: "Nyheter, aktiviteter og Facebook-oppdateringer fra Wat Thai Bergen." },
    en: { title: "Wat Thai Bergen · Wat Thai Norway", desc: "News, activities and Facebook updates from Wat Thai Bergen, connected to Wat Thai Norway." },
  },
  donate: {
    th: { title: "ร่วมทำบุญ · วัดไทยนอร์เวย์", desc: "ร่วมทำบุญและสนับสนุนวัดไทยนอร์เวย์ — กองทุนสร้างวัดและกิจกรรมต่าง ๆ" },
    no: { title: "Gi en gave · Wat Thai Norge", desc: "Støtt Wat Thai Norge med en gave — byggefond og aktiviteter." },
    en: { title: "Donate · Wat Thai Norway", desc: "Support Wat Thai Norway through donations for the temple, building fund and community activities." },
  },
  contact: {
    th: { title: "ติดต่อวัด · วัดไทยนอร์เวย์", desc: "ที่อยู่ เบอร์โทร อีเมล และเส้นทางมายังวัดไทยนอร์เวย์ ที่ Frogner" },
    no: { title: "Kontakt · Wat Thai Norge", desc: "Adresse, telefon, e-post og veibeskrivelse til Wat Thai Norge på Frogner." },
    en: { title: "Contact · Wat Thai Norway", desc: "Address, phone, email and directions to Wat Thai Norway in Frogner." },
  },
  events: {
    th: { title: "กิจกรรมวัด · วัดไทยนอร์เวย์", desc: "ภาพและเรื่องราวจากงานบุญ เทศกาล การศึกษา และชุมชนไทยในนอร์เวย์" },
    no: { title: "Arrangementer · Wat Thai Norge", desc: "Bilder og historier fra meritter, festivaler, utdanning og fellesskap ved Wat Thai Norge." },
    en: { title: "Events · Wat Thai Norway", desc: "Photos and stories from merit-making, festivals, education and community life at Wat Thai Norway." },
  },
  gallery: {
    th: { title: "แกลเลอรี · วัดไทยนอร์เวย์", desc: "ภาพกิจกรรมจากวัดไทยนอร์เวย์ — งานบุญ เทศกาล ชุมชน และการศึกษา" },
    no: { title: "Galleri · Wat Thai Norge", desc: "Bilder fra Wat Thai Norge — meritter, festivaler, fellesskap og utdanning." },
    en: { title: "Gallery · Wat Thai Norway", desc: "Photo gallery from Wat Thai Norway — ceremonies, festivals, community and education." },
  },
  eventDetail: {
    th: { title: "กิจกรรม · วัดไทยนอร์เวย์", desc: "รายละเอียดและภาพกิจกรรมจากวัดไทยนอร์เวย์" },
    no: { title: "Arrangement · Wat Thai Norge", desc: "Detaljer og bilder fra et arrangement ved Wat Thai Norge." },
    en: { title: "Event · Wat Thai Norway", desc: "Details and photos from an event at Wat Thai Norway." },
  },
};

const ACCENT_PALETTES = {
  gold:  {
    accent: "#C69A2B",
    accentDeep: "#765512",
    bg: "#fbf8f1",
    bgDeep: "#f1eadc",
    ink: "#2b2118",
    muted: "#675c4d",
    line: "rgba(43,33,24,0.11)",
    nordic: "#315A73",
    nordicSoft: "#e8f0f3",
    forest: "#526246",
    forestSoft: "#edf2e8",
    sakura: "#B96F7F",
    sakuraSoft: "#f7e7e7",
    goldSoft: "#f6edcf",
  },
  red:   { accent: "#8B1A1A", accentDeep: "#6e1414", bg: "#faf5f3", bgDeep: "#f1e7e4", ink: "#1c0e0a", muted: "#6a4843", line: "rgba(28,14,10,0.10)" },
  green: { accent: "#3d5a3d", accentDeep: "#2b432b", bg: "#f6f6f0", bgDeep: "#e9ebde", ink: "#1c2419", muted: "#525a4a", line: "rgba(28,36,25,0.10)" },
  navy:  { accent: "#C9A227", accentDeep: "#a98718", bg: "#f4f6fa", bgDeep: "#e7ecf3", ink: "#0e1d3a", muted: "#4a5a78", line: "rgba(14,29,58,0.10)" },
};

function MobileBottomActions({ t, setPage }) {
  const lang = t.locale;
  const labels = {
    contact: lang === "th" ? "ติดต่อวัด" : lang === "no" ? "Kontakt" : "Contact",
    donate: lang === "th" ? "ทำบุญ" : lang === "no" ? "Gi en gave" : "Donate",
    directions: lang === "th" ? "เส้นทาง" : lang === "no" ? "Veien hit" : "Directions",
  };
  const directionsUrl = (window.WTN_COMMUNITY && window.WTN_COMMUNITY.maps) || "https://www.google.com/maps/search/?api=1&query=Wat+Thai+Norway+Trondheimsvegen+582+2016+Frogner";
  const buttonBase = {
    minHeight: "56px",
    borderRadius: "18px",
    border: "1px solid rgba(43,33,24,0.10)",
    fontFamily: "var(--font-body)",
    fontSize: "12px",
    letterSpacing: "0.03em",
    cursor: "pointer",
    textDecoration: "none",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    gap: "4px",
    WebkitTapHighlightColor: "transparent",
  };

  return (
    <div
      className="wn-mobile-bottom-actions"
      aria-label={lang === "th" ? "ปุ่มลัดสำหรับมือถือ" : lang === "no" ? "Hurtigvalg på mobil" : "Mobile quick actions"}
      style={{
        display: "none",
        position: "fixed",
        left: "16px",
        right: "16px",
        bottom: "14px",
        zIndex: 90,
        gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
        gap: "8px",
        padding: "9px",
        borderRadius: "28px",
        background: "rgba(251,248,241,0.92)",
        border: "1px solid rgba(43,33,24,0.12)",
        boxShadow: "0 18px 46px rgba(43,33,24,0.22)",
        backdropFilter: "blur(14px)",
      }}
    >
      <button
        onClick={() => setPage("contact")}
        style={{ ...buttonBase, background: "var(--bg)", color: "var(--ink)" }}
      >
        <span aria-hidden="true" style={{ fontSize: "17px", lineHeight: 1 }}>☎</span>
        <span>{labels.contact}</span>
      </button>
      <button
        onClick={() => setPage("donate")}
        style={{ ...buttonBase, background: "var(--accent)", color: "#191107", border: "1px solid var(--accent)", boxShadow: "0 10px 24px rgba(198,154,43,0.22)" }}
      >
        <span aria-hidden="true" style={{ fontSize: "17px", lineHeight: 1 }}>•</span>
        <span>{labels.donate}</span>
      </button>
      <a
        href={directionsUrl}
        target="_blank"
        rel="noopener noreferrer"
        style={{ ...buttonBase, background: "var(--nordic)", color: "var(--bg)", border: "1px solid var(--nordic)" }}
      >
        <span aria-hidden="true" style={{ fontSize: "17px", lineHeight: 1 }}>⌖</span>
        <span>{labels.directions}</span>
      </a>
    </div>
  );
}

function App() {
  const [t, setTweaksState] = useStateApp(TWEAK_DEFAULTS);
  const setTweak = (key, value) => setTweaksState((prev) => ({ ...prev, [key]: value }));
  const [page, setPageState] = useStateApp(() => parseLocation().page);
  const [eventSlug, setEventSlugState] = useStateApp(() => parseLocation().eventSlug);
  const tr = window.TRANSLATIONS[t.lang] || window.TRANSLATIONS.th;
  const palette = ACCENT_PALETTES[t.accent] || ACCENT_PALETTES.gold;
  const heroDark = page === "home" && t.heroStyle !== "editorial";

  // Navigate: update state + push a real URL (no reload). Back/forward via popstate.
  const setPage = (next, opts) => {
    opts = opts || {};
    const slug = next === "eventDetail" ? (opts.slug || null) : null;
    setPageState(next);
    setEventSlugState(slug);
    let pathSeg = "";
    if (next === "eventDetail" && slug) pathSeg = "events/" + slug;
    else pathSeg = PAGE_PATHS[next] || "";
    const url = routeBase() + pathSeg;
    try {
      if (window.location.pathname !== url) {
        window.history.pushState({ page: next, eventSlug: slug }, "", url || routeBase());
      }
    } catch (e) { /* sandbox may block pushState; state still updates */ }
  };

  useEffectApp(() => {
    const onPop = () => {
      const loc = parseLocation();
      setPageState(loc.page);
      setEventSlugState(loc.eventSlug);
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Per-page SEO: title, description, canonical, OG, <html lang>
  useEffectApp(() => {
    const lang = ["th", "no", "en"].includes(t.lang) ? t.lang : "th";
    document.documentElement.lang = lang;
    let seo = (PAGE_SEO[page] || PAGE_SEO.home)[lang] || PAGE_SEO[page].th;
    let url = SITE_ORIGIN + (page === "eventDetail" && eventSlug ? "events/" + eventSlug : (PAGE_PATHS[page] || ""));
    let ogImage = SITE_ORIGIN.replace(/\/$/, "") + "/assets/life/sakura-sign.jpg";

    let ogAlt = "ป้ายวัดไทยนอร์เวย์ท่ามกลางดอกซากุระ · Wat Thai Norway sign framed by cherry blossoms";
    if (page === "eventDetail" && eventSlug && window.TempleEventsData) {
      const event = window.TempleEventsData.getBySlug(eventSlug);
      if (event) {
        seo = { title: event.seoTitle, desc: event.seoDescription };
        if (event.coverImage) ogImage = SITE_ORIGIN.replace(/\/$/, "") + event.coverImage;
        ogAlt = event.thaiTitle || event.title;
      }
    }

    document.title = seo.title;
    const setMeta = (sel, attr, val) => { const el = document.querySelector(sel); if (el) el.setAttribute(attr, val); };
    setMeta('meta[name="description"]', "content", seo.desc);
    setMeta('link[rel="canonical"]', "href", url);
    setMeta('meta[property="og:title"]', "content", seo.title);
    setMeta('meta[property="og:description"]', "content", seo.desc);
    setMeta('meta[property="og:url"]', "content", url);
    setMeta('meta[property="og:locale"]', "content", lang === "no" ? "nb_NO" : lang === "en" ? "en_US" : "th_TH");
    setMeta('meta[property="og:image"]', "content", ogImage);
    setMeta('meta[property="og:image:alt"]', "content", ogAlt);
    setMeta('meta[name="twitter:image"]', "content", ogImage);
    setMeta('meta[name="twitter:title"]', "content", seo.title);
    setMeta('meta[name="twitter:description"]', "content", seo.desc);
  }, [page, eventSlug, t.lang]);

  // Apply CSS variables
  useEffectApp(() => {
    const root = document.documentElement;
    Object.entries(palette).forEach(([k, v]) => {
      const cssKey = k === "accent" ? "--accent"
        : k === "accentDeep" ? "--accent-deep"
        : k === "bg" ? "--bg"
        : k === "bgDeep" ? "--bg-deep"
        : k === "ink" ? "--ink"
        : k === "muted" ? "--muted"
        : k === "line" ? "--line"
        : k === "nordic" ? "--nordic"
        : k === "nordicSoft" ? "--nordic-soft"
        : k === "forest" ? "--forest"
        : k === "forestSoft" ? "--forest-soft"
        : k === "sakura" ? "--sakura"
        : k === "sakuraSoft" ? "--sakura-soft"
        : k === "goldSoft" ? "--gold-soft" : null;
      if (cssKey) root.style.setProperty(cssKey, v);
    });
    root.style.setProperty("--font-display", tr.fontStack);
    root.style.setProperty("--font-body", tr.bodyFontStack);
  }, [t.accent, t.lang]);

  // Scroll to top on page change
  useEffectApp(() => {
    window.scrollTo({ top: 0, behavior: "auto" });
  }, [page]);

  return (
    <div className="wn-app-shell" data-screen-label={page} style={{ backgroundColor: "var(--bg)", color: "var(--ink)", fontFamily: "var(--font-body)" }}>
      <Header t={tr} page={page} setPage={setPage} onDark={heroDark} lang={t.lang} onLang={(v) => setTweak("lang", v)} />
      <main id="main-content" tabIndex="-1">
      {page === "home" && <HomePage t={tr} setPage={setPage} heroStyle={t.heroStyle} />}
      {page === "about" && <AboutPage t={tr} />}
      {page === "people" && <PeoplePage t={tr} />}
      {page === "calendar" && <CalendarPage t={tr} setPage={setPage} />}
      {page === "dailyDhamma" && <DailyDhammaPage t={tr} />}
      {page === "bergen" && <BergenPage t={tr} />}
      {page === "donate" && <DonatePage t={tr} />}
      {page === "contact" && <ContactPage t={tr} />}
      {page === "events" && <EventsPage t={tr} setPage={setPage} />}
      {page === "eventDetail" && <EventDetailPage t={tr} setPage={setPage} eventSlug={eventSlug} />}
      {page === "gallery" && <GalleryPage t={tr} setPage={setPage} />}
      </main>
      <Footer t={tr} setPage={setPage} />
      <MobileBottomActions t={tr} setPage={setPage} />

    </div>
  );
}

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