const { useState, useEffect } = React;
const W = window.WK;
const { A, LOGO, tri, BRAND, L, SLIDES, WHY, PROCESS, ORDER, SERVICES, FAQ, SERVICE_FAQ, CMS, getStore, setStore, pk, resolveImg,
  Ic, PageHero, Flowchart, PaymentMethods, OnlineBooking, OfficialChannels, ShareButtons, ContactForm, Footer, FloatingWidget,
  Button, Badge, ServiceCard, BlogCard, CaseStudyCard, TestimonialCard, AdvantageCard, Accordion, Input, Textarea, Select, Label } = W;
const { useRef } = React;

/* ---------------- Header (with services dropdown) ---------------- */
function Header({ lang, setLang, t, page, go }) {
  const [open, setOpen] = useState(false);
  const langs = [["en","EN"],["zh_TW","繁"],["zh_CN","简"]];
  const isSvc = page === "services" || page.startsWith("svc:");
  const link = (key, label, active) => (
    <a href="#" onClick={(e)=>{e.preventDefault();go(key);}}
       style={{ fontSize:14, fontWeight:500, color: active ? "hsl(var(--primary))":"hsl(var(--foreground))",
                borderBottom: active ? "2px solid hsl(var(--primary))":"2px solid transparent", paddingBottom:4, whiteSpace:"nowrap" }}>{label}</a>
  );
  return (
    <header style={{ position:"sticky", top:0, zIndex:50, background:"hsl(var(--background) / 0.92)", backdropFilter:"blur(8px)", borderBottom:"1px solid hsl(var(--border))" }}>
      <div className="wk-container" style={{ height:64, display:"flex", alignItems:"center", justifyContent:"space-between" }}>
        <img src={LOGO} alt="Fr8ight" style={{ height:36, cursor:"pointer" }} onClick={()=>go("home")} />
        <nav style={{ display:"flex", gap:26, alignItems:"center" }}>
          {link("home", t.home, page==="home")}
          <div style={{ position:"relative" }} onMouseEnter={()=>setOpen(true)} onMouseLeave={()=>setOpen(false)}>
            <a href="#" onClick={(e)=>{e.preventDefault();go("services");}}
               style={{ fontSize:14, fontWeight:500, color: isSvc ? "hsl(var(--primary))":"hsl(var(--foreground))", borderBottom: isSvc ? "2px solid hsl(var(--primary))":"2px solid transparent", paddingBottom:4, display:"inline-flex", alignItems:"center", gap:4 }}>
              {t.services}<Ic d="m6 9 6 6 6-6" size={14} color="currentColor" />
            </a>
            {open && (
              <div style={{ position:"absolute", top:"100%", left:"50%", transform:"translateX(-50%)", marginTop:8, background:"hsl(var(--card))", border:"1px solid hsl(var(--border))", borderRadius:"var(--radius-md)", boxShadow:"var(--shadow-lg)", padding:8, minWidth:220 }}>
                {SERVICES.map(s=>(
                  <a key={s.key} href="#" onClick={(e)=>{e.preventDefault();go("svc:"+s.key);setOpen(false);}}
                     style={{ display:"block", padding:"9px 12px", borderRadius:"var(--radius-sm)", fontSize:14, color:"hsl(var(--foreground))", textDecoration:"none" }}
                     onMouseEnter={(e)=>e.currentTarget.style.background="hsl(var(--accent))"} onMouseLeave={(e)=>e.currentTarget.style.background="transparent"}>
                    <span style={{ color:"hsl(var(--primary))", fontWeight:700, marginRight:8 }}>{s.num}</span>{tri(lang,s.title.en,s.title.zh_TW,s.title.zh_CN)}
                  </a>
                ))}
              </div>
            )}
          </div>
          {link("cases", t.cases, page==="cases")}
          {link("about", t.about, page==="about")}
          {link("blog", t.blog, page==="blog")}
          {link("contact", t.contact, page==="contact")}
        </nav>
        <div style={{ display:"flex", alignItems:"center", gap:12 }}>
          <div style={{ display:"flex", border:"1px solid hsl(var(--border))", borderRadius:"var(--radius-pill)", overflow:"hidden" }}>
            {langs.map(([code,label]) => (
              <button key={code} onClick={()=>setLang(code)} style={{ border:"none", cursor:"pointer", padding:"5px 11px", fontSize:12, fontWeight:600, background: lang===code ? "hsl(var(--primary))":"transparent", color: lang===code ? "#fff":"hsl(var(--muted-foreground))" }}>{label}</button>
            ))}
          </div>
          <Button size="sm" onClick={()=>go("contact")}>{t.quote}</Button>
        </div>
      </div>
    </header>
  );
}

