const { useState, useEffect, useMemo } = React;

  const L = (o, l) => (typeof o === "string" ? o : o?.[l] ?? o?.zh);

  const Ic = {
    drop: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 3 C 12 3 5 11 5 16 A 7 7 0 0 0 19 16 C 19 11 12 3 12 3 Z"/></svg>,
    flame: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 3 C 12 8 15 9 15 13 A 3 3 0 0 1 9 13 C 9 10 11 9 12 3 Z"/></svg>,
    leaf: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 19 C 5 10 10 4 19 4 C 19 13 13 19 5 19 Z"/><path d="M5 19 L 14 10"/></svg>,
    check: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12l4 4L19 6"/></svg>,
    phone: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 3 h 4 l 2 5 l -3 2 c 1 4 4 7 8 8 l 2 -3 l 5 2 v 4 c 0 1 -1 2 -2 2 C 11 23 1 13 1 5 c 0 -1 1 -2 2 -2"/></svg>,
    pin: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 22 s 8 -8 8 -14 a 8 8 0 0 0 -16 0 c 0 6 8 14 8 14 z"/><circle cx="12" cy="8" r="3"/></svg>,
    mail: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>,
    clock: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>,
    wa: () => <svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.3c-.3-.1-1.6-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.8 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.2-.6-1.5-.9-2-.2-.5-.5-.5-.6-.5-.2 0-.4 0-.6 0-.2 0-.5.1-.8.4-.3.3-1.1 1-1.1 2.5s1.1 2.9 1.3 3.1c.2.2 2.2 3.4 5.4 4.7 3.2 1.3 3.2.9 3.8.8.6-.1 1.6-.7 1.8-1.3.2-.6.2-1.2.2-1.3-.1-.1-.3-.2-.6-.3zM12 2a10 10 0 0 0-8.5 15.2l-1.4 5.1 5.3-1.4A10 10 0 1 0 12 2z"/></svg>,
    menu: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  };

  // Brand logo — uploaded logo.jpg in the theme folder.
  // Theme URL is injected by functions.php as window.AftertailAPI.themeUrl.
  function Logo() {
    const base = (typeof window !== "undefined" && window.AftertailAPI && window.AftertailAPI.themeUrl) || "";
    return (
      <img
        src={base + "/logo.jpg"}
        alt="尾站 Aftertail"
        style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }}
      />
    );
  }

  // Cloud SVG
  function Cloud({ size = 120, opacity = 1 }) {
    return (
      <svg viewBox="0 0 200 100" width={size} style={{opacity}}>
        <g fill="white">
          <ellipse cx="60" cy="60" rx="40" ry="30"/>
          <ellipse cx="110" cy="55" rx="50" ry="35"/>
          <ellipse cx="150" cy="65" rx="35" ry="28"/>
          <ellipse cx="100" cy="45" rx="35" ry="28"/>
        </g>
      </svg>
    );
  }

  // Hero pet illustration — stylized cat/dog looking up
  function HeroPet() {
    return (
      <svg viewBox="0 0 220 240" fill="none">
        <defs>
          <linearGradient id="petFur" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#6b86a0"/>
            <stop offset="100%" stopColor="#2e5277"/>
          </linearGradient>
        </defs>
        {/* body silhouette — pet sitting, looking up */}
        <ellipse cx="110" cy="200" rx="75" ry="28" fill="rgba(27, 58, 86, 0.15)"/>
        <path d="M 60 190 Q 50 140 80 120 Q 90 100 110 100 Q 130 100 140 120 Q 170 140 160 190 Z" fill="url(#petFur)"/>
        {/* head */}
        <circle cx="110" cy="95" r="38" fill="url(#petFur)"/>
        {/* ears */}
        <path d="M 80 70 L 75 45 L 95 65 Z" fill="url(#petFur)"/>
        <path d="M 140 70 L 145 45 L 125 65 Z" fill="url(#petFur)"/>
        <path d="M 82 67 L 80 55 L 90 63 Z" fill="#f4b17a" opacity="0.5"/>
        <path d="M 138 67 L 140 55 L 130 63 Z" fill="#f4b17a" opacity="0.5"/>
        {/* eyes closed/peaceful — small arcs */}
        <path d="M 95 90 Q 100 93 105 90" stroke="#f0f7ff" strokeWidth="2" fill="none" strokeLinecap="round"/>
        <path d="M 115 90 Q 120 93 125 90" stroke="#f0f7ff" strokeWidth="2" fill="none" strokeLinecap="round"/>
        {/* nose */}
        <ellipse cx="110" cy="103" rx="3" ry="2" fill="#f0f7ff"/>
        {/* mouth */}
        <path d="M 110 107 Q 107 112 104 110 M 110 107 Q 113 112 116 110" stroke="#f0f7ff" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
        {/* whiskers */}
        <g stroke="#f0f7ff" strokeWidth="1" strokeLinecap="round" opacity="0.6">
          <line x1="80" y1="105" x2="95" y2="105"/>
          <line x1="80" y1="110" x2="95" y2="108"/>
          <line x1="125" y1="105" x2="140" y2="105"/>
          <line x1="125" y1="108" x2="140" y2="110"/>
        </g>
        {/* collar with small tag */}
        <rect x="88" y="128" width="44" height="5" rx="2" fill="#f4b17a"/>
        <circle cx="110" cy="137" r="4" fill="#ffd59a" stroke="#f4b17a" strokeWidth="1"/>
        {/* small star/sparkle above head — gentle */}
        <g opacity="0.7">
          <circle cx="170" cy="50" r="2" fill="#ffd59a"/>
          <circle cx="50" cy="60" r="1.5" fill="#ffd59a"/>
          <circle cx="160" cy="90" r="1" fill="#ffd59a"/>
        </g>
      </svg>
    );
  }

  function Mountains() {
    return (
      <svg viewBox="0 0 800 300" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
        <path d="M0 180 L 120 120 L 220 160 L 320 100 L 420 170 L 520 120 L 640 160 L 750 110 L 800 150 L 800 300 L 0 300 Z" fill="#b9ddf5" opacity="0.5"/>
        <path d="M0 220 L 100 170 L 200 200 L 320 160 L 440 210 L 560 170 L 700 200 L 800 170 L 800 300 L 0 300 Z" fill="#7cb7e4" opacity="0.6"/>
        <path d="M0 270 L 800 270 L 800 300 L 0 300 Z" fill="#4d93cc" opacity="0.3"/>
      </svg>
    );
  }

  // ============= COPY =============
  const T = {
    nav: {
      about: { zh: "關於我們", en: "About" },
      services: { zh: "服務", en: "Services" },
      pricing: { zh: "價錢", en: "Pricing" },
      memorial: { zh: "紀念品", en: "Keepsakes" },
      blog: { zh: "文章", en: "Blog" },
      booking: { zh: "預約", en: "Booking" },
      faq: { zh: "常見問題", en: "FAQ" },
      contact: { zh: "聯絡", en: "Contact" },
    },
  };

  const PAGES = [
    { id: "about", href: "/about/", zh: "關於我們", en: "About" },
    { id: "services", href: "/services/", zh: "服務", en: "Services" },
    { id: "pricing", href: "/pricing/", zh: "價錢", en: "Pricing" },
    { id: "memorial", href: "/memorial/", zh: "紀念品", en: "Keepsakes" },
    { id: "blog", href: "/blog/", zh: "文章", en: "Blog" },
    { id: "booking", href: "/booking/", zh: "預約", en: "Booking" },
    { id: "faq", href: "/faq/", zh: "常見問題", en: "FAQ" },
    { id: "contact", href: "/contact/", zh: "聯絡", en: "Contact" },
  ];

  // ============= NAV =============
  function UrgencyBar({ lang }) {
    return (
      <div className="urgency">
        <span className="item"><span className="dot"></span>{lang === "zh" ? "24 小時待命" : "24/7 STANDBY"}</span>
        <span className="sep">·</span>
        <span className="item">{lang === "zh" ? "最快 30 分鐘上門接收" : "PICKUP WITHIN 30 MIN"}</span>
        <span className="sep item-lg">·</span>
        <span className="item item-lg">{lang === "zh" ? "全港 18 區免費接送" : "FREE PICKUP · ALL 18 DISTRICTS"}</span>
      </div>
    );
  }

  function Nav({ lang, setLang, onMenu, section }) {
    return (
      <nav className="topnav">
        <div className="nav-inner">
          <a href="/" className="brand">
            <div className="brand-mark"><Logo/></div>
            <div>
              <div className="brand-cn">尾站</div>
              <div className="brand-en">Aftertail · Pet Aftercare</div>
            </div>
          </a>
          <div className="nav-links">
            {PAGES.map(page => (
              <a key={page.id} href={page.href} className={section === page.id ? "active" : ""}>
                {lang === "zh" ? page.zh : page.en}
              </a>
            ))}
          </div>
          <div className="nav-cta">
            <div className="lang-tog">
              <button className={lang === "zh" ? "on" : ""} onClick={() => setLang("zh")}>中文</button>
              <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            </div>
            <a href="tel:91234567" className="hotline">
              <Ic.phone/>
              <span>9123 4567</span>
            </a>
            <button className="hamburger" onClick={onMenu} aria-label="menu"><Ic.menu/></button>
          </div>
        </div>
      </nav>
    );
  }

  function MobileMenu({ lang, open, onClose, section }) {
    return (
      <div className={"mmenu" + (open ? " open" : "")}>
        <div className="mmenu-head">
          <div className="brand">
            <div className="brand-mark"><Logo/></div>
            <div><div className="brand-cn">尾站</div></div>
          </div>
          <button onClick={onClose} aria-label="close">×</button>
        </div>
        <div className="mmenu-links">
          {PAGES.map(l => (
            <a key={l.href} href={l.href} onClick={onClose} className={section === l.id ? "active" : ""}>
              <span>{lang === "zh" ? l.zh : l.en}</span>
              <span className="en">{lang === "zh" ? l.en : l.zh}</span>
            </a>
          ))}
        </div>
        <div className="mmenu-cta">
          <a href="tel:91234567" className="btn btn-primary"><Ic.phone/> {lang === "zh" ? "24 小時熱線 9123 4567" : "24h Hotline · 9123 4567"}</a>
        </div>
      </div>
    );
  }

  // ============= HERO =============
  function Hero({ lang }) {
    return (
      <section className="hero" id="top">
        <div className="sky-layer">
          <div className="cloud slow" style={{top:"12%", left:"-15%"}}><Cloud size={180} opacity={0.85}/></div>
          <div className="cloud mid" style={{top:"32%", left:"-25%", animationDelay:"-40s"}}><Cloud size={140} opacity={0.7}/></div>
          <div className="cloud fast" style={{top:"55%", left:"-20%", animationDelay:"-20s"}}><Cloud size={100} opacity={0.55}/></div>
          <div className="cloud slow" style={{top:"8%", left:"-30%", animationDelay:"-90s"}}><Cloud size={220} opacity={0.9}/></div>
        </div>
        <div className="hero-inner">
          <div className="wrap">
            <div className="hero-grid">
              <div>
                <div className="hero-eyebrow">
                  <span className="pulse"></span>
                  <span className="eyebrow">{lang === "zh" ? "香港寵物善終 · Est. 2018" : "Hong Kong Pet Aftercare · Est. 2018"}</span>
                </div>
                <h1>
                  {lang === "zh" ? (
                    <>
                      <span className="cn">溫柔的尾站</span>
                      <em>A gentle</em><br/>last stop.
                    </>
                  ) : (
                    <>
                      <span className="cn">A gentle last stop.</span>
                      <em>溫柔的</em><br/>尾站。
                    </>
                  )}
                </h1>
                <div className="hero-verse">
                  {lang === "zh" ? (
                    <>
                      香港寵物火化及追思服務。<br/>
                      在最後一程，給牠應得的尊重與溫柔。
                      <span className="v-cn">Pet cremation & memorial in Hong Kong.</span>
                    </>
                  ) : (
                    <>
                      Pet cremation & memorial services.<br/>
                      Dignity and warmth, on the final journey home.
                      <span className="v-cn">香港寵物火化及追思服務</span>
                    </>
                  )}
                </div>
                <div className="hero-actions">
                  <a href="/booking/" className="btn btn-primary">{lang === "zh" ? "預約服務" : "Book Service"} →</a>
                  <a href="tel:91234567" className="btn btn-ghost"><Ic.phone/> {lang === "zh" ? "24 小時熱線" : "24h Hotline"}</a>
                </div>
                <div className="promise-row">
                  <div className="pchip">
                    <span className="pchip-num">24</span>
                    <span className="pchip-text">
                      <span className="pchip-unit">Hours</span>
                      <span className="pchip-label">{lang === "zh" ? "全年無休待命" : "Always standby"}</span>
                    </span>
                  </div>
                  <div className="pchip">
                    <span className="pchip-num">30</span>
                    <span className="pchip-text">
                      <span className="pchip-unit">Minutes</span>
                      <span className="pchip-label">{lang === "zh" ? "最快上門接收" : "Fastest pickup"}</span>
                    </span>
                  </div>
                  <div className="pchip">
                    <span className="pchip-num">18</span>
                    <span className="pchip-text">
                      <span className="pchip-unit">Districts</span>
                      <span className="pchip-label">{lang === "zh" ? "全港免費接送" : "Free HK pickup"}</span>
                    </span>
                  </div>
                </div>
              </div>
              <div className="hero-art">
                <div className="sun"></div>
                <div className="mountains"><Mountains/></div>
                <div style={{position:"absolute", top:"22%", left:"14%", opacity:0.9}}><Cloud size={90}/></div>
                <div style={{position:"absolute", top:"38%", right:"8%", opacity:0.7}}><Cloud size={60}/></div>
                <div style={{position:"absolute", top:"14%", right:"32%", opacity:0.5}}><Cloud size={40}/></div>
                <div className="pet"><HeroPet/></div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // ============= ABOUT =============
  function About({ lang }) {
    const stats = [
      { n: "1,800", l: lang === "zh" ? "服務家庭" : "Families served", s: "2018–2026" },
      { n: "24", suf: "h", l: lang === "zh" ? "熱線待命" : "Hotline standby" },
      { n: "30", suf: "min", l: lang === "zh" ? "平均到場" : "Avg. arrival" },
      { n: "98", suf: "%", l: lang === "zh" ? "五星好評" : "5-star reviews" },
    ];
    return (
      <section id="about">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow">{lang === "zh" ? "關於尾站" : "About Aftertail"}</div>
            </div>
            <div>
              <h2>
                {lang === "zh" ? (
                  <>不是終點，<em>是</em>溫柔的尾站。<span className="tc" style={{color:"var(--muted)", fontSize:"0.5em", marginTop:12, fontFamily:"var(--serif)", fontStyle:"italic"}}>Not an end — a gentle last stop.</span></>
                ) : (
                  <>Not an end — <em>a</em> gentle last stop.<span className="tc" style={{color:"var(--muted)", fontSize:"0.55em", marginTop:12}}>不是終點，是溫柔的尾站。</span></>
                )}
              </h2>
              <p>
                {lang === "zh"
                  ? "「尾站」的意思，是這條路上最後一個停靠點。我們相信，離別不一定灰暗。像在晴天的小山頂，風吹過，雲飄過，毛孩靜靜地抬頭望著天——這就是我們想給每一位家人的告別。"
                  : "A \"last stop\" is the final landing on a journey. We believe farewells don\u2019t have to be dark. Picture a hilltop on a bright day — wind, drifting clouds, your pet gazing up at the sky. That\u2019s the goodbye we wish to give every family."}
              </p>
            </div>
          </div>
          <div className="about-stats">
            {stats.map((s, i) => (
              <div className="stat" key={i}>
                <div className="n">{s.n}{s.suf && <em>{s.suf}</em>}</div>
                <div className="l">{s.l}</div>
                {s.s && <div className="sub">{s.s}</div>}
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  // ============= SERVICES =============
  function Services({ lang }) {
    const data = {
      water: {
        title: { zh: "水化", en: "Aquamation" },
        en: "Alkaline Hydrolysis",
        tag: { zh: "最環保", en: "MOST ECO" },
        desc: { zh: "以溫水與微量鹼性溶液模擬自然分解。碳排放僅為火化的 1/10，沒有火、沒有煙，過程寧靜。", en: "Gentle alkaline hydrolysis mimics the natural decomposition process. 1/10th the carbon footprint of cremation — no fire, no smoke, a quiet farewell." },
        features: [
          { zh: "碳排放僅 1/10", en: "1/10 carbon footprint" },
          { zh: "過程無煙無火", en: "No smoke, no flame" },
          { zh: "骨灰量多 20%", en: "20% more ashes returned" },
          { zh: "適合所有體型", en: "Suitable for all sizes" },
        ],
      },
      fire: {
        title: { zh: "火化", en: "Cremation" },
        en: "Traditional Cremation",
        tag: { zh: "傳統", en: "TRADITIONAL" },
        desc: { zh: "傳統火化服務，提供個別火化或集體火化兩種選擇，全程專人陪同，可選擇出席或視像觀禮。", en: "Traditional cremation — choose individual or communal. A dedicated attendant accompanies the whole process, with optional on-site or video viewing." },
        features: [
          { zh: "個別／集體可選", en: "Individual or communal" },
          { zh: "可現場或視像觀禮", en: "On-site or video viewing" },
          { zh: "約 60–90 分鐘完成", en: "Completes in 60–90 min" },
          { zh: "提供紙鶴摺紙儀式", en: "Optional crane folding ritual" },
        ],
      },
    };
    return (
      <section id="services" className="services-section">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "我們的服務" : "Our Services"}</div></div>
            <div>
              <h2>
                {lang === "zh" ? <>火化——<br/><em>以家人之禮</em>相送。</> : <>Cremation —<br/>a farewell <em>given as family</em>.</>}
              </h2>
              <p>{lang === "zh" ? "一份心意，為牠選擇最合適的告別方式。" : "One intent — the farewell that feels right for them."}</p>
            </div>
          </div>
          <div className="services-dual">
            {/* 目前只提供火化;恢復水化時改返 ["water", "fire"] */}
            {["fire"].map(m => {
              const d = data[m];
              return (
                <div key={m} className="s-card">
                  <div className={"s-visual " + m}>
                    {m === "water" ? <WaterVisual/> : <FireVisual/>}
                  </div>
                  <div className="s-body">
                    <span className={"s-tag " + (m === "water" ? "eco" : "trad")}>
                      {m === "water" ? <Ic.leaf/> : <Ic.flame/>}
                      {L(d.tag, lang)}
                    </span>
                    <h3>{L(d.title, lang)} <span className="en">{d.en}</span></h3>
                    <p className="desc">{L(d.desc, lang)}</p>
                    <ul className="s-feat">
                      {d.features.map((f, i) => (
                        <li key={i}><span className="k"><Ic.check/></span>{L(f, lang)}</li>
                      ))}
                    </ul>
                    <a href="/pricing/" className="btn btn-ghost">{lang === "zh" ? "查看價錢" : "See pricing"} →</a>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    );
  }

  function WaterVisual() {
    return (
      <svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
        <defs>
          <radialGradient id="wg" cx="50%" cy="55%">
            <stop offset="0%" stopColor="#ffffff" stopOpacity="0.9"/>
            <stop offset="100%" stopColor="#b9ddf5" stopOpacity="0"/>
          </radialGradient>
        </defs>
        <rect width="400" height="250" fill="url(#wg)"/>
        {[0, 1, 2, 3, 4].map(i => (
          <circle key={i} cx="200" cy="140" r={30 + i * 28} fill="none" stroke="#4d93cc" strokeWidth="1" opacity={0.4 - i * 0.07}>
            <animate attributeName="r" from={30 + i * 28} to={60 + i * 28} dur="4s" repeatCount="indefinite" begin={`${i * 0.3}s`}/>
            <animate attributeName="opacity" from={0.4 - i * 0.07} to="0" dur="4s" repeatCount="indefinite" begin={`${i * 0.3}s`}/>
          </circle>
        ))}
        <circle cx="200" cy="140" r="8" fill="#4d93cc"/>
        {/* leaf */}
        <g transform="translate(320, 60)" opacity="0.7">
          <path d="M 0 15 Q 10 -5 25 0 Q 25 15 10 20 Z" fill="#7dd89a"/>
        </g>
      </svg>
    );
  }

  function FireVisual() {
    return (
      <svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
        <defs>
          <radialGradient id="fg" cx="50%" cy="70%">
            <stop offset="0%" stopColor="#ffd59a" stopOpacity="0.9"/>
            <stop offset="100%" stopColor="#f4b17a" stopOpacity="0"/>
          </radialGradient>
        </defs>
        <rect width="400" height="250" fill="url(#fg)"/>
        <g transform="translate(200, 175)">
          <path d="M 0 0 Q -20 -40 -10 -60 Q 0 -80 0 -100 Q 10 -80 20 -60 Q 30 -40 0 0 Z" fill="#f4b17a" opacity="0.8">
            <animate attributeName="d" values="M 0 0 Q -20 -40 -10 -60 Q 0 -80 0 -100 Q 10 -80 20 -60 Q 30 -40 0 0 Z; M 0 0 Q -22 -42 -8 -62 Q 2 -82 0 -95 Q 12 -82 22 -58 Q 28 -40 0 0 Z; M 0 0 Q -20 -40 -10 -60 Q 0 -80 0 -100 Q 10 -80 20 -60 Q 30 -40 0 0 Z" dur="2s" repeatCount="indefinite"/>
          </path>
          <path d="M 0 0 Q -10 -25 -5 -40 Q 0 -55 0 -70 Q 5 -55 10 -40 Q 15 -25 0 0 Z" fill="#ffd59a">
            <animate attributeName="d" values="M 0 0 Q -10 -25 -5 -40 Q 0 -55 0 -70 Q 5 -55 10 -40 Q 15 -25 0 0 Z; M 0 0 Q -12 -27 -3 -42 Q 2 -55 0 -65 Q 6 -55 12 -38 Q 14 -25 0 0 Z; M 0 0 Q -10 -25 -5 -40 Q 0 -55 0 -70 Q 5 -55 10 -40 Q 15 -25 0 0 Z" dur="2s" repeatCount="indefinite"/>
          </path>
        </g>
      </svg>
    );
  }

  // ============= PROCESS =============
  function Process({ lang }) {
    const steps = [
      { zh: "聯絡我們", en: "Contact", d: { zh: "24 小時熱線、WhatsApp 或網上即時預約。", en: "24h hotline, WhatsApp or instant online booking." } },
      { zh: "上門接送", en: "Pickup", d: { zh: "最快 30 分鐘到達，免費覆蓋全港 18 區。", en: "Arrival within 30 minutes, free across all 18 HK districts." } },
      { zh: "告別儀式", en: "Farewell", d: { zh: "安排個別告別室，家人可陪同最後一程。", en: "Private farewell room, family can accompany the final moments." } },
      { zh: "火化", en: "Aftercare", d: { zh: "按預約的服務進行，過程可視像陪伴。", en: "As booked. Video accompaniment available throughout." } },
      { zh: "交還骨灰", en: "Return", d: { zh: "翌日安排領取或送回府上，附證書與紀念相。", en: "Next-day collection or delivery, with certificate and memorial print." } },
    ];
    return (
      <section id="process" className="process-section">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "服務流程" : "Our Process"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>五步，<em>安心</em>同行。</> : <>Five steps, <em>walked</em> together.</>}</h2>
              <p>{lang === "zh" ? "由第一通電話，到接毛孩回家，每一步都有專人陪伴。" : "From the first call to returning your companion home — every step, accompanied."}</p>
            </div>
          </div>
          <div className="process-steps">
            {steps.map((s, i) => (
              <div className="pstep" key={i}>
                <div className="dot">{i + 1}</div>
                <div>
                  <h4>{lang === "zh" ? s.zh : s.en}<span className="en">{lang === "zh" ? s.en : s.zh}</span></h4>
                  <p>{L(s.d, lang)}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  // ============= PRICING =============
  function Pricing({ lang }) {
    const [mode, setMode] = useState("fire");
    const [weight, setWeight] = useState(8);

    const tiers = [
      { id: "c", n: { zh: "集體", en: "Communal" }, en: "Communal", r: { zh: "不分體重", en: "All sizes" }, amt: 980, per: { zh: "不保留骨灰", en: "Ashes not returned" },
        feats: [
          { zh: "上門接送（市區）", en: "Urban pickup" },
          { zh: "集體儀式", en: "Communal rite" },
          { zh: "紀念證書", en: "Memorial certificate" },
          { zh: "毛孩相框", en: "Memorial photo print" },
        ],
      },
      { id: "i", n: { zh: "個別", en: "Individual" }, en: "Individual", r: { zh: "按體重計算", en: "By weight" }, amt: null, per: { zh: "可保留骨灰", en: "Ashes returned" }, feat: true,
        feats: [
          { zh: "上門接送（全港）", en: "HK-wide pickup" },
          { zh: "個別告別室（30 分鐘）", en: "Private room (30 min)" },
          { zh: "全程可視像觀禮", en: "Live video viewing" },
          { zh: "骨灰罐一個", en: "Urn included" },
          { zh: "證書 + 相框 + 紙鶴", en: "Certificate, photo & crane" },
        ],
      },
      { id: "p", n: { zh: "尊尚", en: "Premium" }, en: "Premium", r: { zh: "全包套餐", en: "All inclusive" }, amt: 6800, per: { zh: "紀念品全套", en: "Full keepsake set" },
        feats: [
          { zh: "專車接送（含夜間）", en: "Priority 24h pickup" },
          { zh: "個別告別室（60 分鐘）", en: "Private room (60 min)" },
          { zh: "鮮花佈置 + 鋼琴音樂", en: "Floral setting & piano" },
          { zh: "手工骨灰罐", en: "Hand-crafted urn" },
          { zh: "爪印 + 毛髮紀念品", en: "Paw print & fur keepsake" },
          { zh: "追思短片製作", en: "Memorial video produced" },
        ],
      },
    ];

    const calcPrice = (w, m) => {
      // simplified model: water slightly pricier
      const base = m === "water" ? 1800 : 1500;
      const perKg = m === "water" ? 180 : 160;
      return Math.round(base + Math.max(0, w - 2) * perKg);
    };

    return (
      <section id="pricing" className="pricing-section">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "價錢套餐" : "Pricing"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>明碼實價，<em>無隱藏</em>收費。</> : <>Clear pricing, <em>no</em> hidden fees.</>}</h2>
              <p>{lang === "zh" ? "三套方案適合不同需要；個別套餐按體重計算，可即時試算。" : "Three packages for different needs. Individual is priced by weight — try the calculator below."}</p>
            </div>
          </div>

          <div className="pricing-grid">
            {tiers.map(t => (
              <div key={t.id} className={"price-card" + (t.feat ? " feat" : "")}>
                {t.feat && <div className="flag">{lang === "zh" ? "最受歡迎" : "MOST CHOSEN"}</div>}
                <h3>{L(t.n, lang)} <span className="en">{t.en}</span></h3>
                <div className="range">{L(t.r, lang)}</div>
                <div className="amt">
                  <span className="c">HK$</span>
                  {t.amt ?? (lang === "zh" ? <span style={{fontSize:"0.55em"}}>由 {calcPrice(2, "fire")} 起</span> : <span style={{fontSize:"0.55em"}}>from {calcPrice(2, "fire")}</span>)}
                </div>
                <div className="per">{L(t.per, lang)}</div>
                <ul>
                  {t.feats.map((f, i) => (
                    <li key={i}><span className="c"><Ic.check/></span>{L(f, lang)}</li>
                  ))}
                </ul>
                <a href="/booking/" className="btn btn-primary">{lang === "zh" ? "選擇此方案" : "Choose this"} →</a>
              </div>
            ))}
          </div>

          {/* Calculator */}
          <div className="calc">
            <div className="calc-head">
              <div>
                <h4>{lang === "zh" ? "按體重試算（個別）" : "By-weight calculator (Individual)"}</h4>
                <p>{lang === "zh" ? "參考價，不含特別紀念品。最終價錢以確認時為準。" : "Reference price excluding keepsakes. Final quote confirmed at booking."}</p>
              </div>
              <div className="calc-tabs">
                {/* 目前只提供火化;恢復水化時加返 water button */}
                <button className={mode === "fire" ? "on" : ""} onClick={() => setMode("fire")}>{lang === "zh" ? "火化" : "CREMATION"}</button>
              </div>
            </div>
            <div className="calc-grid">
              <div className="slider-group">
                <label>{lang === "zh" ? "牠的體重" : "Pet weight"}</label>
                <div className="slider-val">{weight}<em>kg</em></div>
                <input type="range" min="1" max="50" value={weight} onChange={e => setWeight(+e.target.value)}/>
                <div style={{display:"flex", justifyContent:"space-between", fontFamily:"var(--mono)", fontSize:10, color:"var(--muted)", letterSpacing:"0.1em", marginTop:8}}>
                  <span>1 KG</span><span>50 KG</span>
                </div>
              </div>
              <div className="calc-readout">
                <div className="big"><span className="c">HK$</span>{calcPrice(weight, mode).toLocaleString()}</div>
                <div className="cap">{lang === "zh" ? "火化・個別套餐參考價" : "Cremation · Individual ref. price"}</div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // ============= MEMORIAL =============
  function Memorial({ lang }) {
    const products = [
      { n: { zh: "陶瓷骨灰罐", en: "Ceramic Urn" }, p: "HK$ 380+", ic: "urn" },
      { n: { zh: "水晶吊墜", en: "Crystal Pendant" }, p: "HK$ 680", ic: "pendant" },
      { n: { zh: "爪印紀念板", en: "Paw Print" }, p: "HK$ 280", ic: "paw" },
      { n: { zh: "毛髮紀念瓶", en: "Fur Vial" }, p: "HK$ 220", ic: "vial" },
      { n: { zh: "手繪相框", en: "Hand-painted Frame" }, p: "HK$ 480", ic: "frame" },
      { n: { zh: "追思短片", en: "Memorial Video" }, p: "HK$ 980", ic: "video" },
      { n: { zh: "紙摺紙鶴", en: "Origami Cranes" }, p: "HK$ 120", ic: "crane" },
      { n: { zh: "紀念樹苗", en: "Memorial Sapling" }, p: "HK$ 380", ic: "tree" },
    ];
    const icons = {
      urn: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3 C 14 3 15 4 15 6 L 15 8 L 16 8 C 17 8 18 9 18 10 L 18 18 C 18 20 16 22 14 22 L 10 22 C 8 22 6 20 6 18 L 6 10 C 6 9 7 8 8 8 L 9 8 L 9 6 C 9 4 10 3 12 3 Z" opacity="0.7"/></svg>,
      pendant: <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="10" r="3" opacity="0.4"/><path d="M12 13 L 8 20 L 12 18 L 16 20 Z" opacity="0.7"/><circle cx="12" cy="6" r="1.5" opacity="0.5"/></svg>,
      paw: <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="10" r="2" opacity="0.6"/><circle cx="18" cy="10" r="2" opacity="0.6"/><circle cx="9" cy="6" r="2" opacity="0.6"/><circle cx="15" cy="6" r="2" opacity="0.6"/><path d="M 8 14 Q 12 16 16 14 Q 18 18 12 20 Q 6 18 8 14 Z" opacity="0.7"/></svg>,
      vial: <svg viewBox="0 0 24 24" fill="currentColor"><rect x="9" y="3" width="6" height="3" rx="1" opacity="0.5"/><path d="M 10 6 L 10 19 Q 10 21 12 21 Q 14 21 14 19 L 14 6 Z" opacity="0.6"/><path d="M 10 14 L 14 14 L 14 19 Q 14 21 12 21 Q 10 21 10 19 Z" opacity="0.3"/></svg>,
      frame: <svg viewBox="0 0 24 24" fill="currentColor"><rect x="4" y="4" width="16" height="16" rx="1" fill="none" stroke="currentColor" strokeWidth="1.5" opacity="0.5"/><circle cx="12" cy="10" r="3" opacity="0.5"/><path d="M 7 18 Q 12 14 17 18 L 17 19 L 7 19 Z" opacity="0.5"/></svg>,
      video: <svg viewBox="0 0 24 24" fill="currentColor"><rect x="3" y="6" width="13" height="12" rx="1" opacity="0.4"/><path d="M 16 10 L 22 6 L 22 18 L 16 14 Z" opacity="0.6"/></svg>,
      crane: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M 3 14 L 12 6 L 21 14 L 15 14 L 12 18 L 9 14 Z" opacity="0.6"/><circle cx="12" cy="4" r="1" opacity="0.5"/></svg>,
      tree: <svg viewBox="0 0 24 24" fill="currentColor"><path d="M 12 3 L 8 9 L 10 9 L 6 15 L 9 15 L 5 20 L 19 20 L 15 15 L 18 15 L 14 9 L 16 9 Z" opacity="0.6"/><rect x="11" y="19" width="2" height="3" opacity="0.5"/></svg>,
    };
    return (
      <section id="memorial">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "紀念品" : "Keepsakes"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>帶一片<em>天</em>回家。</> : <>Take a piece of <em>sky</em> home.</>}</h2>
              <p>{lang === "zh" ? "全部手工製作，可加刻毛孩名字、生忌或一句話。" : "All hand-crafted. Engrave a name, date, or a single line."}</p>
            </div>
          </div>
          <div className="mem-grid">
            {products.map((p, i) => (
              <div className="mem-card" key={i}>
                <div className="thumb" style={{color: "var(--sky-5)"}}>{icons[p.ic]}</div>
                <div className="info">
                  <div className="n">{L(p.n, lang)}</div>
                  <div className="en">{p.n.en}</div>
                  <div className="p">{p.p}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  // ============= TESTIMONIALS =============
  function Testimonials({ lang }) {
    const data = [
      { t: { zh: "半夜兩點嗰通電話，佢哋一個鐘內就到咗門口。陪我哋坐咗十五分鐘先捧走 Toby，好感謝。", en: "A 2 a.m. call — they arrived within the hour. Sat with us for fifteen minutes before taking Toby. So grateful." }, n: "Carmen", sm: "w/ Toby · 拉布拉多" },
      { t: { zh: "最欣賞係全程冇 pushy sales。想加咩服務先介紹，唔夾硬推套餐。價錢清清楚楚。", en: "Zero pushy sales. They explained options only when asked. Transparent pricing end to end." }, n: "Alvin", sm: "w/ 妹妹 · 英短" },
      { t: { zh: "成個過程好平靜、好有尊嚴。收到骨灰嗰日，連佢嘅小爪印同一首琴音短片都整埋，喊得好慘。", en: "The whole process felt calm and dignified. On the return day, they included her paw print and a piano memorial video. Ugly cried." }, n: "Phoebe", sm: "w/ 點點 · 貴婦" },
    ];
    return (
      <section id="testimonials" className="testimonials">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "家屬心聲" : "Family Voices"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>1,800 <em>個</em> 家的離別故事。</> : <>1,800 <em>family</em> farewells told.</>}</h2>
            </div>
          </div>
          <div className="tg">
            {data.map((d, i) => (
              <div className="t" key={i}>
                <div className="q">"</div>
                <p>{L(d.t, lang)}</p>
                <div className="who">
                  <div className="av">{d.n[0]}</div>
                  <div>
                    <div className="nm">{d.n}</div>
                    <div className="sm">{d.sm}</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  // ============= BOOKING =============
  function BookingSystemSlot({ lang, service, slot }) {
    const api = (typeof window !== "undefined" && window.AftertailAPI) || {};
    const embedUrl = api.bookingEmbedUrl || "";
    const scriptUrl = api.bookingScriptUrl || "";
    useEffect(() => {
      if (!scriptUrl || typeof document === "undefined") return;
      const existing = document.querySelector(`script[data-aftertail-booking-script="${scriptUrl}"]`);
      if (existing) return;
      const script = document.createElement("script");
      script.src = scriptUrl;
      script.async = true;
      script.dataset.aftertailBookingScript = scriptUrl;
      document.body.appendChild(script);
    }, [scriptUrl]);
    return (
      <div
        id="aftertail-booking-system-slot"
        className="booking-system-slot"
        data-provider="company-booking-system"
        data-selected-service={service}
        data-selected-slot={slot}
        data-integration-ready={embedUrl || scriptUrl ? "true" : "false"}
        data-integration-mode={embedUrl ? "iframe" : scriptUrl ? "script" : "placeholder"}
      >
        <div className="slot-head">
          <div>
            <div className="eyebrow">{lang === "zh" ? "公司預約系統" : "Company Booking System"}</div>
            <h3>{lang === "zh" ? "即時預約版面" : "Live Booking Panel"}</h3>
          </div>
          <span className="slot-status">{embedUrl || scriptUrl ? "LIVE" : "READY"}</span>
        </div>
        {embedUrl ? (
          <iframe
            title={lang === "zh" ? "尾站公司預約系統" : "Aftertail company booking system"}
            src={embedUrl}
            loading="lazy"
          />
        ) : scriptUrl ? (
          <div
            id="aftertail-management-widget"
            className="management-widget-slot"
            data-aftertail-widget-root
          >
            <div className="slot-placeholder">
              <div className="slot-icon"><Ic.clock/></div>
              <div>
                <strong>{lang === "zh" ? "正在載入公司管理系統" : "Loading management system"}</strong>
                <p>{lang === "zh"
                  ? "此區域已預留給同事開發的預約 / 管理系統 widget。"
                  : "This area is reserved for the booking / management system widget."}</p>
              </div>
            </div>
          </div>
        ) : (
          <div className="slot-placeholder">
            <div className="slot-icon"><Ic.clock/></div>
            <div>
              <strong>{lang === "zh" ? "預留給公司預約系統接入" : "Reserved for company booking integration"}</strong>
              <p>{lang === "zh"
                ? "之後可用 iframe 網址或 widget script 接入。同事只要掛到 #aftertail-booking-system-slot 或 #aftertail-management-widget 就可以。"
                : "This accepts an iframe URL or a widget script. Developers can mount into #aftertail-booking-system-slot or #aftertail-management-widget."}</p>
            </div>
          </div>
        )}
      </div>
    );
  }

  function Booking({ lang }) {
    const [service, setService] = useState("fire");
    const [slot, setSlot] = useState("14:00");
    const [date, setDate] = useState(18);
    const [formData, setFormData] = useState({
      name: "",
      phone: "",
      pet_name: "",
      weight: "",
      address: "",
      notes: "",
    });
    const [submitState, setSubmitState] = useState("idle");
    const today = new Date();
    const monthName = lang === "zh" ? `${today.getFullYear()}年 ${today.getMonth() + 1}月` : today.toLocaleDateString("en-US", { month: "long", year: "numeric" });
    const slots = ["10:00", "11:30", "14:00", "15:30", "17:00", "19:00"];
    const offSlots = new Set(["11:30", "17:00"]);
    const api = (typeof window !== "undefined" && window.AftertailAPI) || {};
    const updateField = (field, value) => setFormData(prev => ({ ...prev, [field]: value }));
    const submitBooking = async (event) => {
      event.preventDefault();
      if (!formData.name.trim() || !formData.phone.trim()) {
        setSubmitState("error");
        return;
      }
      setSubmitState("sending");
      try {
        const res = await fetch(api.bookingUrl || "/wp-json/aftertail/v1/booking", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(api.nonce ? { "X-WP-Nonce": api.nonce } : {}),
          },
          body: JSON.stringify({
            ...formData,
            service,
            date: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(date).padStart(2, "0")}`,
            slot,
            lang,
          }),
        });
        if (!res.ok) throw new Error("booking_failed");
        setSubmitState("success");
        setFormData({ name: "", phone: "", pet_name: "", weight: "", address: "", notes: "" });
      } catch (error) {
        setSubmitState("error");
      }
    };

    return (
      <section id="booking">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "預約服務" : "Book Service"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>留低資料，<em>其他</em>交俾我哋。</> : <>Leave a note, <em>we</em> handle the rest.</>}</h2>
              <p>{lang === "zh" ? "填好以下資料，我哋會喺 15 分鐘內回覆確認。急事請直接致電 9123 4567。" : "We reply within 15 minutes. For urgent help, call 9123 4567."}</p>
            </div>
          </div>
          <div className="booking-grid">
            <div>
              <BookingSystemSlot lang={lang} service={service} slot={slot}/>

              <form className="form-card fallback-form" onSubmit={submitBooking}>
                <h3>{lang === "zh" ? "後備查詢表格" : "Fallback Enquiry Form"}</h3>
                <div className="sub">{lang === "zh" ? "正式系統未接入時，可暫用此表格收集資料。" : "Use this while the official system is being connected."}</div>

                <div className="field">
                  <label>{lang === "zh" ? "服務 *" : "Service *"}</label>
                  <div className="radio-group">
                    {/* 目前只提供火化;恢復水化時加返 water radio-opt */}
                    <div className={"radio-opt" + (service === "fire" ? " sel" : "")} onClick={() => setService("fire")}>
                      <div className="t-cn">{lang === "zh" ? "火化" : "Cremation"}</div>
                      <div className="t-en">{lang === "zh" ? "Cremation" : "火化"}</div>
                    </div>
                  </div>
                </div>

                <div className="field-row">
                  <div className="field">
                    <label>{lang === "zh" ? "姓名 *" : "Name *"}</label>
                    <input type="text" value={formData.name} onChange={e => updateField("name", e.target.value)} placeholder={lang === "zh" ? "陳小姐" : "Ms. Chan"} required/>
                  </div>
                  <div className="field">
                    <label>{lang === "zh" ? "電話 *" : "Phone *"}</label>
                    <input type="tel" value={formData.phone} onChange={e => updateField("phone", e.target.value)} placeholder="+852 9xxx xxxx" required/>
                  </div>
                </div>

                <div className="field-row">
                  <div className="field">
                    <label>{lang === "zh" ? "毛孩名字" : "Pet's name"}</label>
                    <input type="text" value={formData.pet_name} onChange={e => updateField("pet_name", e.target.value)} placeholder={lang === "zh" ? "Toby" : "Toby"}/>
                  </div>
                  <div className="field">
                    <label>{lang === "zh" ? "體重 (kg)" : "Weight (kg)"}</label>
                    <input type="number" value={formData.weight} onChange={e => updateField("weight", e.target.value)} placeholder="8"/>
                  </div>
                </div>

                <div className="field">
                  <label>{lang === "zh" ? "偏好時間" : "Preferred time"}</label>
                  <div className="timeslots">
                    {slots.map(s => (
                      <div key={s} className={"tslot" + (offSlots.has(s) ? " off" : "") + (slot === s ? " sel" : "")}
                        onClick={() => !offSlots.has(s) && setSlot(s)}>{s}</div>
                    ))}
                  </div>
                </div>

                <div className="field">
                  <label>{lang === "zh" ? "接送地址" : "Pickup address"}</label>
                  <input type="text" value={formData.address} onChange={e => updateField("address", e.target.value)} placeholder={lang === "zh" ? "香港九龍觀塘…" : "Kwun Tong, Kowloon…"}/>
                </div>

                <div className="field">
                  <label>{lang === "zh" ? "備註" : "Notes"}</label>
                  <textarea rows="3" value={formData.notes} onChange={e => updateField("notes", e.target.value)} placeholder={lang === "zh" ? "有任何希望安排的事，例如音樂、特別紀念…" : "Any special arrangements — music, keepsakes…"}></textarea>
                </div>

                <button className="btn btn-primary" disabled={submitState === "sending"} style={{width:"100%", justifyContent:"center", padding:"16px"}}>
                  {submitState === "sending" ? (lang === "zh" ? "送出中..." : "Sending...") : (lang === "zh" ? "提交查詢" : "Submit Enquiry")} →
                </button>
                {submitState === "success" && <div className="form-note ok">{lang === "zh" ? "已收到資料，我哋會盡快聯絡你。" : "Received. We will contact you shortly."}</div>}
                {submitState === "error" && <div className="form-note err">{lang === "zh" ? "未能送出，請檢查姓名及電話，或直接致電 9123 4567。" : "Could not submit. Check name and phone, or call 9123 4567."}</div>}
              </form>
            </div>

            <div className="booking-info">
              <h3>{lang === "zh" ? "服務資訊" : "At a glance"}</h3>
              <div className="bi-row">
                <div className="ic"><Ic.clock/></div>
                <div>
                  <div className="k">{lang === "zh" ? "回覆時間" : "Response"}</div>
                  <div className="v">{lang === "zh" ? "15 分鐘內" : "Within 15 minutes"}<small>{lang === "zh" ? "急件直接致電" : "Call for emergencies"}</small></div>
                </div>
              </div>
              <div className="bi-row">
                <div className="ic"><Ic.pin/></div>
                <div>
                  <div className="k">{lang === "zh" ? "接送範圍" : "Coverage"}</div>
                  <div className="v">{lang === "zh" ? "全港 18 區免費" : "Free across 18 districts"}<small>{lang === "zh" ? "離島另行報價" : "Outlying islands quoted"}</small></div>
                </div>
              </div>
              <div className="bi-row">
                <div className="ic"><Ic.phone/></div>
                <div>
                  <div className="k">{lang === "zh" ? "24 小時熱線" : "24h Hotline"}</div>
                  <div className="v">9123 4567<small>{lang === "zh" ? "節假日同時開放" : "Including holidays"}</small></div>
                </div>
              </div>
              <div className="bi-row">
                <div className="ic"><Ic.mail/></div>
                <div>
                  <div className="k">Email</div>
                  <div className="v">hello@aftertail.hk</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // ============= FAQ =============
  function FAQ({ lang }) {
    const items = [
      { q: { zh: "需要預約定係可以即時接送？", en: "Do I need to book in advance?" }, a: { zh: "24 小時熱線即時接收。一般上門時間為 30 至 60 分鐘，視乎交通。夜間亦可。", en: "Our 24h hotline accepts immediate requests. Typical arrival is 30–60 minutes depending on traffic. Night service available." } },
      { q: { zh: "家人可以全程陪同嗎？", en: "Can family accompany the whole process?" }, a: { zh: "個別套餐可以全程在告別室陪同，或透過視像參與。集體套餐則於告別完成後交付骨灰。", en: "With the Individual package, family may accompany the whole farewell on-site or via live video. Communal packages include a farewell before the rite." } },
      { q: { zh: "最快幾時可以收返骨灰？", en: "When can I receive the ashes?" }, a: { zh: "個別套餐一般翌日即可領取或送回家。火化過程約 1-2 小時。", en: "Individual packages: next-day collection or delivery. Cremation takes ~1–2 hours." } },
      { q: { zh: "有無特殊寵物服務？（如爬蟲、兔仔）", en: "Do you serve non-cat/dog pets?" }, a: { zh: "所有毛孩、羽毛、鱗片家人我哋都接收——兔、倉鼠、雀、龜、蜥蜴、魚類，都以同樣心意對待。", en: "All companion animals welcome — rabbits, hamsters, birds, turtles, lizards, fish. Same care, same dignity." } },
      { q: { zh: "點收費？有冇隱藏費用？", en: "How does pricing work? Any hidden fees?" }, a: { zh: "明碼實價。三套方案已包全部基本服務；紀念品可加購。離島、夜間、特別佈置會另行報價，預約時會清楚說明。", en: "Transparent pricing. All three packages include core services; keepsakes are add-ons. Outlying islands, late-night, and special settings are quoted clearly at booking." } },
    ];
    return (
      <section id="faq">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "常見問題" : "FAQ"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>有問題，<em>直接問</em>。</> : <>Questions? <em>Ask</em>.</>}</h2>
              <p>{lang === "zh" ? "下面搵唔到答案？WhatsApp 我哋，通常 15 分鐘內回覆。" : "Can\u2019t find your answer below? WhatsApp us — we reply within 15 minutes."}</p>
            </div>
          </div>
          <div className="faq-list">
            {items.map((it, i) => (
              <details className="faq-item" key={i}>
                <summary>
                  <div>
                    <div>{L(it.q, lang)}</div>
                    <div className="en">{lang === "zh" ? it.q.en : it.q.zh}</div>
                  </div>
                </summary>
                <div className="ans">
                  {L(it.a, lang)}
                  <span className="en">{lang === "zh" ? it.a.en : it.a.zh}</span>
                </div>
              </details>
            ))}
          </div>
        </div>
      </section>
    );
  }

  // ============= CONTACT + FOOTER =============
  function Contact({ lang }) {
    const api = (typeof window !== "undefined" && window.AftertailAPI) || {};
    const [contactData, setContactData] = useState({ name: "", phone: "", message: "" });
    const [contactState, setContactState] = useState("idle");
    const updateContact = (field, value) => setContactData(prev => ({ ...prev, [field]: value }));
    const submitContact = async (event) => {
      event.preventDefault();
      if (!contactData.name.trim() || !contactData.message.trim()) {
        setContactState("error");
        return;
      }
      setContactState("sending");
      try {
        const res = await fetch(api.contactUrl || "/wp-json/aftertail/v1/contact", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(api.nonce ? { "X-WP-Nonce": api.nonce } : {}),
          },
          body: JSON.stringify({ ...contactData, lang }),
        });
        if (!res.ok) throw new Error("contact_failed");
        setContactState("success");
        setContactData({ name: "", phone: "", message: "" });
      } catch (error) {
        setContactState("error");
      }
    };

    return (
      <section id="contact" className="contact-section">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "聯絡我們" : "Contact"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>隨時來坐，<em>或</em>來電。</> : <>Visit us, <em>or</em> call.</>}</h2>
              <p>{lang === "zh" ? "門市設於觀塘，附近亦有停車場。一般辦公時間 10am–8pm；熱線 24 小時接聽。" : "Shop in Kwun Tong, parking nearby. Office 10am–8pm; hotline 24 hours."}</p>
            </div>
          </div>
          <div className="contact-grid">
            <div className="ci-card">
              <div className="it">
                <div className="k">{lang === "zh" ? "地址" : "Address"}</div>
                <div className="v">{lang === "zh" ? "九龍觀塘成業街 7 號" : "7 Shing Yip St, Kwun Tong, Kowloon"}</div>
                <div className="sub">{lang === "zh" ? "工業大廈 12 樓 B 室" : "12/F Flat B, Industrial Bldg"}</div>
              </div>
              <div className="it">
                <div className="k">{lang === "zh" ? "熱線" : "Hotline"}</div>
                <div className="v">9123 4567</div>
                <div className="sub">{lang === "zh" ? "24 小時" : "24 hours"}</div>
              </div>
              <div className="it">
                <div className="k">Email</div>
                <div className="v">hello@aftertail.hk</div>
              </div>
              <div className="it">
                <div className="k">{lang === "zh" ? "辦公時間" : "Shop hours"}</div>
                <div className="v">{lang === "zh" ? "10am – 8pm" : "10am – 8pm"}</div>
                <div className="sub">{lang === "zh" ? "星期一至日" : "Monday – Sunday"}</div>
              </div>
            </div>
            <div className="contact-stack">
              <form className="form-card contact-form-card" onSubmit={submitContact}>
                <h3>{lang === "zh" ? "簡易查詢" : "Quick enquiry"}</h3>
                <div className="sub">{lang === "zh" ? "唔一定要即時預約；有問題可以先留言，我哋會回覆。" : "Not ready to book? Leave a question and we will reply."}</div>
                <div className="field-row">
                  <div className="field">
                    <label>{lang === "zh" ? "姓名 *" : "Name *"}</label>
                    <input value={contactData.name} onChange={e => updateContact("name", e.target.value)} placeholder={lang === "zh" ? "陳小姐" : "Ms. Chan"} required/>
                  </div>
                  <div className="field">
                    <label>{lang === "zh" ? "電話 / WhatsApp" : "Phone / WhatsApp"}</label>
                    <input value={contactData.phone} onChange={e => updateContact("phone", e.target.value)} placeholder="+852 9xxx xxxx"/>
                  </div>
                </div>
                <div className="field">
                  <label>{lang === "zh" ? "想查詢嘅內容 *" : "Message *"}</label>
                  <textarea rows="4" value={contactData.message} onChange={e => updateContact("message", e.target.value)} placeholder={lang === "zh" ? "例如：想了解火化流程、價錢、上門接送安排…" : "For example: cremation process, pricing, pickup arrangement..."} required></textarea>
                </div>
                <button className="btn btn-primary" disabled={contactState === "sending"} style={{width:"100%", justifyContent:"center"}}>
                  {contactState === "sending" ? (lang === "zh" ? "送出中..." : "Sending...") : (lang === "zh" ? "送出查詢" : "Send enquiry")} →
                </button>
                {contactState === "success" && <div className="form-note ok">{lang === "zh" ? "查詢已送出，我哋會盡快回覆。" : "Your enquiry has been sent."}</div>}
                {contactState === "error" && <div className="form-note err">{lang === "zh" ? "未能送出，請填姓名及查詢內容，或直接致電 9123 4567。" : "Could not submit. Please fill name and message, or call 9123 4567."}</div>}
              </form>
              <div className="map">
              {/* stylized map */}
              <svg viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice" style={{width:"100%", height:"100%"}}>
                <rect width="400" height="300" fill="#eaf5ff"/>
                <path d="M0 120 Q 100 80 200 120 T 400 100 L 400 300 L 0 300 Z" fill="#cfe8fb" opacity="0.6"/>
                <path d="M0 180 Q 120 160 240 180 T 400 170 L 400 300 L 0 300 Z" fill="#b9ddf5" opacity="0.6"/>
                <g opacity="0.6">
                  <circle cx="80" cy="60" r="18" fill="white"/>
                  <circle cx="120" cy="55" r="28" fill="white"/>
                  <circle cx="320" cy="90" r="22" fill="white"/>
                  <circle cx="360" cy="85" r="18" fill="white"/>
                </g>
                {/* roads */}
                <path d="M 0 200 L 400 180" stroke="white" strokeWidth="3" opacity="0.8"/>
                <path d="M 140 300 L 200 100 L 300 160 L 400 140" stroke="white" strokeWidth="3" opacity="0.8" fill="none"/>
                {/* pin */}
                <g transform="translate(200, 160)">
                  <circle r="28" fill="#1b3a56" opacity="0.15"/>
                  <circle r="14" fill="#1b3a56"/>
                  <circle r="6" fill="white"/>
                  <path d="M 0 14 L -8 28 L 8 28 Z" fill="#1b3a56"/>
                </g>
              </svg>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  // ============= BLOG =============
  function BlogLanding({ lang }) {
    const topics = [
      { zh: "火化與善終知識", en: "Cremation & aftercare basics" },
      { zh: "告別儀式準備", en: "Preparing for farewells" },
      { zh: "紀念品與骨灰保存", en: "Keepsakes and ashes care" },
      { zh: "影片故事 / 社交媒體內容", en: "Video stories / social content" },
    ];
    return (
      <section id="blog" className="blog-section">
        <div className="wrap">
          <div className="section-head">
            <div><div className="eyebrow">{lang === "zh" ? "文章與影片" : "Blog & Video"}</div></div>
            <div>
              <h2>{lang === "zh" ? <>把知識、故事、<em>影片</em>留下來。</> : <>Keep knowledge, stories, <em>video</em>.</>}</h2>
              <p>{lang === "zh"
                ? "這裡預留給 SEO 文章、Instagram / Facebook 影片整理、Blogger 內容搬遷。正式文章會用 WordPress Posts 發佈，每篇都有獨立 SEO URL。"
                : "Reserved for SEO articles, Instagram / Facebook video writeups, and Blogger migration. Published posts use native WordPress Posts with SEO-friendly URLs."}</p>
            </div>
          </div>
          <div className="blog-landing-grid">
            {topics.map((topic, i) => (
              <div className="blog-topic-card" key={i}>
                <div className="topic-no">{String(i + 1).padStart(2, "0")}</div>
                <h3>{lang === "zh" ? topic.zh : topic.en}</h3>
                <p>{lang === "zh" ? topic.en : topic.zh}</p>
              </div>
            ))}
          </div>
          <div className="blog-actions">
            <a href="/blog/" className="btn btn-primary">{lang === "zh" ? "查看全部文章" : "View all posts"} →</a>
            <a href="/contact/" className="btn btn-ghost">{lang === "zh" ? "提交拍攝影片 / 文章題材" : "Submit video / article idea"}</a>
          </div>
        </div>
      </section>
    );
  }

  function Footer({ lang }) {
    return (
      <footer>
        <div className="wrap">
          <div className="f-grid">
            <div className="f-col f-brand">
              <div className="brand">
                <div className="brand-mark" style={{filter:"brightness(1.2)"}}><Logo/></div>
                <div>
                  <div className="brand-cn">尾站</div>
                  <div className="brand-en">Aftertail · Hong Kong</div>
                </div>
              </div>
              <p>{lang === "zh" ? "香港寵物善終服務。火化及追思陪伴，全天候為每一個家庭服務。" : "Hong Kong pet aftercare — cremation and memorial, around the clock for every family."}</p>
            </div>
            <div className="f-col">
              <h5>{lang === "zh" ? "服務" : "Services"}</h5>
              <a href="/services/">{lang === "zh" ? "火化" : "Cremation"}</a>
              <a href="/memorial/">{lang === "zh" ? "紀念品" : "Keepsakes"}</a>
              <a href="/blog/">{lang === "zh" ? "文章 / 影片" : "Blog / Video"}</a>
              <a href="/pricing/">{lang === "zh" ? "價錢" : "Pricing"}</a>
            </div>
            <div className="f-col">
              <h5>{lang === "zh" ? "公司" : "Company"}</h5>
              <a href="/about/">{lang === "zh" ? "關於我們" : "About"}</a>
              <a href="/">{lang === "zh" ? "家屬心聲" : "Reviews"}</a>
              <a href="/faq/">FAQ</a>
              <a href="/contact/">{lang === "zh" ? "聯絡" : "Contact"}</a>
            </div>
            <div className="f-col">
              <h5>{lang === "zh" ? "聯絡" : "Reach us"}</h5>
              <a href="tel:91234567">9123 4567</a>
              <a href="mailto:hello@aftertail.hk">hello@aftertail.hk</a>
              <a href="#">WhatsApp</a>
              <a href="#">Instagram</a>
            </div>
          </div>
          <div className="f-bot">
            <div>© 2026 Aftertail 尾站 · ALL RIGHTS RESERVED</div>
            <div>HK Pet Aftercare License · No. HK-PA-2018-0042</div>
          </div>
        </div>
      </footer>
    );
  }

  // ============= PROMISE STICKY =============
  function PromiseSticky({ lang }) {
    const [hide, setHide] = useState(false);
    const [show, setShow] = useState(false);
    useEffect(() => {
      const onScroll = () => setShow(window.scrollY > window.innerHeight * 0.8);
      window.addEventListener("scroll", onScroll, { passive: true });
      onScroll();
      return () => window.removeEventListener("scroll", onScroll);
    }, []);
    if (hide) return null;
    return (
      <div className={"ps-sticky" + (show ? " show" : "")}>
        <div className="h">
          <span className="d"></span>
          <span className="l">{lang === "zh" ? "此刻待命中" : "ON STANDBY NOW"}</span>
          <button onClick={() => setHide(true)} style={{marginLeft:"auto", background:"transparent", border:0, color:"var(--muted)", cursor:"pointer", fontSize:16, lineHeight:1}}>×</button>
        </div>
        <div className="t">
          {lang === "zh" ? (<>最快 <b>30 分鐘</b><br/>上門接收毛孩</>) : (<>Pickup within <b>30 min</b><br/>across Hong Kong</>)}
        </div>
        <div className="s">{lang === "zh" ? "致電 9123 4567 · WhatsApp" : "CALL 9123 4567 · WHATSAPP"}</div>
      </div>
    );
  }

  // ============= APP =============
  // Read the active page section from the WordPress template.
  // front-page.php sets data-section="home"; page.php sets it to the page slug.
  // Anything unknown falls back to "home" so the site never renders blank.
  function getSection() {
    if (typeof document === "undefined") return "home";
    const el = document.getElementById("app");
    const s = el && el.dataset && el.dataset.section ? el.dataset.section : "home";
    const valid = ["home", "about", "services", "pricing", "memorial", "blog", "booking", "faq", "contact"];
    return valid.includes(s) ? s : "home";
  }

  function PageBody({ section, lang }) {
    switch (section) {
      case "about":
        return <About lang={lang}/>;
      case "services":
        return <><Services lang={lang}/><Process lang={lang}/></>;
      case "pricing":
        return <Pricing lang={lang}/>;
      case "memorial":
        return <Memorial lang={lang}/>;
      case "blog":
        return <BlogLanding lang={lang}/>;
      case "booking":
        return <Booking lang={lang}/>;
      case "faq":
        return <FAQ lang={lang}/>;
      case "contact":
        return <Contact lang={lang}/>;
      case "home":
      default:
        return <><Hero lang={lang}/><Testimonials lang={lang}/></>;
    }
  }

  function App() {
    const [lang, setLang] = useState("zh");
    const [menuOpen, setMenuOpen] = useState(false);
    const section = getSection();
    return (
      <>
        <UrgencyBar lang={lang}/>
        <Nav lang={lang} setLang={setLang} section={section} onMenu={() => setMenuOpen(true)}/>
        <MobileMenu lang={lang} section={section} open={menuOpen} onClose={() => setMenuOpen(false)}/>
        <PageBody section={section} lang={lang}/>
        <Footer lang={lang}/>
        <a href="https://wa.me/85291234567" className="wa-fab">
          <Ic.wa/>
          <span>WhatsApp<span className="lb">{lang === "zh" ? "即時對話" : "Instant chat"}</span></span>
        </a>
        <PromiseSticky lang={lang}/>
      </>
    );
  }

  // Chrome-only mode: home.php / single.php 係純 PHP 出文章內容,
  // 只掛頂 bar(#app-chrome-top)同 footer(#app-chrome-bottom)兩個細 mount。
  function ChromeTop() {
    const [lang, setLang] = useState("zh");
    const [menuOpen, setMenuOpen] = useState(false);
    const el = document.getElementById("app-chrome-top");
    const s = el && el.dataset && el.dataset.section ? el.dataset.section : "blog";
    return (
      <>
        <UrgencyBar lang={lang}/>
        <Nav lang={lang} setLang={setLang} section={s} onMenu={() => setMenuOpen(true)}/>
        <MobileMenu lang={lang} section={s} open={menuOpen} onClose={() => setMenuOpen(false)}/>
      </>
    );
  }

  function ChromeBottom() {
    return (
      <>
        <Footer lang="zh"/>
        <a href="https://wa.me/85291234567" className="wa-fab">
          <Ic.wa/>
          <span>WhatsApp<span className="lb">即時對話</span></span>
        </a>
      </>
    );
  }

  const appEl = document.getElementById("app");
  if (appEl) {
    ReactDOM.createRoot(appEl).render(<App/>);
  } else {
    const topEl = document.getElementById("app-chrome-top");
    const bottomEl = document.getElementById("app-chrome-bottom");
    if (topEl) ReactDOM.createRoot(topEl).render(<ChromeTop/>);
    if (bottomEl) ReactDOM.createRoot(bottomEl).render(<ChromeBottom/>);
  }
