/* ============================================================
   Shipstar — marketing landing (composes calculator + offer)
   ============================================================ */
const { useState:useStateLP, useEffect:useEffectLP, useRef:useRefLP } = React;

/* reveal-on-scroll (transform only) */
function useReveal(){
  const ref = useRefLP(null);
  useEffectLP(()=>{
    const el = ref.current; if(!el) return;
    const io = new IntersectionObserver(es=>es.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add('in'); io.unobserve(e.target);} }),{threshold:0.15});
    el.querySelectorAll('.rv,.rv2,.rv3').forEach(n=>io.observe(n));
    return ()=>io.disconnect();
  },[]);
  return ref;
}

const COPY = {
  en:{
    nav:['How it works','Calculator','Pricing','Contact'], start:'Start free', login:'Log in',
    eyebrow:'Vietnam → United States & Canada',
    h1a:'Launch your brand in', h1b:'North America', h1c:' — from Vietnam.',
    sub:'We warehouse, pick, pack, clear US & Canadian customs, and ship — so you sell in North America without running a single warehouse abroad.',
    cta1:'Calculate your savings', cta2:'See how it works',
    trust:[['shipped','$120M+','shipped for VN brands'],['brands','1,042','brands launched'],['fc','4','US & CA fulfillment centers']],
    hiwK:'How it works', hiwH:'From Saigon to a US doorstep — handled.',
    hiwL:'Four steps. You ship to us once; we run the rest across North America.',
    steps:[
      ['Send your inventory','Air or sea from Vietnam — we arrange freight and clear customs.','box'],
      ['We store & manage','Received, photographed and stocked across US & Canada FCs.','inventory'],
      ['An order comes in','TikTok Shop, Amazon, Shopify, Temu — synced automatically.','cart'],
      ['We pick, pack & ship','Duty handled, label printed, delivered in 2–3 days.','truck'],
    ],
    calcK:'See your numbers', calcH:'How much would you save?',
    calcL:'Running your own US warehouse is expensive. Drag the sliders — see the gap.',
    proofK:'Trusted by Vietnamese founders', proofH:'Brands already selling across the border.',
    priceK:'Pricing', priceH:'Simple plans. No hidden fees.', priceL:'Switch or cancel anytime. New sellers get Growth free for a year.',
    footTagline:'Cross-border fulfillment for Vietnamese brands.',
  },
  vi:{
    nav:['Cách hoạt động','Máy tính','Bảng giá','Liên hệ'], start:'Bắt đầu miễn phí', login:'Đăng nhập',
    eyebrow:'Việt Nam → Hoa Kỳ & Canada',
    h1a:'Đưa thương hiệu của bạn đến', h1b:'Bắc Mỹ', h1c:' — từ Việt Nam.',
    sub:'Chúng tôi lưu kho, pick, pack, thông quan Mỹ & Canada và giao hàng — để bạn bán ở Bắc Mỹ mà không cần kho riêng ở nước ngoài.',
    cta1:'Tính số tiền tiết kiệm', cta2:'Xem cách hoạt động',
    trust:[['shipped','$120Tr+','đã giao cho thương hiệu Việt'],['brands','1.042','thương hiệu đã ra mắt'],['fc','4','trung tâm tại Mỹ & Canada']],
    hiwK:'Cách hoạt động', hiwH:'Từ Sài Gòn đến tận cửa nhà ở Mỹ.',
    hiwL:'Bốn bước. Bạn gửi hàng một lần, chúng tôi lo phần còn lại trên khắp Bắc Mỹ.',
    steps:[
      ['Gửi hàng cho chúng tôi','Đường air hoặc sea từ Việt Nam — chúng tôi lo vận chuyển & hải quan.','box'],
      ['Lưu kho & quản lý','Nhận, chụp ảnh và lưu kho tại Mỹ & Canada.','inventory'],
      ['Có đơn hàng','TikTok Shop, Amazon, Shopify, Temu — tự động đồng bộ.','cart'],
      ['Pick, pack & giao','Lo thuế, in nhãn, giao trong 2–3 ngày.','truck'],
    ],
    calcK:'Xem con số của bạn', calcH:'Bạn sẽ tiết kiệm bao nhiêu?',
    calcL:'Tự vận hành kho ở Mỹ rất tốn kém. Kéo thanh trượt để thấy sự khác biệt.',
    proofK:'Được nhà sáng lập Việt tin dùng', proofH:'Các thương hiệu đã bán xuyên biên giới.',
    priceK:'Bảng giá', priceH:'Gói đơn giản. Không phí ẩn.', priceL:'Đổi hoặc hủy bất cứ lúc nào. Người bán mới được miễn phí Growth 1 năm.',
    footTagline:'Hoàn tất đơn hàng xuyên biên giới cho thương hiệu Việt.',
  },
};