/* ---------------- Home ---------------- */
function Hero({ t, lang, go }) {
  const [i, setI] = useState(0);
  useEffect(() => { const id = setInterval(()=>setI(p=>(p+1)%SLIDES.length), 6000); return ()=>clearInterval(id); }, []);
  const s = SLIDES[i];
  return (
    <section style={{ position:"relative", height:560, background:"hsl(var(--secondary))", overflow:"hidden" }}>
      {SLIDES.map((sl,idx)=>(
        <img key={idx} src={sl.image} alt="" style={{ position:"absolute", inset:0, width:"100%", height:"100%", objectFit:"cover", opacity: idx===i?0.42:0, transition:"opacity 1s ease" }} />
      ))}
      <div style={{ position:"absolute", inset:0, background:"var(--scrim-hero)" }} />
      <div className="wk-container" style={{ position:"relative", height:"100%", display:"flex", flexDirection:"column", justifyContent:"center" }}>
        <div style={{ maxWidth:640, color:"#fff" }}>
          <h1 style={{ fontSize:56, lineHeight:1.08, fontWeight:800, letterSpacing:"-0.02em", margin:0 }}>{tri(lang,s.title.en,s.title.zh_TW,s.title.zh_CN)}</h1>
          <p style={{ fontSize:19, lineHeight:1.5, color:"rgba(255,255,255,0.82)", margin:"24px 0 36px", maxWidth:560 }}>{tri(lang,s.desc.en,s.desc.zh_TW,s.desc.zh_CN)}</p>
          <div style={{ display:"flex", gap:16 }}>
            <Button size="pill" onClick={()=>go("contact")}>{t.quote}</Button>
            <Button size="pill" variant="outline" onClick={()=>go("services")} style={{ background:"transparent", color:"#fff", borderColor:"rgba(255,255,255,0.35)" }}>{t.our}</Button>
          </div>
        </div>
      </div>
      <div style={{ position:"absolute", bottom:28, left:0, right:0, display:"flex", justifyContent:"center", gap:10 }}>
        {SLIDES.map((_,idx)=>(<button key={idx} onClick={()=>setI(idx)} style={{ width:10, height:10, borderRadius:"50%", border:"none", cursor:"pointer", background: idx===i ? "#fff":"rgba(255,255,255,0.4)" }} />))}
      </div>
    </section>
  );
}

function ServicesOverview({ t, lang, go }) {
  return (
    <section className="wk-section" style={{ borderBottom:"1px solid hsl(var(--border))" }}><div className="wk-container">
      <div style={{ textAlign:"center", maxWidth:560, margin:"0 auto 56px" }}>
        <div className="wk-eyebrow">{tri(lang,"Our Expertise","我們的專業","我们的专业")}</div>
        <h2 className="wk-h2">{tri(lang,"Our core services","核心業務","核心业务")}</h2>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:28 }}>
        {SERVICES.map((s)=><ServiceCard key={s.key} number={s.num} subtitle={tri(lang,s.tagline.en,s.tagline.zh_TW,s.tagline.zh_CN)} title={tri(lang,s.title.en,s.title.zh_TW,s.title.zh_CN)} description={tri(lang,s.desc.en,s.desc.zh_TW,s.desc.zh_CN)} image={s.image} ctaText={t.learn} onClick={()=>go("svc:"+s.key)} />)}
      </div>
    </div></section>
  );
}

function WhyCard({ w, lang }) {
  return (
    <div style={{ display:"flex", gap:20, background:"hsl(var(--card))", border:"1px solid hsl(var(--border))", borderRadius:"var(--radius-lg)", padding:"26px 28px", boxShadow:"var(--shadow-sm)" }}>
      <div style={{ flex:"none", display:"flex", flexDirection:"column", alignItems:"center" }}>
        <div style={{ width:52, height:52, borderRadius:"var(--radius-md)", background:"hsl(var(--primary) / 0.1)", display:"flex", alignItems:"center", justifyContent:"center" }}><Ic d={w.icon} /></div>
        <div style={{ fontSize:12, fontWeight:700, color:"hsl(var(--muted-foreground))", letterSpacing:"0.1em", marginTop:8 }}>{w.n}</div>
      </div>
      <div><h3 style={{ fontSize:18, fontWeight:700, color:"hsl(var(--foreground))", margin:"2px 0 8px" }}>{tri(lang,w.t.en,w.t.zh_TW,w.t.zh_CN)}</h3>
        <p style={{ fontSize:14, lineHeight:1.6, color:"hsl(var(--muted-foreground))", margin:0 }}>{tri(lang,w.d.en,w.d.zh_TW,w.d.zh_CN)}</p></div>
    </div>
  );
}
function WhyChooseUs({ t, lang }) {
  return (
    <section className="wk-section" style={{ background:"hsl(var(--muted))" }}><div className="wk-container">
      <div style={{ marginBottom:48 }}>
        <div className="wk-eyebrow">{t.whyEyebrow}</div>
        <h2 className="wk-h2">{t.whyTitle}</h2>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:24, marginBottom:24 }}>
        {WHY.slice(0,2).map((w)=><WhyCard key={w.n} w={w} lang={lang} />)}
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:24 }}>
        {WHY.slice(2).map((w)=><WhyCard key={w.n} w={w} lang={lang} />)}
      </div>
    </div></section>
  );
}

function ProcessSection({ t, lang }) {
  return (
    <section className="wk-section"><div className="wk-container">
      <div style={{ textAlign:"center", maxWidth:560, margin:"0 auto 48px" }}>
        <div className="wk-eyebrow">{t.procEyebrow}</div>
        <h2 className="wk-h2">{t.procTitle}</h2>
      </div>
      <Flowchart steps={PROCESS} lang={lang} />
    </div></section>
  );
}

