/* ============================================================
   Live bid auction simulator
   ============================================================ */

const BIDDER_POOL = [
  { name: "Al-Rajhi Freight", initials: "AR", rating: 4.9, trips: 1284, truck: "40FT" },
  { name: "Najd Logistics", initials: "NL", rating: 4.7, trips: 642, truck: "REEFER" },
  { name: "Hassan A.", initials: "HA", rating: 4.8, trips: 218, truck: "FLATBED" },
  { name: "Bin Saud Cargo", initials: "BS", rating: 4.6, trips: 891, truck: "40FT" },
  { name: "Khalid M.", initials: "KM", rating: 4.9, trips: 356, truck: "20FT" },
  { name: "Tabuk Express", initials: "TE", rating: 4.5, trips: 1102, truck: "40FT" },
  { name: "Saif R.", initials: "SR", rating: 4.8, trips: 174, truck: "REEFER" },
  { name: "Riyadh Heavy", initials: "RH", rating: 4.7, trips: 2031, truck: "LOWBED" },
];

const LOAD = {
  from: { city: "Riyadh", code: "RUH", meta: "Industrial City 2" },
  to: { city: "Jeddah", code: "JED", meta: "Port — Container Yard 4" },
  distance: "947 km",
  weight: "22 t",
  truck: "40FT trailer",
  pickup: "Tomorrow, 06:00",
  startAsk: 4200, // SAR
};

function rand(min, max) { return Math.random() * (max - min) + min; }
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }

function Route() {
  return (
    <div className="route">
      <div>
        <div className="pin from">A</div>
      </div>
      <div>
        <div className="city">{LOAD.from.city} <span style={{ color: "var(--fg-dim)", fontFamily: "var(--font-mono)", fontSize: 13, marginLeft: 6 }}>→ {LOAD.to.city}</span></div>
        <div className="meta">{LOAD.from.meta}  ·  to  ·  {LOAD.to.meta}</div>
        <div className="line" style={{ marginTop: 10 }}>
          <span className="dashes" />
          <span className="truck-glyph">{LOAD.distance} · {LOAD.truck}</span>
          <span className="dashes" />
        </div>
      </div>
      <div>
        <div className="pin to">B</div>
      </div>
    </div>
  );
}