function HeroVisual(){
  const stage = useRefLP(null);
  const [m,setM] = useStateLP({x:0,y:0});
  const onMove = (e)=>{
    const r = stage.current.getBoundingClientRect();
    setM({ x:((e.clientX-r.left)/r.width-0.5)*2, y:((e.clientY-r.top)/r.height-0.5)*2 });
  };
  const lyr = (depth)=>({ transform:`translate(${m.x*depth}px,${m.y*depth}px)` });
  return (
    <div className="hero-stage" ref={stage} onMouseMove={onMove} onMouseLeave={()=>setM({x:0,y:0})} aria-hidden="true">
      <div className="hero-layer" style={lyr(6)}>
        <svg className="hero-arc" viewBox="0 0 520 440" fill="none" preserveAspectRatio="none">
          <path d="M40 360 C 160 120, 360 120, 480 300" stroke="var(--brand)" strokeWidth="2.5" strokeDasharray="2 9" strokeLinecap="round" opacity="0.6" />
        </svg>
      </div>
      {/* origin pin VN */}
      <div className="hero-layer" style={lyr(14)}>
        <div className="pin" style={{left:18,top:344}}><span className="ring" style={{background:'var(--brand)'}} /><span className="lab">Hồ Chí Minh 🇻🇳</span></div>
      </div>
      {/* destination pins US + CA */}
      <div className="hero-layer" style={lyr(10)}>
        <div className="pin" style={{right:8,top:286}}><span className="ring" style={{background:'var(--green)'}} /><span className="lab">Austin, TX 🇺🇸</span></div>
        <div className="pin" style={{right:120,top:96}}><span className="ring" style={{background:'var(--blue)'}} /><span className="lab">Toronto, ON 🇨🇦</span></div>
      </div>
      <div className="hero-layer" style={lyr(22)}><div className="parcel"><Icon name="box" size={22} /></div></div>
      {/* floating cards */}
      <div className="hero-layer" style={lyr(30)}>
        <div className="float-card" style={{left:0,top:30}}>
          <span className="fc-ic" style={{background:'var(--brand-soft)',color:'var(--brand-deep)'}}><Icon name="cart" size={17} /></span>
          <div><div className="fc-t">New TikTok order</div><div className="fc-s">2× Hoi An vase · $76</div></div>
        </div>
      </div>
      <div className="hero-layer" style={lyr(38)}>
        <div className="float-card" style={{right:0,top:200}}>
          <span className="fc-ic" style={{background:'var(--green-soft)',color:'#0f6b40'}}><Icon name="check" size={17} /></span>
          <div><div className="fc-t">Delivered · 2 days</div><div className="fc-s">Customs cleared automatically</div></div>
        </div>
      </div>
    </div>
  );
}