function CasesRow({ t, lang, go }) {
  const items = casesData(lang).slice(0,3);
  return (
    <section className="wk-section" style={{ background:"hsl(var(--muted))" }}><div className="wk-container">
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-end", marginBottom:48 }}>
        <div><div className="wk-eyebrow">{tri(lang,"Proven Results","實際成果","实际成果")}</div><h2 className="wk-h2">{tri(lang,"Recent case studies","近期案例","近期案例")}</h2></div>
        <Button variant="ghost" onClick={()=>go("cases")} style={{ color:"hsl(var(--primary))" }}>{t.viewAll} →</Button>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:28 }}>
        {items.map((c,i)=><CaseStudyCard key={i} {...c} ctaText={t.viewDetails} onClick={()=>go("cases")} />)}
      </div>
    </div></section>
  );
}

function testimonialsData(lang) {
  return (getStore().reviews || []).filter(r=>r.status==="published").map(r=>({
    rating: r.rating, name: pk(lang,r.name), company: pk(lang,r.company), feedback: pk(lang,r.feedback),
  }));
}
function TestimonialsRow({ lang }) {
  const all = testimonialsData(lang);
  const [page, setPage] = useState(0);
  const per = 3;
  const pages = Math.ceil(all.length / per);
  const items = all.slice(page*per, page*per+per);
  return (
    <section className="wk-section"><div className="wk-container">
      <div style={{ textAlign:"center", maxWidth:560, margin:"0 auto 48px" }}>
        <div className="wk-eyebrow">{tri(lang,"Client Voices","客戶評價","客户评价")}</div>
        <h2 className="wk-h2">{tri(lang,"Trusted by shippers across the GBA","深受大灣區託運人信賴","深受大湾区托运人信赖")}</h2>
      </div>
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:24, minHeight:230 }}>{items.map((v,i)=><TestimonialCard key={page+"-"+i} {...v} />)}</div>
      <div style={{ display:"flex", justifyContent:"center", alignItems:"center", gap:14, marginTop:36 }}>
        <button onClick={()=>setPage(p=>(p-1+pages)%pages)} aria-label="prev" style={{ width:40, height:40, borderRadius:"50%", border:"1px solid hsl(var(--border))", background:"hsl(var(--card))", cursor:"pointer", color:"hsl(var(--foreground))" }}><Ic d="m15 18-6-6 6-6" size={18} color="currentColor" /></button>
        <div style={{ display:"flex", gap:8 }}>{Array.from({length:pages}).map((_,i)=>(<button key={i} onClick={()=>setPage(i)} aria-label={"page "+(i+1)} style={{ width:9, height:9, borderRadius:"50%", border:"none", cursor:"pointer", background: i===page?"hsl(var(--primary))":"hsl(var(--border))" }} />))}</div>
        <button onClick={()=>setPage(p=>(p+1)%pages)} aria-label="next" style={{ width:40, height:40, borderRadius:"50%", border:"1px solid hsl(var(--border))", background:"hsl(var(--card))", cursor:"pointer", color:"hsl(var(--foreground))" }}><Ic d="m9 18 6-6-6-6" size={18} color="currentColor" /></button>
      </div>
    </div></section>
  );
}

function CTABand({ t, go }) {
  return (
    <section style={{ background:"hsl(var(--secondary))" }}>
      <div className="wk-container" style={{ padding:"56px 24px", display:"flex", justifyContent:"space-between", alignItems:"center", gap:24, flexWrap:"wrap" }}>
        <div><h3 style={{ color:"#fff", fontSize:26, fontWeight:700, margin:0 }}>{t.ready}</h3><p style={{ color:"rgba(255,255,255,0.75)", margin:"8px 0 0" }}>{t.readyDesc}</p></div>
        <Button size="pill" onClick={()=>go("contact")}>{t.quote}</Button>
      </div>
    </section>
  );
}

function AboutHome({ t, lang, go }) {
  const pg = getStore().page || {};
  return (
    <section className="wk-section"><div className="wk-container">
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:56, alignItems:"center" }}>
        <div style={{ position:"relative" }}>
          <img src={pg.aboutImg ? resolveImg(pg.aboutImg) : A+"sub-hk-to-cn.png"} alt={tri(lang,"About Fr8ight","關於 Fr8ight","关于 Fr8ight")} style={{ width:"100%", borderRadius:"var(--radius-lg)", boxShadow:"var(--shadow-lg)", display:"block" }} />
        </div>
        <div>
          <div className="wk-eyebrow">{tri(lang,"About Us","關於我們","关于我们")}</div>
          <h2 className="wk-h2" style={{ marginBottom:20 }}>{pk(lang,pg.aboutTitle) || tri(lang,"Redefining logistics across every border","跨越每個邊界，重新定義物流","跨越每个边界，重新定义物流")}</h2>
          <p style={{ fontSize:16.5, lineHeight:1.8, color:"hsl(var(--muted-foreground))", margin:"0 0 18px" }}>{pk(lang,pg.aboutText)}</p>
          <p style={{ fontSize:16.5, lineHeight:1.8, color:"hsl(var(--muted-foreground))", margin:"0 0 28px" }}>{pk(lang,pg.aboutText2)}</p>
          <Button size="pill" onClick={()=>go("about")}>{tri(lang,"Learn more","了解更多","了解更多")}</Button>
        </div>
      </div>
    </div></section>
  );
}

function HomePage({ t, lang, go }) {
  return (
    <React.Fragment>
      <Hero t={t} lang={lang} go={go} />
      <ServicesOverview t={t} lang={lang} go={go} />
      <AboutHome t={t} lang={lang} go={go} />
      <WhyChooseUs t={t} lang={lang} />
      <ProcessSection t={t} lang={lang} />
      <PaymentMethods t={t} />
      <CasesRow t={t} lang={lang} go={go} />
      <TestimonialsRow lang={lang} />
      <CTABand t={t} go={go} />
    </React.Fragment>
  );
}

