/* ============================================================
   Steps, Stats, Roadmap, Waitlist
   ============================================================ */

const STEPS = [
  {
    eye: "Step 01",
    title: "Post a load",
    desc: "Shipper enters pickup, drop-off, weight, and timeline. Live on the platform in under 60 seconds — no broker phone calls, no waiting for callbacks.",
    chips: ["Pickup · Drop", "Weight · Volume", "Truck type", "Timeline"],
  },
  {
    eye: "Step 02",
    title: "Bids come in",
    desc: "Drivers and carriers near you see the load instantly and submit competitive bids in real-time. The reverse auction drives price down to market truth.",
    chips: ["Real-time auction", "Driver rating shown", "Truck verified", "Bid history"],
  },
  {
    eye: "Step 03",
    title: "Pick & confirm",
    desc: "You see every offer side-by-side — price, rating, trips completed, truck type. Tap one bid and the shipment is locked in. Payment is held in escrow.",
    chips: ["Side-by-side compare", "One-tap confirm", "Escrow held", "ETA generated"],
  },
  {
    eye: "Step 04",
    title: "Track & pay",
    desc: "Live GPS the whole route. Digital proof-of-delivery at drop-off triggers instant payment release. No paperwork, no chasing.",
    chips: ["Live GPS", "Digital POD", "Instant payout", "Rate & review"],
  },
];