function LiveAuction({ accent, sectionRef }) {
  const [bids, setBids] = React.useState([]);
  const [bidCounter, setBidCounter] = React.useState(0);
  const [accepted, setAccepted] = React.useState(null);
  const [watchers, setWatchers] = React.useState(34);
  const [running, setRunning] = React.useState(true);

  // initial seed bids
  React.useEffect(() => {
    const seeds = [];
    const sortedPool = [...BIDDER_POOL].sort(() => Math.random() - 0.5);
    let price = LOAD.startAsk;
    for (let i = 0; i < 3; i++) {
      const dec = Math.round(rand(80, 220) / 5) * 5;
      price = price - dec;
      seeds.push(makeBid(sortedPool[i], price, Date.now() - (3 - i) * 8000));
    }
    setBids(seeds);
    setBidCounter(seeds.length);
  }, []);

  function makeBid(bidder, amount, ts) {
    return {
      id: Math.random().toString(36).slice(2),
      bidder,
      amount,
      ts: ts || Date.now(),
    };
  }

  // auto-incoming bids
  React.useEffect(() => {
    if (!running || accepted) return;
    const t = setTimeout(() => {
      let added = false;
      setBids((cur) => {
        if (cur.length >= 12) return cur;
        const lowest = Math.min(...cur.map((b) => b.amount), LOAD.startAsk);
        // dynamic floor — never undercut below 2900, and stop the auction
        // from collapsing onto a single price by requiring at least 20 SAR
        // of headroom over the floor.
        const FLOOR = 2900;
        if (lowest <= FLOOR + 20) return cur; // auction settled — stop adding
        const taken = new Set(cur.map((b) => b.bidder.name));
        const existingAmounts = new Set(cur.map((b) => b.amount));
        const remaining = BIDDER_POOL.filter((b) => !taken.has(b.name));
        const bidder = remaining.length ? pick(remaining) : pick(BIDDER_POOL);
        const maxUndercut = Math.min(90, lowest - FLOOR - 5);
        const undercut = Math.round(rand(15, Math.max(20, maxUndercut)) / 5) * 5;
        let amount = Math.max(FLOOR, lowest - undercut);
        // avoid duplicate amounts already in the list
        while (existingAmounts.has(amount) && amount > FLOOR) amount -= 5;
        if (existingAmounts.has(amount)) return cur;
        added = true;
        return [makeBid(bidder, amount), ...cur].slice(0, 8);
      });
      if (added) {
        setBidCounter((c) => c + 1);
        setWatchers((w) => Math.max(20, w + Math.round(rand(-2, 4))));
      }
    }, rand(2400, 4200));
    return () => clearTimeout(t);
  }, [bids, running, accepted]);

  // sort by amount ascending (best/lowest bid wins)
  const sorted = [...bids].sort((a, b) => a.amount - b.amount);
  const best = sorted[0];

  function handleAccept(bid) {
    setAccepted(bid);
    setRunning(false);
  }

  function reset() {
    setBids([]);
    setBidCounter(0);
    setAccepted(null);
    setRunning(true);
    setTimeout(() => {
      const seeds = [];
      const sortedPool = [...BIDDER_POOL].sort(() => Math.random() - 0.5);
      let price = LOAD.startAsk;
      for (let i = 0; i < 3; i++) {
        const dec = Math.round(rand(80, 220) / 5) * 5;
        price = price - dec;
        seeds.push(makeBid(sortedPool[i], price, Date.now() - (3 - i) * 8000));
      }
      setBids(seeds);
      setBidCounter(seeds.length);
    }, 100);
  }

  return (
    <section className="section" id="auction" ref={sectionRef}>
      <div className="section-head">
        <div>
          <div className="section-eyebrow">02 · How it feels</div>
          <h2 className="section-title">Watch a load go to auction. Live.</h2>
        </div>
        <button className="btn btn-ghost" onClick={reset}>↻ Reset demo</button>
      </div>

      <div className="auction">
        {/* LOAD */}
        <div className="load-card">
          <div className="card-head">
            <div className="card-head-title">Load #TR-{(7421 + bidCounter).toString().padStart(5, "0")}</div>
            <div className="live-tag"><span className="dot" /> Live</div>
          </div>
          <Route />
          <div className="load-specs">
            <div>
              <div className="spec-label">Weight</div>
              <div className="spec-value">{LOAD.weight}</div>
            </div>
            <div>
              <div className="spec-label">Truck</div>
              <div className="spec-value">{LOAD.truck}</div>
            </div>
            <div>
              <div className="spec-label">Pickup</div>
              <div className="spec-value">{LOAD.pickup}</div>
            </div>
          </div>
          <div className="ask-row">
            <span className="lbl">Current best bid</span>
            <span className="val">
              {best && best.amount < LOAD.startAsk && (
                <span className="strike">SAR {LOAD.startAsk.toLocaleString()}</span>
              )}
              SAR {(best ? best.amount : LOAD.startAsk).toLocaleString()}
            </span>
          </div>
          {accepted ? (
            <div style={{
              marginTop: 18,
              padding: 14,
              borderRadius: 12,
              background: "oklch(0.86 0.19 150 / 0.08)",
              border: "1px solid oklch(0.86 0.19 150 / 0.4)",
              fontFamily: "var(--font-mono)",
              fontSize: 12,
              letterSpacing: "0.06em",
              color: "var(--live)",
            }}>
              ✓ DEAL CONFIRMED · {accepted.bidder.name} · SAR {accepted.amount.toLocaleString()}
            </div>
          ) : (
            <div className="try-hint">
              <span>Try it:</span>
              <span>Tap <kbd>Accept</kbd> on any bid to confirm the shipment.</span>
            </div>
          )}
        </div>

        {/* BIDS */}
        <div className="bids-card">
          <div className="card-head">
            <div className="card-head-title">Incoming bids · {bids.length}</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--fg-muted)" }}>
              <span style={{ color: "var(--live)" }}>●</span> {watchers} drivers watching
            </div>
          </div>
          <div className="bids-list">
            {sorted.map((b, i) => {
              const isBest = i === 0 && !accepted;
              const isAccepted = accepted && accepted.id === b.id;
              return (
                <div key={b.id} className={"bid-row " + (isAccepted ? "accepted" : isBest ? "best" : "")}>
                  <div className="avatar">{b.bidder.initials}</div>
                  <div>
                    <div className="bidder-name">{b.bidder.name}</div>
                    <div className="bidder-meta">
                      <span><span className="star">★</span> {b.bidder.rating}</span>
                      <span>· {b.bidder.trips} trips</span>
                      <span>· {b.bidder.truck}</span>
                    </div>
                  </div>
                  <div className="bid-amount">
                    SAR {b.amount.toLocaleString()}
                  </div>
                  {isAccepted ? (
                    <button className="bid-action success">✓ Won</button>
                  ) : (
                    <button
                      className={"bid-action " + (isBest ? "primary" : "")}
                      onClick={() => handleAccept(b)}
                      disabled={!!accepted}
                    >
                      Accept
                    </button>
                  )}
                </div>
              );
            })}
          </div>
          <div className="bids-foot">
            <div className="bids-stats">
              <span><strong>{bidCounter}</strong>bids total</span>
              <span><strong>−{best ? Math.round(((LOAD.startAsk - best.amount) / LOAD.startAsk) * 100) : 0}%</strong>vs ask</span>
              <span><strong>{Math.floor((Date.now() - (bids[bids.length - 1]?.ts || Date.now())) / 1000)}s</strong>since first bid</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { LiveAuction });