/* ---------------- Services overview page ---------------- */
function ServicesPage({ t, lang, go }) {
  return (
    <React.Fragment>
      <PageHero image={A+"freight-truck.png"} title={tri(lang,"Cross-Border Logistics & Moving Solutions","跨境物流與搬家服務方案","跨境物流与搬家服务方案")} subtitle={tri(lang,"Comprehensive, reliable and efficient logistics tailored to your needs.","為您量身打造的全面、可靠且高效的物流服務。","为您量身打造的全面、可靠且高效的物流服务。")} />
      <section className="wk-section"><div className="wk-container">
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:28 }}>
          {SERVICES.map((s)=>(
            <div key={s.key}>
              <ServiceCard number={s.num} subtitle={tri(lang,s.tagline.en,s.tagline.zh_TW,s.tagline.zh_CN)} title={tri(lang,s.title.en,s.title.zh_TW,s.title.zh_CN)} description={tri(lang,s.desc.en,s.desc.zh_TW,s.desc.zh_CN)} image={s.image} ctaText={tri(lang,"View service →","查看服務 →","查看服务 →")} onClick={()=>go("svc:"+s.key)} />
            </div>
          ))}
        </div>
      </div></section>
      <ProcessSection t={t} lang={lang} />
      <PaymentMethods t={t} />
      <CTABand t={t} go={go} />
    </React.Fragment>
  );
}

/* ---------------- Service detail (2nd level) ---------------- */
function ServiceDetailPage({ svcKey, t, lang, go }) {
  const s = SERVICES.find(x=>x.key===svcKey) || SERVICES[0];
  const title = tri(lang,s.title.en,s.title.zh_TW,s.title.zh_CN);
  return (
    <React.Fragment>
      <PageHero image={s.image} title={title} subtitle={tri(lang,s.desc.en,s.desc.zh_TW,s.desc.zh_CN)} />
      {/* breadcrumb + inner services */}
      <section className="wk-section" style={{ paddingBottom:48 }}><div className="wk-container">
        <div style={{ fontSize:13, color:"hsl(var(--muted-foreground))", marginBottom:28 }}>
          <a href="#" onClick={(e)=>{e.preventDefault();go("services");}} style={{ color:"hsl(var(--primary))" }}>{t.services}</a> / {title}
        </div>
        <div className="wk-eyebrow">{tri(lang,"What's included","服務內容","服务内容")}</div>
        <h2 className="wk-h2" style={{ marginBottom:32 }}>{tri(lang,"Services under this category","此類別下的業務","此类别下的业务")}</h2>
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(300px,1fr))", gap:28 }}>
          {s.sub.map((b,i)=>(
            <div key={i} style={{ display:"flex", flexDirection:"column", background:"hsl(var(--card))", border:"1px solid hsl(var(--border))", borderRadius:"var(--radius-lg)", overflow:"hidden", boxShadow:"var(--shadow-md)" }}>
              <div style={{ aspectRatio:"16 / 10", overflow:"hidden" }}><img src={b.img} alt="" style={{ width:"100%", height:"100%", objectFit:"cover" }} /></div>
              <div style={{ padding:"22px 24px", display:"flex", flexDirection:"column", flex:1 }}>
                <h3 style={{ fontSize:20, fontWeight:700, color:"hsl(var(--foreground))", margin:"0 0 10px" }}>{tri(lang,b.en,b.zh_TW,b.zh_CN)}</h3>
                <p style={{ fontSize:14, lineHeight:1.6, color:"hsl(var(--muted-foreground))", margin:"0 0 18px", flex:1 }}>{tri(lang,b.d.en,b.d.zh_TW,b.d.zh_CN)}</p>
                <a href="#" onClick={(e)=>{e.preventDefault();go("contact");}} style={{ fontSize:14, fontWeight:600, color:"hsl(var(--primary))", display:"inline-flex", alignItems:"center", gap:6 }}>{t.learn} <Ic d="M5 12h14M13 6l6 6-6 6" size={16} color="currentColor" /></a>
              </div>
            </div>
          ))}
        </div>
      </div></section>

      {/* Moving-only: new self-service feature */}
      {s.key==="moving" && (
        <section className="wk-section" style={{ background:"hsl(var(--accent))", paddingTop:56, paddingBottom:56 }}><div className="wk-container" style={{ display:"flex", gap:36, alignItems:"center", flexWrap:"wrap" }}>
          <img src={A+"qr-mainland-moving.jpg"} alt="QR" style={{ width:160, height:160, borderRadius:"var(--radius-md)", background:"#fff", padding:8, boxShadow:"var(--shadow-md)" }} />
          <div style={{ flex:"1 1 360px" }}>
            <Badge pill>{tri(lang,"NEW FEATURE","全新功能","全新功能")}</Badge>
            <h3 style={{ fontSize:26, fontWeight:800, color:"hsl(var(--foreground))", margin:"12px 0 10px" }}>{tri(lang,"Mainland moving orders now support online self-service booking","內地搬家訂單現已支援線上自助下單","内地搬家订单现已支持在线自助下单")}</h3>
            <p style={{ fontSize:15, lineHeight:1.6, color:"hsl(var(--accent-foreground))", margin:0 }}>{tri(lang,"Place mainland moving orders easily through our official WeChat account. Scan the QR code to enter our smart booking system, get an instant quote and track your moving progress in real time.","您現在可以直接透過我們的官方微信公眾號輕鬆下達內地搬家訂單。掃描二維碼進入我們的智能預訂系統，獲取即時報價並實時追蹤您的搬家進度。","您现在可以直接通过我们的官方微信公众号轻松下达内地搬家订单。扫描二维码进入我们的智能预订系统，获取即时报价并实时追踪您的搬家进度。")}</p>
          </div>
        </div></section>
      )}

      <section className="wk-section" style={{ background:"hsl(var(--muted))", paddingTop:56, paddingBottom:56 }}><div className="wk-container">
        <div style={{ textAlign:"center", marginBottom:44 }}><div className="wk-eyebrow">{t.procEyebrow}</div><h2 className="wk-h2">{t.procTitle}</h2></div>
        <Flowchart steps={PROCESS} lang={lang} />
      </div></section>

      <section className="wk-section" style={{ paddingTop:56 }}><div className="wk-container" style={{ maxWidth:760 }}>
        <h3 style={{ fontSize:26, fontWeight:700, textAlign:"center", marginBottom:24, color:"hsl(var(--foreground))" }}>{t.faq}</h3>
        <Accordion defaultOpen={[0]} items={(SERVICE_FAQ[s.key]||FAQ).map(f=>({ question:tri(lang,f.q.en,f.q.zh_TW,f.q.zh_CN), answer:tri(lang,f.a.en,f.a.zh_TW,f.a.zh_CN) }))} />
      </div></section>

      <OnlineBooking t={t} />
      <CTABand t={t} go={go} />
    </React.Fragment>
  );
}

