// landing.jsx — hero globe, infinite carousel, features, steps
const { useMemo: useMemoL, useState: useStateL } = React;

// Real destination photo with a tuned "travel poster" fallback (so it never looks broken).
function DestImage({ id, photoId, country, w = 600, className, style, eager }) {
  const lookupId = photoId || id;
  const art = destArt(lookupId);
  const src = destPhoto(lookupId, w);
  const [loaded, setLoaded] = useStateL(false);
  const [failed, setFailed] = useStateL(!src);
  return (
    <div className={"destimg " + (className || "")} style={style}>
      {/* poster fallback — shown until/unless the real photo loads */}
      <div className="destimg-poster" style={{ background: `linear-gradient(165deg, ${art.sky[0]}, ${art.sky[1]})` }}>
        <div className="destimg-sun" style={{ background: art.sun, boxShadow: `0 0 50px 14px ${art.sun}` }}></div>
        <div className="destimg-range"></div>
        <div className="destimg-range two"></div>
        <div className="destimg-cap">{art.landmark}</div>
      </div>
      {!failed && (
        <img src={src} alt={country} loading={eager ? "eager" : "lazy"}
          className={"destimg-photo" + (loaded ? " in" : "")}
          onLoad={() => setLoaded(true)} onError={() => setFailed(true)} />
      )}
      <div className="destimg-scrim"></div>
    </div>
  );
}

function landingNetworkBadge(plan) {
  const net = String(plan?.net || "").trim();
  if (net && !/^4g\/5g$/i.test(net)) return net;
  return "";
}

function landingMoney(value) {
  const amount = Number(value);
  return Number.isFinite(amount) ? amount.toFixed(2) : "0.00";
}

function PlanCard({ plan, onClick }) {
  const networkBadge = landingNetworkBadge(plan);
  return (
    <div className="plan-card" onClick={() => onClick(plan)}>
      <div className="plan-banner">
        <DestImage id={plan.id} photoId={plan.photoId} country={plan.country} w={520} eager />
        <div className="plan-banner-top">
          {networkBadge && <span className="plan-net glass">{networkBadge}</span>}
          {plan.popular && <span className="plan-pop"><Ic.spark/> Popular</span>}
        </div>
        <div className="plan-banner-name">{plan.country}</div>
        <div className="plan-banner-region">{plan.region}{plan.popular ? " · Popular" : ""}</div>
      </div>
      <div className="plan-info">
        <div className="plan-foot">
          <div className="plan-data">{plan.data} <small>/ {plan.days}d</small></div>
          <div className="plan-price"><small>from</small> ${landingMoney(plan.displayPrice ?? plan.price)}</div>
        </div>
      </div>
    </div>
  );
}

function Marquee({ plans, speed, reverse, onClick }) {
  const dur = Math.max(8, 120 / Math.max(0.2, speed));
  const doubled = [...plans, ...plans];
  return (
    <div className="marquee">
      <div className="marquee-track" style={{ animationDuration: dur + "s", animationDirection: reverse ? "reverse" : "normal" }}>
        {doubled.map((p, i) => <PlanCard key={p.id + "-" + i} plan={p} onClick={onClick} />)}
      </div>
    </div>
  );
}