function Landing(){
  const [lang,setLang] = useStateLP('en');
  const [scrolled,setScrolled] = useStateLP(false);
  const [prog,setProg] = useStateLP(0);
  const c = COPY[lang];
  const root = useReveal();

  useEffectLP(()=>{
    const onScroll = ()=>{
      const y = window.scrollY;
      setScrolled(y>40);
      const h = document.documentElement.scrollHeight - window.innerHeight;
      setProg(h>0 ? (y/h)*100 : 0);
    };
    window.addEventListener('scroll',onScroll,{passive:true}); onScroll();
    return ()=>window.removeEventListener('scroll',onScroll);
  },[]);
  const go = (id)=>{ const el=document.getElementById(id); el&&el.scrollIntoView({behavior:'smooth',block:'start'}); };

  return (
    <div className="lp" ref={root}>
      <div className="lp-progress" style={{width:prog+'%'}} />
      <nav className={'lp-nav'+(scrolled?' frost':'')}>
        <div className="lp-brand"><span className="lg"><Icon name="ship" size={18} /></span> Shipstar</div>
        <div className="lp-links">
          <a onClick={()=>go('how')}>{c.nav[0]}</a><a onClick={()=>go('calculator')}>{c.nav[1]}</a>
          <a onClick={()=>go('pricing')}>{c.nav[2]}</a><a onClick={()=>go('footer')}>{c.nav[3]}</a>
        </div>
        <div className="lp-nav-right">
          <div className="lang-tog"><button className={lang==='en'?'on':''} onClick={()=>setLang('en')}>EN</button><button className={lang==='vi'?'on':''} onClick={()=>setLang('vi')}>VI</button></div>
          <Button variant="ghost" size="sm" onClick={()=>{location.href='auth.html';}}>{c.login}</Button>
          <Button variant="brand" size="sm" onClick={()=>{location.href='auth.html?mode=signup';}}>{c.start}</Button>
        </div>
      </nav>

      {/* HERO */}
      <header className="lp-hero">
        <div className="lp-hero-bg">
          <div className="blob" style={{width:520,height:520,background:'var(--brand-soft)',top:-120,right:-80}} />
          <div className="blob" style={{width:440,height:440,background:'var(--blue-soft)',bottom:-160,left:-120}} />
        </div>
        <div>
          <div className="lp-eyebrow"><span className="fl">🇻🇳</span> {c.eyebrow} <span className="fl">🇺🇸🇨🇦</span></div>
          <h1>{c.h1a} <span className="accent">{c.h1b}</span>{c.h1c}</h1>
          <p className="sub">{c.sub}</p>
          <div className="lp-cta-row">
            <Button variant="brand" size="lg" iconRight="arrowR" onClick={()=>go('calculator')}>{c.cta1}</Button>
            <Button variant="ghost" size="lg" onClick={()=>go('how')}>{c.cta2}</Button>
          </div>
          <div className="lp-trust">
            {c.trust.map((t,i)=><Trust key={i} v={t[1]} l={t[2]} />)}
          </div>
        </div>
        <HeroVisual />
      </header>

      {/* HOW IT WORKS */}
      <section className="lp-sec" id="how">
        <div className="lp-kicker rv">{c.hiwK}</div>
        <h2 className="lp-h2 rv">{c.hiwH}</h2>
        <p className="lp-lead rv">{c.hiwL}</p>
        <div className="steps">
          <svg className="conn" viewBox="0 0 100 2" preserveAspectRatio="none"><line x1="0" y1="1" x2="100" y2="1" stroke="var(--border)" strokeWidth="2" strokeDasharray="3 4" /></svg>
          {c.steps.map((s,i)=>(
            <div className={'step '+(i===0?'rv':i===1?'rv':i===2?'rv2':'rv3')} key={i}>
              <div className="sn"><Icon name={s[2]} size={26} /><span className="badge">{i+1}</span></div>
              <h3>{s[0]}</h3><p>{s[1]}</p>
            </div>))}
        </div>
      </section>

      {/* SOCIAL PROOF */}
      <section className="lp-sec" style={{paddingTop:0}}>
        <div className="lp-kicker rv">{c.proofK}</div>
        <h2 className="lp-h2 rv" style={{marginBottom:36}}>{c.proofH}</h2>
        <div className="quotes">
          {[
            ['“We closed our LA warehouse. Shipstar ships faster and our landed cost dropped 31%.”','Trần Minh','Saigon Ceramics Co.','brand','SGC'],
            ['“Customs used to terrify me. Now I just send the container and orders go out.”','Phạm Lan','Mekong Naturals','green','MKN'],
            ['“TikTok Shop orders are picked and shipped same-day. My margin finally makes sense.”','Lê Quân','Hanoi Home Goods','blue','HHG'],
          ].map((q,i)=>(
            <div className={'quote '+(i===0?'rv':i===1?'rv2':'rv3')} key={i}>
              <p>{q[0]}</p>
              <div className="by"><SellerLogo tone={q[3]} text={q[4]} size={32} /><div><div className="nm">{q[1]}</div><div className="rl">{q[2]}</div></div></div>
            </div>))}
        </div>
        <div className="logo-row rv">
          {['Saigon Ceramics','Mekong Naturals','Hanoi Home','Da Nang Apparel','Hue Silk','Lotus Beauty','Bamboo & Co.'].map(l=><span className="lg" key={l}>{l}</span>)}
        </div>
      </section>

      {/* CALCULATOR */}
      <section className="lp-sec" style={{paddingTop:10}}>
        <div className="lp-kicker rv">{c.calcK}</div>
        <h2 className="lp-h2 rv">{c.calcH}</h2>
        <p className="lp-lead rv">{c.calcL}</p>
        <div className="rv"><SavingsCalculator /></div>
      </section>

      {/* OFFER */}
      <OfferBand />

      {/* PRICING */}
      <section className="lp-sec" id="pricing">
        <div className="lp-kicker rv">{c.priceK}</div>
        <h2 className="lp-h2 rv">{c.priceH}</h2>
        <p className="lp-lead rv">{c.priceL}</p>
        <div className="tiers">
          <Tier cls="rv" name="Starter" price="$0" unit="/mo + usage" desc="For new sellers testing US demand." feats={['Pay per order shipped','Standard 2–3 day delivery','1 sales channel','Email support']} cta="Start free" go={go} />
          <Tier cls="rv2" hot badge="1 year free — new sellers" name="Growth" price="$0" unit="year one ($1,200/yr)" desc="For brands scaling across North America." feats={['Everything in Starter','Volume shipping discounts','Unlimited channels (TikTok, Amazon…)','Profit & analytics dashboard','Priority onboarding']} cta="Claim free year" go={go} />
          <Tier cls="rv3" name="Scale" price="Custom" unit="" desc="For high-volume, multi-warehouse brands." feats={['Everything in Growth','Dedicated warehouse space','Account manager','API & custom integrations','Shipstar Boost credit line']} cta="Talk to sales" go={go} />
        </div>
      </section>

      {/* FOOTER */}
      <footer className="lp-foot" id="footer">
        <div className="lp-foot-in">
          <div style={{maxWidth:280}}>
            <div className="lp-brand" style={{marginBottom:10}}><span className="lg"><Icon name="ship" size={18} /></span> Shipstar</div>
            <p style={{fontSize:13.5,color:'var(--fg-3)',lineHeight:1.55}}>{c.footTagline}</p>
            <div className="lang-tog" style={{marginTop:14,display:'inline-flex'}}>
              <button className={lang==='en'?'on':''} onClick={()=>setLang('en')}>EN</button>
              <button className={lang==='vi'?'on':''} onClick={()=>setLang('vi')}>Tiếng Việt</button>
            </div>
          </div>
          <div className="col"><h4>Product</h4><a onClick={()=>go('how')}>How it works</a><a onClick={()=>go('calculator')}>Calculator</a><a onClick={()=>go('pricing')}>Pricing</a><a onClick={()=>{location.href='app.html';}}>Dashboard</a></div>
          <div className="col"><h4>Company</h4><a>About</a><a>Careers</a><a>Blog</a><a>Contact</a></div>
          <div className="col"><h4>Contact</h4><a>Zalo: 0900 000 000</a><a>hello@shipstar.vn</a><a>Hồ Chí Minh City</a></div>
        </div>
        <div style={{maxWidth:1180,margin:'28px auto 0',paddingTop:18,borderTop:'1px solid var(--border-2)',fontSize:12,color:'var(--fg-3)',display:'flex',justifyContent:'space-between',gap:12,flexWrap:'wrap'}}>
          <span>© 2026 Shipstar. Cross-border 3PL.</span><span>Terms · Privacy</span>
        </div>
      </footer>
      <ToastHost />
    </div>
  );
}