/* ---------------- Cases ---------------- */
function casesData(lang) {
  return (getStore().cases || []).filter(c=>c.status==="published").map(c=>({
    client: pk(lang,c.client), location: pk(lang,c.location), tag: pk(lang,c.tag),
    teaser: pk(lang,c.teaser), image: resolveImg(c.img),
  }));
}
function CasesPage({ t, lang, go }) {
  const all = casesData(lang);
  const [page, setPage] = useState(0);
  const per = 6;
  const pages = Math.ceil(all.length / per);
  const items = all.slice(page*per, page*per+per);
  return (
    <React.Fragment>
      <PageHero image={A+"freight-aerial.png"} title={tri(lang,"Success Cases","成功案例展示","成功案例展示")} subtitle={tri(lang,"Real results from our logistics solutions.","我們物流解決方案的實際成果。","我们物流解决方案的实际成果。")} />
      <section className="wk-section"><div className="wk-container">
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:28 }}>
          {items.map((c,i)=>(
            <CaseStudyCard key={page+"-"+i} {...c} label={c.tag} ctaText={t.viewDetails} onClick={()=>go("contact")} />
          ))}
        </div>
        {pages>1 && (
          <div style={{ display:"flex", justifyContent:"center", alignItems:"center", gap:10, marginTop:44 }}>
            <button onClick={()=>{setPage(p=>Math.max(0,p-1));window.scrollTo(0,0);}} disabled={page===0} style={{ height:40, padding:"0 16px", borderRadius:"var(--radius-md)", border:"1px solid hsl(var(--border))", background:"hsl(var(--card))", cursor: page===0?"default":"pointer", opacity: page===0?0.4:1, fontSize:14, fontWeight:600, color:"hsl(var(--foreground))" }}>{tri(lang,"Previous","上一頁","上一页")}</button>
            {Array.from({length:pages}).map((_,i)=>(
              <button key={i} onClick={()=>{setPage(i);window.scrollTo(0,0);}} style={{ width:40, height:40, borderRadius:"var(--radius-md)", border:"1px solid "+(i===page?"hsl(var(--primary))":"hsl(var(--border))"), background: i===page?"hsl(var(--primary))":"hsl(var(--card))", color: i===page?"#fff":"hsl(var(--foreground))", fontWeight:700, cursor:"pointer" }}>{i+1}</button>
            ))}
            <button onClick={()=>{setPage(p=>Math.min(pages-1,p+1));window.scrollTo(0,0);}} disabled={page===pages-1} style={{ height:40, padding:"0 16px", borderRadius:"var(--radius-md)", border:"1px solid hsl(var(--border))", background:"hsl(var(--card))", cursor: page===pages-1?"default":"pointer", opacity: page===pages-1?0.4:1, fontSize:14, fontWeight:600, color:"hsl(var(--foreground))" }}>{tri(lang,"Next","下一頁","下一页")}</button>
          </div>
        )}
      </div></section>
      <CTABand t={t} go={go} />
    </React.Fragment>
  );
}