function Steps() {
  const [active, setActive] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setActive((a) => (a + 1) % STEPS.length), 5000);
    return () => clearInterval(t);
  }, []);
  const s = STEPS[active];
  return (
    <section className="section" id="how">
      <div className="section-head">
        <div>
          <div className="section-eyebrow">03 · How it works</div>
          <h2 className="section-title">Four taps from load to delivery.</h2>
        </div>
      </div>
      <div className="steps">
        <div className="step-tabs">
          {STEPS.map((step, i) => (
            <button
              key={i}
              className={"step-tab " + (i === active ? "active" : "")}
              onClick={() => setActive(i)}
            >
              <span className="num">{String(i + 1).padStart(2, "0")}</span>
              <span className="title">{step.title}</span>
            </button>
          ))}
        </div>
        <div className="step-panel" key={active}>
          <div className="step-panel-eye">{s.eye}</div>
          <h3 className="step-panel-title">{s.title}</h3>
          <p className="step-panel-desc">{s.desc}</p>
          <div className="step-panel-visual">
            {s.chips.map((c) => <span className="step-chip" key={c}>{c}</span>)}
          </div>
          <div className="step-panel-num">{String(active + 1).padStart(2, "0")}</div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Stats
   ============================================================ */

function AnimatedNumber({ to, suffix = "", duration = 1400, format = (n) => n.toLocaleString() }) {
  const [val, setVal] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    let started = false;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const start = performance.now();
          const tick = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(to * eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{format(Math.round(val))}{suffix}</span>;
}

function Stats() {
  return (
    <section className="section" id="market">
      <div className="section-head">
        <div>
          <div className="section-eyebrow">04 · Market</div>
          <h2 className="section-title">The market is huge — and almost entirely offline.</h2>
        </div>
      </div>
      <div className="stats">
        <div className="stat">
          <div className="stat-value">
            <AnimatedNumber to={180} /><span className="unit">B+ SAR</span>
          </div>
          <div className="stat-label">KSA Freight Market</div>
          <div className="stat-foot">Annual freight movement in Saudi Arabia alone.</div>
        </div>
        <div className="stat">
          <div className="stat-value">
            <AnimatedNumber to={60} /><span className="unit">B+ USD</span>
          </div>
          <div className="stat-label">GCC by 2027</div>
          <div className="stat-foot">Total addressable logistics market across the region.</div>
        </div>
        <div className="stat">
          <div className="stat-value">
            &lt;<AnimatedNumber to={5} /><span className="unit">%</span>
          </div>
          <div className="stat-label">Digitally enabled</div>
          <div className="stat-foot">Most loads still booked by phone and WhatsApp today.</div>
        </div>
        <div className="stat">
          <div className="stat-value">
            <AnimatedNumber to={90} /><span className="unit">%</span>
          </div>
          <div className="stat-label">Smartphone reach</div>
          <div className="stat-foot">Across the GCC — mobile-first carrier behaviour, already.</div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Roadmap + KSA map
   ============================================================ */

const PHASES = [
  {
    when: "Q3 · 2026",
    title: "Riyadh MVP launch",
    sub: "Closed pilot with 50 shippers and 200 vetted drivers in Riyadh.",
    cities: ["Riyadh"],
  },
  {
    when: "Q4 · 2026",
    title: "Commission live",
    sub: "Payments, ratings, driver subscriptions, and platform commission go live.",
    cities: ["Riyadh"],
  },
  {
    when: "Q1 · 2027",
    title: "KSA expansion",
    sub: "Jeddah, Dammam, Makkah, Tabuk — full coverage of all 13 provinces.",
    cities: ["Riyadh", "Jeddah", "Dammam", "Makkah", "Tabuk", "Abha", "Al-Madinah"],
  },
  {
    when: "Q4 · 2027",
    title: "GCC expansion",
    sub: "UAE, Kuwait, and Bahrain market entry. One platform, every emirate.",
    cities: ["Riyadh", "Jeddah", "Dammam", "Makkah", "Tabuk", "Abha", "Al-Madinah", "Dubai", "Kuwait City", "Manama"],
  },
];

// Approximate (x, y) on a 600x420 illustrative map (not geographically accurate, just suggestive)
const CITY_COORDS = {
  "Riyadh":      { x: 340, y: 220 },
  "Jeddah":      { x: 180, y: 250 },
  "Makkah":      { x: 195, y: 270 },
  "Al-Madinah":  { x: 200, y: 200 },
  "Tabuk":       { x: 175, y: 130 },
  "Dammam":      { x: 430, y: 195 },
  "Abha":        { x: 245, y: 340 },
  "Dubai":       { x: 510, y: 235 },
  "Kuwait City": { x: 420, y: 130 },
  "Manama":      { x: 430, y: 210 },
};

function KSAMap({ activeCities }) {
  return (
    <svg className="map-svg" viewBox="0 0 600 420" xmlns="http://www.w3.org/2000/svg">
      {/* very rough KSA + neighbours outline — stylized, NOT a real map */}
      <path
        d="M120 110 L210 80 L300 95 L380 80 L440 100 L470 150 L500 170 L545 210 L520 260 L470 290 L420 320 L360 350 L300 365 L240 360 L200 330 L170 290 L140 250 L110 200 Z"
        fill="oklch(0.22 0.008 60)"
        stroke="var(--border-strong)"
        strokeWidth="1"
        strokeDasharray="3 3"
      />
      {/* grid lines */}
      {[100, 200, 300, 400, 500].map((x) => (
        <line key={"v" + x} x1={x} y1="0" x2={x} y2="420" stroke="var(--border)" strokeWidth="0.5" opacity="0.4" />
      ))}
      {[100, 200, 300, 400].map((y) => (
        <line key={"h" + y} x1="0" y1={y} x2="600" y2={y} stroke="var(--border)" strokeWidth="0.5" opacity="0.4" />
      ))}

      {Object.entries(CITY_COORDS).map(([name, c]) => {
        const isActive = activeCities.includes(name);
        return (
          <g
            key={name}
            className={"city-node " + (isActive ? "active" : "dim")}
            transform={`translate(${c.x},${c.y})`}
          >
            <circle className="ring" r="6" />
            <circle className="core" r={isActive ? 5 : 3} />
            <text x="10" y="4">{name}</text>
          </g>
        );
      })}
    </svg>
  );
}

function Roadmap() {
  const [active, setActive] = React.useState(0);
  return (
    <section className="section" id="roadmap">
      <div className="section-head">
        <div>
          <div className="section-eyebrow">05 · Roadmap</div>
          <h2 className="section-title">Riyadh first. Then the Kingdom. Then the GCC.</h2>
        </div>
      </div>
      <div className="roadmap">
        <div className="map-card">
          <div className="card-head">
            <div className="card-head-title">Coverage map · {PHASES[active].when}</div>
            <div className="live-tag"><span className="dot" /> {PHASES[active].cities.length} cities</div>
          </div>
          <KSAMap activeCities={PHASES[active].cities} />
        </div>
        <div className="timeline-card">
          <div className="card-head">
            <div className="card-head-title">Phased rollout</div>
          </div>
          <div className="timeline-list">
            {PHASES.map((p, i) => (
              <div
                key={i}
                className={"tline " + (i === active ? "active" : "")}
                onMouseEnter={() => setActive(i)}
                onClick={() => setActive(i)}
              >
                <div className="when">{p.when}</div>
                <div className="what">
                  <div className="what-title">{p.title}</div>
                  <div className="what-sub">{p.sub}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Waitlist
   ============================================================ */

const ROLES = {
  shipper: {
    label: "I ship freight",
    headline: "Move loads faster — and stop overpaying brokers.",
    sub: "Get early-access pricing, a private onboarding session, and the first 90 days commission-free.",
    perks: [
      "First 90 days · zero commission on bids you accept",
      "Bulk-upload tool for fleets running >10 loads/week",
      "Dedicated onboarding with the founding team",
      "Early API access for fleet operators",
    ],
    fields: ["Company name", "Loads / month"],
  },
  driver: {
    label: "I drive / own trucks",
    headline: "Find loads on your route. Stop driving back empty.",
    sub: "Priority bid visibility for the first 6 months, free driver subscription, and instant payout on every job.",
    perks: [
      "Priority bid placement — free for 6 months",
      "Instant payout on delivery — no 30-day terms",
      "Match loads to your return route automatically",
      "Build a verified rating from day one",
    ],
    fields: ["Truck type", "Operating region"],
  },
};

function Waitlist({ defaultRole, sectionRef }) {
  const [role, setRole] = React.useState(defaultRole || "shipper");
  React.useEffect(() => { setRole(defaultRole || "shipper"); }, [defaultRole]);
  const [pos, setPos] = React.useState(1247);
  const [submitted, setSubmitted] = React.useState(false);
  const [email, setEmail] = React.useState("");
  const [name, setName] = React.useState("");
  const [extra, setExtra] = React.useState("");
  const [touched, setTouched] = React.useState(false);
  const toggleRef = React.useRef(null);
  const [sliderStyle, setSliderStyle] = React.useState({});

  // animate waitlist counter
  React.useEffect(() => {
    const i = setInterval(() => {
      if (Math.random() > 0.55) setPos((p) => p + 1);
    }, 2400);
    return () => clearInterval(i);
  }, []);

  // role toggle slider position
  React.useEffect(() => {
    if (!toggleRef.current) return;
    const btn = toggleRef.current.querySelector(`button[data-role="${role}"]`);
    if (!btn) return;
    setSliderStyle({
      transform: `translateX(${btn.offsetLeft - 4}px)`,
      width: btn.offsetWidth,
    });
  }, [role]);

  const r = ROLES[role];
  const emailValid = /\S+@\S+\.\S+/.test(email);

  function submit(e) {
    e.preventDefault();
    setTouched(true);
    if (!emailValid || !name) return;
    setSubmitted(true);
    setPos((p) => p + 1);
  }

  return (
    <section className="section" id="waitlist" ref={sectionRef}>
      <div className="section-head">
        <div>
          <div className="section-eyebrow">06 · Waitlist</div>
          <h2 className="section-title">Be on the platform when bids go live.</h2>
        </div>
      </div>

      <div className="waitlist">
        <div style={{ position: "relative", zIndex: 1 }}>
          <div className="role-toggle" ref={toggleRef}>
            <span className="slider" style={sliderStyle} />
            <button
              data-role="shipper"
              className={role === "shipper" ? "active" : ""}
              onClick={() => setRole("shipper")}
            >
              📦 Shipper
            </button>
            <button
              data-role="driver"
              className={role === "driver" ? "active" : ""}
              onClick={() => setRole("driver")}
            >
              🚚 Driver / Carrier
            </button>
          </div>
          <h3 className="waitlist-headline">{r.headline}</h3>
          <p className="waitlist-sub">{r.sub}</p>
          <ul className="role-perks">
            {r.perks.map((p) => (
              <li key={p}>
                <span className="check">✓</span>
                <span>{p}</span>
              </li>
            ))}
          </ul>
        </div>

        <div>
          {submitted ? (
            <div className="form">
              <div className="success-state">
                <div className="checkmark">✓</div>
                <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>
                  You're on the list.
                </div>
                <div className="pos">Your position</div>
                <div className="pos-num">#{pos.toLocaleString()}</div>
                <div style={{ color: "var(--fg-muted)", fontSize: 14, marginTop: 18, lineHeight: 1.5 }}>
                  We'll email <strong style={{ color: "var(--fg)" }}>{email}</strong> the moment your city goes live.
                  <br />Watch for an invite from <code style={{ color: "var(--accent)" }}>hello@truckee.sa</code>.
                </div>
                <button
                  className="btn btn-ghost"
                  style={{ marginTop: 22 }}
                  onClick={() => { setSubmitted(false); setEmail(""); setName(""); setExtra(""); setTouched(false); }}
                >
                  Sign someone else up
                </button>
              </div>
            </div>
          ) : (
            <form className="form" onSubmit={submit}>
              <div className="field">
                <label>Full name</label>
                <input
                  type="text"
                  placeholder="Your name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className={touched && !name ? "invalid" : ""}
                />
              </div>
              <div className="field">
                <label>Work email</label>
                <input
                  type="email"
                  placeholder="you@company.sa"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className={touched && !emailValid ? "invalid" : ""}
                />
              </div>
              <div className="form-row">
                <div className="field">
                  <label>{r.fields[0]}</label>
                  <input
                    type="text"
                    placeholder={role === "shipper" ? "Acme Trading Co." : "e.g. 40FT trailer"}
                    value={extra}
                    onChange={(e) => setExtra(e.target.value)}
                  />
                </div>
                <div className="field">
                  <label>{r.fields[1]}</label>
                  <select defaultValue="">
                    <option value="" disabled>Select</option>
                    {role === "shipper" ? (
                      <>
                        <option>1 – 5</option>
                        <option>6 – 25</option>
                        <option>26 – 100</option>
                        <option>100+</option>
                      </>
                    ) : (
                      <>
                        <option>Riyadh</option>
                        <option>Jeddah</option>
                        <option>Dammam</option>
                        <option>All KSA</option>
                      </>
                    )}
                  </select>
                </div>
              </div>
              <button className="submit" type="submit">
                Reserve my spot →
              </button>
              <div className="waitlist-counter">
                <span>{role === "shipper" ? "Shippers" : "Drivers"} signed up</span>
                <span className="num">{pos.toLocaleString()}</span>
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Steps, Stats, Roadmap, Waitlist });