function landingCountrySlug(name) {
  return String(name || "")
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function Landing({ t, accent, go, onSelectPlan, onLogin, user, plans = [] }) {
  const globePlans = plans.length ? plans : FEATURED_PLANS;
  const carouselPlans = useMemoL(() => globePlans, [globePlans]);
  const rowA = carouselPlans.slice(0, Math.ceil(carouselPlans.length / 2));
  const rowB = carouselPlans.slice(Math.ceil(carouselPlans.length / 2));
  const openMarketplaceDestination = plan => {
    if (plan.type === "country" || plan.region !== "Bundles") {
      go(`marketplace/${landingCountrySlug(plan.country)}`);
      return;
    }
    go("marketplace");
  };
  const features = [
    { ic: <Ic.bolt/>, h: "Live in 60 seconds", p: "Scan a QR and you're online before you land. No store visits, no swapping tiny plastic SIMs." },
    { ic: <Ic.globe/>, h: "200+ destinations", p: "One app for every trip. Country plans, regional bundles, and a true global pass that follows you everywhere." },
    { ic: <Ic.signal/>, h: "Premium partner networks", p: "We choose plans around strong local operators where carrier data is available, without guessing unsupported network claims." },
    { ic: <Ic.shield/>, h: "Keep your number", p: "Your eSIM runs alongside your home line. Calls and texts stay on, data rides Journey." },
    { ic: <Ic.infinity/>, h: "No contracts, ever", p: "Pay once per trip. Top up when you need more. Nothing auto-renews behind your back." },
    { ic: <Ic.clock/>, h: "Buy now, use later", p: "Stock up before the airport. Plans wait quietly in My eSIMs until you choose to activate." },
  ];
  const steps = [
    { n: "01", h: "Pick a destination", p: "Browse plans by country or region and choose the data bundle that fits your trip." },
    { n: "02", h: "Get your eSIM", p: "Done in seconds. Your eSIM and QR code land instantly in My eSIMs, ready when you are." },
    { n: "03", h: "Scan & connect", p: "Open settings, scan the QR, tap activate. You're on a premium local network in under a minute." },
  ];

  return (
    <div>
      {/* hero */}
      <section className="hero container">
        <div className="hero-copy">
          <span className="eyebrow"><span className="dot"></span> eSIM marketplace · 200+ destinations</span>
          <h1>Stay online<br/>the moment you<br/><span className="grad">touch down.</span></h1>
          <p className="hero-sub">Journey turns your phone into a local line in over 200 countries. Buy a data plan in seconds, scan a QR, and connect to supported partner networks the instant you arrive.</p>
          <div className="hero-cta">
            <button className="btn btn-accent btn-lg" onClick={() => go("marketplace")}><Ic.globe/> Browse plans</button>
            <button className="btn btn-ghost btn-lg" onClick={() => (user ? go("myesims") : onLogin())}>{user ? "My eSIMs" : "How it works"} <Ic.arrow/></button>
          </div>
          <div className="hero-stats">
            <div><div className="s-num">200+</div><div className="s-lab">Destinations</div></div>
            <div><div className="s-num">4.9★</div><div className="s-lab">12k+ reviews</div></div>
            <div><div className="s-num">60s</div><div className="s-lab">Avg. setup</div></div>
          </div>
        </div>
        <div className="hero-globe">
          <Globe plans={globePlans} accent={accent} palette={t.globePalette === "accent" ? null : t.globePalette} spin={t.spinSpeed} dark={!t.light} onSelect={onSelectPlan} />
        </div>
      </section>

      {/* carousel */}
      <section style={{ padding: "30px 0 10px" }}>
        <div className="container" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 20 }}>
          <div>
            <span className="eyebrow"><span className="dot"></span> Trending now</span>
            <h2 style={{ fontFamily: "var(--font-d)", fontSize: "clamp(24px,3vw,38px)", letterSpacing: "-0.03em", margin: "10px 0 0" }}>Popular plans, moving fast</h2>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => go("marketplace")}>See all <Ic.arrow/></button>
        </div>
        <Marquee plans={rowA} speed={t.carouselSpeed} onClick={openMarketplaceDestination} />
        <Marquee plans={rowB} speed={t.carouselSpeed * 0.8} reverse onClick={openMarketplaceDestination} />
      </section>

      {/* features */}
      <section className="section container">
        <div className="section-head">
          <div>
            <span className="eyebrow"><span className="dot"></span> Why Journey</span>
            <h2>Travel data,<br/>done properly.</h2>
          </div>
          <p>We obsess over the boring parts — network quality, instant delivery, honest pricing — so connecting abroad finally feels effortless.</p>
        </div>
        <div className="feat-grid">
          {features.map(f => (
            <div className="feat" key={f.h}>
              <div className="feat-ic">{f.ic}</div>
              <h3>{f.h}</h3>
              <p>{f.p}</p>
            </div>
          ))}
        </div>
      </section>

      {/* steps */}
      <section className="section container steps-section" style={{ paddingTop: 0 }}>
        <div className="section-head">
          <div>
            <span className="eyebrow"><span className="dot"></span> How it works</span>
            <h2>Three taps to global data.</h2>
          </div>
        </div>
        <div className="steps">
          {steps.map(s => (
            <div className="step" key={s.n}>
              <span className="step-n">{s.n}</span>
              <h3>{s.h}</h3>
              <p>{s.p}</p>
            </div>
          ))}
        </div>
        <div className="steps-cta">
          <button className="btn btn-accent btn-lg" onClick={() => go("marketplace")}><Ic.spark/> Find your plan</button>
        </div>
      </section>

      {/* CTA band */}
      <section className="container" style={{ paddingBottom: 30 }}>
        <div className="card" style={{ padding: "48px 40px", textAlign: "center", position: "relative", overflow: "hidden",
          background: "linear-gradient(160deg, var(--bg-2), color-mix(in oklab, var(--bg-2), var(--accent) 10%))" }}>
          <h2 style={{ fontFamily: "var(--font-d)", fontSize: "clamp(26px,3.2vw,40px)", letterSpacing: "-0.03em", margin: "0 0 12px" }}>Your next trip is already connected.</h2>
          <p style={{ color: "var(--muted)", maxWidth: 460, margin: "0 auto 26px" }}>Grab a plan today, activate whenever you land. No commitment, no roaming bills.</p>
          <button className="btn btn-accent btn-lg" onClick={() => go("marketplace")}>Explore the marketplace <Ic.arrow/></button>
        </div>
      </section>

      <Footer go={go} />
    </div>
  );
}

function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="container footer-grid">
        <div style={{ maxWidth: 280 }}>
          <div className="brand" style={{ marginBottom: 12 }}><span className="brand-mark"></span> Journey</div>
          <p>Premium travel eSIMs for the always-connected. Online in 200+ countries.</p>
        </div>
        <div style={{ display: "flex", gap: 60, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 12 }}>Product</div>
            <div style={{ display: "grid", gap: 9, color: "var(--muted)", fontSize: 14 }}>
              <span style={{ cursor: "pointer" }} onClick={() => go("marketplace")}>Marketplace</span>
              <span style={{ cursor: "pointer" }} onClick={() => go("myesims")}>My eSIMs</span>
              <span>Coverage map</span>
            </div>
          </div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 12 }}>Company</div>
            <div style={{ display: "grid", gap: 9, color: "var(--muted)", fontSize: 14 }}>
              <span>About</span><span>Support</span><span>Privacy</span>
            </div>
          </div>
        </div>
      </div>
      <div className="container" style={{ marginTop: 36, paddingTop: 22, borderTop: "1px solid var(--line)", color: "var(--muted)", fontSize: 13 }}>
        © 2026 Journey eSIMs · Made for people who never stop moving.
      </div>
    </footer>
  );
}

Object.assign(window, { Landing, Marquee, PlanCard });