/* ---------------- About ---------------- */
function AboutPage({ t, lang, go }) {
  const stats = [
    [tri(lang,"15+ Years","15+ 年","15+ 年"), tri(lang,"Experience","經驗","经验"), "M12 6v6l4 2M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Z"],
    ["10,000+", tri(lang,"Customers served","服務客戶","服务客户"), "M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"],
    ["500+", tri(lang,"Cities covered","覆蓋城市","覆盖城市"), "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20ZM2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20Z"],
    ["200+", tri(lang,"Professional team","專業團隊","专业团队"), "M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16M2 9h20v11a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1z"],
  ];
  const checks = [
    tri(lang,"15+ years of experience","15 年以上經驗","15 年以上经验"),
    tri(lang,"10,000+ satisfied customers","10,000+ 滿意客戶","10,000+ 满意客户"),
    tri(lang,"500+ cities covered","覆蓋 500+ 城市","覆盖 500+ 城市"),
    tri(lang,"200+ professional team","200+ 專業團隊","200+ 专业团队"),
    tri(lang,"24/7 customer support","24/7 全天候客服","24/7 全天候客服"),
    tri(lang,"Transparent pricing & full insurance","價格透明與全面保險","价格透明与全面保险"),
  ];
  const philosophy = WHY.slice(0,4);
  return (
    <React.Fragment>
      <PageHero image={A+"fleet-vans.png"} title={tri(lang,"About Fr8ight","關於 Fr8ight","关于 Fr8ight")} subtitle={tri(lang,"Your trusted partner in cross-border logistics and supply-chain excellence.","您在跨境物流與卓越供應鏈中值得信賴的夥伴。","您在跨境物流与卓越供应链中值得信赖的伙伴。")} />
      <section className="wk-section" style={{ paddingBottom:56 }}><div className="wk-container">
        <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:24 }}>
          {stats.map((s,i)=>(<div key={i} style={{ textAlign:"center", padding:"28px 12px", background:"hsl(var(--card))", border:"1px solid hsl(var(--border))", borderRadius:"var(--radius-lg)", boxShadow:"var(--shadow-sm)" }}>
            <div style={{ width:48, height:48, margin:"0 auto 12px", borderRadius:"var(--radius-md)", background:"hsl(var(--primary) / 0.1)", display:"flex", alignItems:"center", justifyContent:"center" }}><Ic d={s[2]} size={22} /></div>
            <div style={{ fontSize:28, fontWeight:800, color:"hsl(var(--foreground))" }}>{s[0]}</div>
            <div style={{ fontSize:13, color:"hsl(var(--muted-foreground))", marginTop:2 }}>{s[1]}</div></div>))}
        </div>
      </div></section>
      <section className="wk-section" style={{ paddingTop:0 }}><div className="wk-container" style={{ display:"grid", gridTemplateColumns:"1fr 1.1fr", gap:56, alignItems:"center" }}>
        <div style={{ borderRadius:"var(--radius-lg)", overflow:"hidden", boxShadow:"var(--shadow-lg)" }}><img src={A+"freight-truck.png"} alt="" style={{ width:"100%", display:"block" }} /></div>
        <div>
          <h2 style={{ fontSize:30, fontWeight:800, letterSpacing:"-0.02em", color:"hsl(var(--foreground))", margin:"0 0 16px" }}>{tri(lang,"Fr8ight — your cross-border logistics expert","Fr8ight – 您的跨境物流專家","Fr8ight – 您的跨境物流专家")}</h2>
          <p style={{ fontSize:15.5, lineHeight:1.7, color:"hsl(var(--muted-foreground))", margin:"0 0 24px" }}>{tri(lang,"With over 15 years of professional service, Fr8ight has become the logistics partner of choice connecting Hong Kong and the Mainland. We are committed to seamless, safe and efficient transport solutions for individuals and enterprises alike.","憑藉超過 15 年的專業服務經驗，Fr8ight 已成為連接香港與內地的首選物流合作夥伴。我們致力於為個人及企業客戶提供無縫、安全且高效的運輸解決方案。","凭借超过 15 年的专业服务经验，Fr8ight 已成为连接香港与内地的首选物流合作伙伴。我们致力于为个人及企业客户提供无缝、安全且高效的运输解决方案。")}</p>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"12px 24px" }}>
            {checks.map((c,i)=>(<div key={i} style={{ display:"flex", alignItems:"center", gap:10 }}><span style={{ color:"hsl(var(--primary))", flex:"none" }}><Ic d="M22 11.08V12a10 10 0 1 1-5.93-9.14M22 4 12 14.01l-3-3" size={18} /></span><span style={{ fontSize:14, color:"hsl(var(--foreground))" }}>{c}</span></div>))}
          </div>
        </div>
      </div></section>
      <section className="wk-section" style={{ background:"hsl(var(--muted))" }}><div className="wk-container">
        <div style={{ textAlign:"center", marginBottom:48 }}><div className="wk-eyebrow">{tri(lang,"Our Philosophy","我們的理念","我们的理念")}</div><h2 className="wk-h2">{tri(lang,"What we stand for","我們的堅持","我们的坚持")}</h2></div>
        <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:24 }}>
          {philosophy.map((w)=>(
            <div key={w.n} style={{ background:"hsl(var(--card))", border:"1px solid hsl(var(--border))", borderRadius:"var(--radius-lg)", padding:26, boxShadow:"var(--shadow-sm)" }}>
              <div style={{ width:48, height:48, borderRadius:"var(--radius-md)", background:"hsl(var(--primary) / 0.1)", display:"flex", alignItems:"center", justifyContent:"center", marginBottom:14 }}><Ic d={w.icon} size={22} /></div>
              <h3 style={{ fontSize:17, fontWeight:700, color:"hsl(var(--foreground))", margin:"0 0 8px" }}>{tri(lang,w.t.en,w.t.zh_TW,w.t.zh_CN)}</h3>
              <p style={{ fontSize:13.5, lineHeight:1.6, color:"hsl(var(--muted-foreground))", margin:0 }}>{tri(lang,w.d.en,w.d.zh_TW,w.d.zh_CN)}</p>
            </div>
          ))}
        </div>
      </div></section>
      <section className="wk-section"><div className="wk-container">
        <div style={{ textAlign:"center", marginBottom:56 }}><div className="wk-eyebrow">{tri(lang,"How to Order","下單流程","下单流程")}</div><h2 className="wk-h2">{tri(lang,"Five steps to ship","五步完成託運","五步完成托运")}</h2></div>
        <Flowchart steps={ORDER.map(o=>({t:o}))} lang={lang} />
      </div></section>
      <CTABand t={t} go={go} />
    </React.Fragment>
  );
}