function Trust({ v, l }){
  // count up the numeric part if present
  const m = String(v).match(/^([^\d]*)([\d.,]+)(.*)$/);
  let display = v;
  if(m){ const num = parseFloat(m[2].replace(/,/g,'')); display = <CountTrust prefix={m[1]} value={num} raw={m[2]} suffix={m[3]} />; }
  return <div className="ti"><div className="v">{display}</div><div className="l">{l}</div></div>;
}
function CountTrust({ prefix, value, raw, suffix }){
  const dec = raw.includes('.')?(raw.split('.')[1].length):0;
  const shown = useCountUp(value, { prefix, suffix, decimals:dec });
  return <>{shown}</>;
}

function Tier({ cls, name, price, unit, desc, feats, cta, hot, badge, go }){
  return (
    <div className={'tier '+(hot?'hot ':'')+cls}>
      {badge && <span className="badge-free">{badge}</span>}
      <div className="tn">{name}</div>
      <div className="tp">{price}{unit && <small> {unit}</small>}</div>
      <div className="td">{desc}</div>
      <ul>{feats.map((f,i)=><li key={i}><Icon name="check" size={15} />{f}</li>)}</ul>
      <Button variant={hot?'brand':'ghost'} block onClick={()=>go('offer')}>{cta}</Button>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<Landing />);