/* ---------------- Blog ---------------- */
function postsData(lang) {
  return (getStore().posts || []).filter(p=>p.status==="published").map(p=>({
    category: pk(lang,p.cat), date: p.date, author: pk(lang,p.author), image: resolveImg(p.img),
    title: pk(lang,p.title), excerpt: pk(lang,p.excerpt), content: pk(lang,p.content),
  }));
}
function BlogPage({ t, lang, go }) {
  const all = postsData(lang);
  const [page, setPage] = useState(0);
  const per = 6;
  const pages = Math.ceil(all.length / per);
  const items = all.slice(page*per, page*per+per);
  return (
    <React.Fragment>
      <PageHero image={A+"moving-office.png"} title={tri(lang,"Insights & Articles","洞察與文章","洞察与文章")} subtitle={tri(lang,"Stay updated with industry trends and company news.","了解行業趨勢與公司動態。","了解行业趋势与公司动态。")} />
      <section className="wk-section"><div className="wk-container">
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:28 }}>
          {items.map((p,i)=>(
            <BlogCard key={page+"-"+i} {...p} ctaText={t.readMore} onClick={()=>go("article:"+(page*per+i))} />
          ))}
        </div>
        {pages>1 && (
          <div style={{ display:"flex", justifyContent:"center", alignItems:"center", gap:10, marginTop:44 }}>
            <button onClick={()=>{setPage(p=>Math.max(0,p-1));window.scrollTo(0,0);}} disabled={page===0} style={{ height:40, padding:"0 16px", borderRadius:"var(--radius-md)", border:"1px solid hsl(var(--border))", background:"hsl(var(--card))", cursor: page===0?"default":"pointer", opacity: page===0?0.4:1, fontSize:14, fontWeight:600, color:"hsl(var(--foreground))" }}>{tri(lang,"Previous","上一頁","上一页")}</button>
            {Array.from({length:pages}).map((_,i)=>(
              <button key={i} onClick={()=>{setPage(i);window.scrollTo(0,0);}} style={{ width:40, height:40, borderRadius:"var(--radius-md)", border:"1px solid "+(i===page?"hsl(var(--primary))":"hsl(var(--border))"), background: i===page?"hsl(var(--primary))":"hsl(var(--card))", color: i===page?"#fff":"hsl(var(--foreground))", fontWeight:700, cursor:"pointer" }}>{i+1}</button>
            ))}
            <button onClick={()=>{setPage(p=>Math.min(pages-1,p+1));window.scrollTo(0,0);}} disabled={page===pages-1} style={{ height:40, padding:"0 16px", borderRadius:"var(--radius-md)", border:"1px solid hsl(var(--border))", background:"hsl(var(--card))", cursor: page===pages-1?"default":"pointer", opacity: page===pages-1?0.4:1, fontSize:14, fontWeight:600, color:"hsl(var(--foreground))" }}>{tri(lang,"Next","下一頁","下一页")}</button>
          </div>
        )}
      </div></section>
      <CTABand t={t} go={go} />
    </React.Fragment>
  );
}

function ArticlePage({ idx, t, lang, go }) {
  const posts = postsData(lang);
  const p = posts[idx] || posts[0];
  const paras = [
    p.excerpt,
    tri(lang,"At Fr8ight we combine cross-border expertise with a dedicated operations team so every shipment is handled with care from pickup to final delivery.","在 Fr8ight，我們結合跨境專業與專屬營運團隊，讓每一票貨從取件到最終配送都得到細心處理。","在 Fr8ight，我们结合跨境专业与专属运营团队，让每一票货从取件到最终配送都得到细心处理。"),
    tri(lang,"Have a shipment in mind? Talk to our team for a tailored quote and a clear, transparent plan with no hidden surcharges.","有貨要寄？聯絡我們的團隊獲取客製化報價，以及清晰透明、無隱藏收費的方案。","有货要寄？联系我们的团队获取定制化报价，以及清晰透明、无隐藏收费的方案。"),
  ];
  return (
    <React.Fragment>
      <article style={{ maxWidth:820, margin:"0 auto", padding:"48px 24px 24px" }}>
        <a href="#" onClick={(e)=>{e.preventDefault();go("blog");}} style={{ fontSize:14, color:"hsl(var(--primary))" }}>{tri(lang,"← Back to Blog","← 返回部落格","← 返回博客")}</a>
        <div style={{ margin:"18px 0 12px" }}><Badge variant="secondary" pill>{p.category}</Badge></div>
        <h1 style={{ fontSize:38, fontWeight:800, letterSpacing:"-0.02em", lineHeight:1.15, color:"hsl(var(--foreground))", margin:"0 0 16px" }}>{p.title}</h1>
        <div style={{ display:"flex", gap:16, fontSize:14, color:"hsl(var(--muted-foreground))", marginBottom:24 }}>
          <span>{p.author}</span><span>·</span><span>{p.date}</span>
        </div>
        <img src={p.image} alt="" style={{ width:"100%", borderRadius:"var(--radius-lg)", boxShadow:"var(--shadow-md)", marginBottom:28 }} />
        {paras.map((para,i)=>(<p key={i} style={{ fontSize:16.5, lineHeight:1.8, color: i===0?"hsl(var(--foreground))":"hsl(var(--muted-foreground))", fontWeight: i===0?500:400, margin:"0 0 20px" }}>{para}</p>))}
        <div style={{ borderTop:"1px solid hsl(var(--border))", marginTop:24, paddingTop:24, display:"flex", justifyContent:"space-between", alignItems:"center", flexWrap:"wrap", gap:16 }}>
          <ShareButtons t={t} />
          <Button onClick={()=>go("contact")}>{t.quote}</Button>
        </div>
      </article>
      <section className="wk-section" style={{ paddingTop:32 }}><div className="wk-container">
        <h3 style={{ fontSize:22, fontWeight:700, color:"hsl(var(--foreground))", marginBottom:24 }}>{tri(lang,"Related articles","相關文章","相关文章")}</h3>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:28 }}>
          {posts.filter((_,i)=>i!==idx).slice(0,3).map((rp,i)=>{ const realIdx=posts.indexOf(rp); return <BlogCard key={i} {...rp} ctaText={t.readMore} onClick={()=>go("article:"+realIdx)} />; })}
        </div>
      </div></section>
    </React.Fragment>
  );
}

/* ---------------- Contact ---------------- */
function ContactPage({ t, lang }) {
  const pg = getStore().page || {};
  const info = [
    [tri(lang,"Office","門市地址","门市地址"), tri(lang,BRAND.addr.en,BRAND.addr.zh_TW,BRAND.addr.zh_CN)],
    ["WhatsApp", pg.whatsapp || BRAND.whatsapp],
    [tri(lang,"Phone","電話","电话"), pg.phone || BRAND.phone],
    ["Email", pg.email || BRAND.email],
    [tri(lang,"Hours","營業時間","营业时间"), tri(lang,BRAND.hours.en,BRAND.hours.zh_TW,BRAND.hours.zh_CN)],
    ["Facebook / Instagram", BRAND.facebook.replace("www.facebook.com/","fb: ")+" · IG: "+BRAND.instagram],
    [tri(lang,"Xiaohongshu (RED)","小紅書","小红书"), BRAND.xhs],
  ];
  return (
    <React.Fragment>
      <PageHero image={A+"delivery-van.png"} title={tri(lang,"Contact Us","聯絡我們","联系我们")} subtitle={tri(lang,"We're here to help with your logistics needs.","我們隨時準備好協助您的物流需求。","我们随时准备好协助您的物流需求。")} />
      <section className="wk-section"><div className="wk-container" style={{ display:"grid", gridTemplateColumns:"1.5fr 1fr", gap:48, alignItems:"start" }}>
        <div className="card-layout" style={{ padding:32 }}><ContactForm t={t} lang={lang} /></div>
        <div style={{ display:"flex", flexDirection:"column", gap:20 }}>
          {info.map((r,i)=>(<div key={i} style={{ borderLeft:"3px solid hsl(var(--primary))", paddingLeft:16 }}>
            <div style={{ fontSize:12, fontWeight:700, letterSpacing:"0.06em", textTransform:"uppercase", color:"hsl(var(--muted-foreground))" }}>{r[0]}</div>
            <div style={{ fontSize:15, color:"hsl(var(--foreground))", marginTop:4, lineHeight:1.5 }}>{r[1]}</div></div>))}
        </div>
      </div></section>
    </React.Fragment>
  );
}

/* ---------------- App router ---------------- */
function App() {
  const [lang, setLang] = useState("en");
  const [page, setPage] = useState("home");
  const [, setVer] = useState(0);
  useEffect(() => {
    // Visitors with no local edits get the published content.json (if uploaded next to this page).
    if (CMS && !CMS.hasLocal()) {
      CMS.fetchPublished((j) => { if (j) { setStore(j); setVer(v=>v+1); } });
    }
  }, []);
  const t = L[lang];
  const go = (p) => { setPage(p); window.scrollTo(0, 0); };
  let body;
  if (page === "home") body = <HomePage t={t} lang={lang} go={go} />;
  else if (page === "services") body = <ServicesPage t={t} lang={lang} go={go} />;
  else if (page.startsWith("svc:")) body = <ServiceDetailPage svcKey={page.slice(4)} t={t} lang={lang} go={go} />;
  else if (page === "cases") body = <CasesPage t={t} lang={lang} go={go} />;
  else if (page === "about") body = <AboutPage t={t} lang={lang} go={go} />;
  else if (page === "blog") body = <BlogPage t={t} lang={lang} go={go} />;
  else if (page.startsWith("article:")) body = <ArticlePage idx={parseInt(page.slice(8),10)} t={t} lang={lang} go={go} />;
  else if (page === "contact") body = <ContactPage t={t} lang={lang} />;
  return (
    <React.Fragment>
      <Header lang={lang} setLang={setLang} t={t} page={page} go={go} />
      {body}
      <OfficialChannels t={t} lang={lang} />
      <Footer t={t} lang={lang} go={go} />
      <FloatingWidget lang={lang} go={go} />
    </React.Fragment>
  );
}

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