// Listing detail page

function ListingDetail({ onNav, onBack, state, item, inventory, projects, watching, onWatch, onBid, onBuyNow, userBids }) {
  const cd = useCountdown(item.closesAt);
  const [photoIdx, setPhotoIdx] = React.useState(0);
  const [customBid, setCustomBid] = React.useState("");
  const [confirm, setConfirm] = React.useState(null); // {kind:'bid'|'buy', amount, qty}
  const isMultiQty = item.type === "premium" && item.quantity > 1;
  const [buyQty, setBuyQty] = React.useState(1);
  React.useEffect(() => { setBuyQty(1); }, [item.id]);
  React.useEffect(() => { if (buyQty > item.quantity) setBuyQty(Math.max(1, item.quantity)); }, [item.quantity]);
  const project = (projects || window.CLEARSPACE_PROJECTS || []).find((p) => p.id === item.projectId);
  const related = inventory.filter((x) => x.id !== item.id && x.projectId === item.projectId).slice(0, 3);
  const minBid = item.currentBid + 100;
  const quickBids = [minBid, minBid + 500, minBid + 2500];

  // Bid history is persisted per-item in a ref so timestamps can tick without being reset
  const historyRef = React.useRef(null);
  if (!historyRef.current || historyRef.current.lotId !== item.id) {
    const now = Date.now();
    historyRef.current = {
      lotId: item.id,
      entries: [
        { amt: item.currentBid, at: now - 4 * 60000, by: "Bidder #8" },
        { amt: item.currentBid - 400, at: now - 11 * 60000, by: "Bidder #3" },
        { amt: item.currentBid - 900, at: now - 28 * 60000, by: "Bidder #8" },
        { amt: item.currentBid - 1400, at: now - 52 * 60000, by: "Bidder #2" },
        { amt: item.startingBid, at: now - 3 * 3600000, by: "Opening" },
      ],
    };
  }
  // Track user's own bid entries
  const yourBid = userBids && userBids[item.id];
  React.useEffect(() => {
    if (yourBid && !historyRef.current.entries.some((e) => e.amt === yourBid && e.you)) {
      historyRef.current.entries = [{ amt: yourBid, at: Date.now(), by: "You", you: true }, ...historyRef.current.entries];
    }
  }, [yourBid]);
  // Tick to re-render timestamps every 30s
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setTick((n) => n + 1), 30000);
    return () => clearInterval(t);
  }, []);

  const doBid = (amt) => {
    if (amt < minBid) return;
    setConfirm({ kind: "bid", amount: amt });
  };
  const confirmBid = () => {
    onBid(item.id, confirm.amount);
    setCustomBid("");
    setConfirm(null);
  };
  const confirmBuy = () => {
    setConfirm(null);
    onBuyNow(item.id, confirm.qty || 1);
  };

  return (
    <div className="container listing-detail" style={{ padding: "28px 32px 80px" }}>
      {/* Back + breadcrumb */}
      <div className="row center gap-12" style={{ marginBottom: 20, flexWrap: "wrap" }}>
        <button className="btn btn-secondary btn-sm" onClick={() => onBack ? onBack("inventory") : onNav("inventory")}
          aria-label="Back" style={{ padding: "6px 12px" }}>
          <span style={{ display: "inline-flex", transform: "rotate(180deg)" }}><IcArrow size={14} /></span>
          <span>Back</span>
        </button>
        <div className="row center gap-8" style={{ fontSize: 13, color: "var(--ink-3)", flexWrap: "wrap" }}>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("inventory"); }} style={{ color: "var(--ink-2)", textDecoration: "none" }}>Inventory</a>
          <IcChev size={13} />
          <span>{typeLabel(item.type)}</span>
          <IcChev size={13} />
          <span className="mono" style={{ color: "var(--ink-2)" }}>{item.id}</span>
        </div>
      </div>

      <div className="stack-on-mobile" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 48 }}>
        {/* Left */}
        <div>
          {/* Gallery */}
          <div>
            <div style={{
              aspectRatio: "4/3", borderRadius: 14, overflow: "hidden",
              border: "1px solid var(--line)", background: "var(--bg-sunken)", position: "relative",
            }}>
              <img src={item.photos[photoIdx]} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              <div style={{ position: "absolute", top: 16, left: 16 }}>
                <span className={`tag ${typeTagClass(item.type)}`}>{typeLabel(item.type)}</span>
              </div>
              <div style={{ position: "absolute", top: 16, right: 16 }}>
                <button className="watch-btn" data-on={watching} onClick={() => onWatch(item.id)}>
                  {watching ? <IcBookmarkFill size={16} /> : <IcBookmark size={16} />}
                </button>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: `repeat(${item.photos.length}, 1fr)`, gap: 8, marginTop: 10 }}>
              {item.photos.map((p, i) => (
                <button key={i} onClick={() => setPhotoIdx(i)}
                  style={{
                    aspectRatio: "4/3", borderRadius: 8, overflow: "hidden",
                    border: `2px solid ${photoIdx === i ? "var(--ink)" : "transparent"}`,
                    padding: 0, cursor: "pointer", background: "var(--bg-sunken)",
                  }}>
                  <img src={p} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                </button>
              ))}
            </div>
          </div>

          {/* Header block */}
          <div style={{ marginTop: 36 }}>
            <div className="row center gap-12" style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 10 }}>
              <span className="mono">{item.id}</span>
              <span>·</span>
              <span>{item.brand}</span>
              <span>·</span>
              <span>{item.model}</span>
            </div>
            <h1 style={{ fontSize: 36, fontWeight: 600, letterSpacing: "-0.025em", lineHeight: 1.1, margin: 0 }}>
              {item.title}
            </h1>
            <div className="row gap-12" style={{ marginTop: 18, flexWrap: "wrap" }}>
              {item.tags.map((t) => <span key={t} className="pill">{t}</span>)}
            </div>
          </div>

          {/* Specs */}
          <div className="specs-grid" style={{
            display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 1,
            background: "var(--line)", border: "1px solid var(--line)", borderRadius: 12,
            marginTop: 28, overflow: "hidden",
          }}>
            {[
              { k: "Quantity", v: item.quantity.toLocaleString(), sub: item.quantity === 1 ? "unit" : "units" },
              { k: "Region", v: item.location.split(",")[0], sub: item.location.split(",")[1]?.trim() || "" },
              { k: "Type", v: typeLabel(item.type), sub: item.partOf ? `part of ${item.partOf}` : "standalone" },
            ].map((s) => (
              <div key={s.k} style={{ background: "var(--bg-elev)", padding: "18px 20px" }}>
                <div className="stat-kicker">{s.k}</div>
                <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em", marginTop: 6 }}>{s.v}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{s.sub}</div>
              </div>
            ))}
          </div>

          {/* Notes */}
          <div style={{ marginTop: 36 }}>
            <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0, marginBottom: 10 }}>Admin notes</h3>
            <p style={{ color: "var(--ink-2)", fontSize: 14, lineHeight: 1.65, margin: 0 }}>{item.notes}</p>
          </div>

          {/* Manifest — full inventory breakdown for whole lots */}
          {item.manifest && item.manifest.length > 0 && (
            <div style={{ marginTop: 32 }}>
              <div className="row between" style={{ alignItems: "flex-end", marginBottom: 12 }}>
                <div>
                  <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0, marginBottom: 4 }}>Full inventory manifest</h3>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{item.manifest.length} line items · {item.manifest.reduce((s, m) => s + m.qty, 0).toLocaleString()} units total</div>
                </div>
                <button className="btn btn-secondary btn-sm">
                  <IcDownload size={13} /> Export CSV
                </button>
              </div>
              <div style={{ border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden", background: "var(--bg-elev)" }}>
                <div style={{ display: "grid", gridTemplateColumns: "140px 1fr 90px", gap: 0, fontSize: 11,
                  fontFamily: "JetBrains Mono, monospace", letterSpacing: "0.08em", textTransform: "uppercase",
                  color: "var(--ink-3)", padding: "10px 16px", borderBottom: "1px solid var(--line)", background: "var(--bg-sunken)" }}>
                  <span>Category</span>
                  <span>Item</span>
                  <span style={{ textAlign: "right" }}>Qty</span>
                </div>
                {item.manifest.map((m, i) => (
                  <div key={i} style={{
                    display: "grid", gridTemplateColumns: "140px 1fr 90px", gap: 0,
                    padding: "10px 16px",
                    borderBottom: i < item.manifest.length - 1 ? "1px solid var(--line)" : "none",
                    fontSize: 13, alignItems: "center",
                  }}>
                    <span style={{ color: "var(--ink-3)", fontSize: 12 }}>{m.cat}</span>
                    <span style={{ color: "var(--ink)" }}>{m.brand}</span>
                    <span className="mono num" style={{ textAlign: "right", fontWeight: 600 }}>{m.qty.toLocaleString()}</span>
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 8, fontFamily: "JetBrains Mono, monospace" }}>
                Pulled from Deal Center · {item.sheet}
              </div>
            </div>
          )}

          {/* Logistics */}
          <div style={{ marginTop: 36, padding: 20, background: "var(--bg-sunken)", border: "1px solid var(--line)", borderRadius: 12 }}>
            <h3 style={{ fontSize: 15, fontWeight: 600, margin: 0, marginBottom: 12 }}>Logistics & fulfillment</h3>
            <div className="logistics-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <div className="row gap-8 center">
                <IcBox size={16} style={{ color: "var(--ink-3)" }} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>Buyer pickup</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Mon–Fri, 8am–4pm · address shared after purchase</div>
                </div>
              </div>
              <div className="row gap-8 center">
                <IcTruck size={16} style={{ color: "var(--ink-3)" }} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>Clearspace delivery</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Quoted within Bay Area post-win</div>
                </div>
              </div>
            </div>
          </div>

        </div>

        {/* Right: bid panel */}
        <div>
          <BidPanel item={item} cd={cd} variant={state.bidPanelVariant}
            customBid={customBid} setCustomBid={setCustomBid}
            minBid={minBid} quickBids={quickBids}
            doBid={doBid}
            isMultiQty={isMultiQty} buyQty={buyQty} setBuyQty={setBuyQty}
            onBuyNow={() => setConfirm({ kind: "buy", amount: item.buyNow * buyQty, qty: buyQty })}
            history={historyRef.current.entries}
            watching={watching.has(item.id)} onWatch={onWatch} />
        </div>
      </div>
      {confirm && (
        <ConfirmBidModal confirm={confirm} item={item}
          onCancel={() => setConfirm(null)}
          onConfirm={confirm.kind === "buy" ? confirmBuy : confirmBid} />
      )}
    </div>
  );
}

function BidPanel({ item, cd, variant, customBid, setCustomBid, minBid, quickBids, doBid, onBuyNow, watching, onWatch, history, isMultiQty, buyQty, setBuyQty }) {
  const buyTotal = item.buyNow * (isMultiQty ? buyQty : 1);
  return (
    <div className="bid-panel">
      {/* Timer */}
      <div className="row between center" style={{ marginBottom: 18 }}>
        <span className={"pill " + (cd.urgent ? "pill-amber" : "pill-primary")}>
          <span className="status-dot" />
          {cd.closed ? "Auction closed" : cd.urgent ? "Closing soon" : "Live auction"}
        </span>
        <span className="mono num" style={{ fontSize: 13, color: "var(--ink-2)", fontWeight: 500 }}>
          {cd.long}
        </span>
      </div>

      {/* Current bid */}
      <div style={{ marginBottom: 6 }}>
        <div className="stat-kicker">Current bid {isMultiQty && <span style={{ color: "var(--ink-3)", textTransform: "none", letterSpacing: 0, fontWeight: 400 }}> · bidding on 1 of {item.quantity}</span>}</div>
        <div className="bid-current mono" style={{ color: "var(--emerald)" }}>{fmt$(item.currentBid)}</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 6 }}>
          {item.bidCount} bid{item.bidCount === 1 ? "" : "s"} · floor {fmt$(item.startingBid)}
        </div>
      </div>

      <div className="hr" style={{ margin: "18px 0" }} />

      {/* Quick bids */}
      <div style={{ marginBottom: 12 }}>
        <div className="stat-kicker" style={{ marginBottom: 8 }}>Quick bid</div>
        <div className="bid-quick">
          {quickBids.map((q) => (
            <button key={q} onClick={() => doBid(q)}>{fmt$(q)}</button>
          ))}
        </div>
      </div>

      {/* Custom bid */}
      <div style={{ marginBottom: 14 }}>
        <div className="stat-kicker" style={{ marginBottom: 8 }}>Custom bid</div>
        <div className="row gap-8">
          <div style={{ position: "relative", flex: 1 }}>
            <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)", fontFamily: "JetBrains Mono", fontSize: 14 }}>$</span>
            <input className="input mono" placeholder={minBid.toLocaleString()}
              value={customBid} onChange={(e) => setCustomBid(e.target.value.replace(/[^0-9]/g, ""))}
              style={{ width: "100%", paddingLeft: 24 }} />
          </div>
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6 }}>Minimum next bid: <span className="mono">{fmt$(minBid)}</span></div>
      </div>

      <button className="btn btn-primary btn-lg btn-block"
        disabled={cd.closed || !customBid || Number(customBid) < minBid}
        onClick={() => doBid(Number(customBid))}>
        Place bid
      </button>

      {item.buyNow && (
        <>
          <div className="row center gap-8" style={{ margin: "16px 0", color: "var(--ink-3)" }}>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.1em" }}>OR</span>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
          </div>
          {isMultiQty && (
            <div style={{ marginBottom: 12 }}>
              <div className="row between center" style={{ marginBottom: 8 }}>
                <div className="stat-kicker">Quantity</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
                  <span className="mono">{item.quantity}</span> available · <span className="mono">{fmt$(item.buyNow)}</span> each
                </div>
              </div>
              <div className="qty-stepper">
                <button aria-label="Decrease quantity" className="qty-btn"
                  onClick={() => setBuyQty((q) => Math.max(1, q - 1))}
                  disabled={buyQty <= 1}>−</button>
                <div className="mono qty-value" aria-label="Quantity">{buyQty}</div>
                <button aria-label="Increase quantity" className="qty-btn"
                  onClick={() => setBuyQty((q) => Math.min(item.quantity, q + 1))}
                  disabled={buyQty >= item.quantity}>+</button>
              </div>
            </div>
          )}
          <button className="btn btn-dark btn-lg btn-block" onClick={onBuyNow} disabled={cd.closed || (isMultiQty && item.quantity < 1)}>
            Buy now · {fmt$(buyTotal)}
          </button>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 8, textAlign: "center" }}>
            {isMultiQty && buyQty < item.quantity
              ? `Locks ${buyQty} of ${item.quantity} for your company. Auction continues on the rest.`
              : "Closes auction instantly and locks inventory."}
          </div>
        </>
      )}

      <button className="btn btn-secondary btn-block" style={{ marginTop: 16 }}
        onClick={() => onWatch(item.id)}>
        {watching ? <><IcBookmarkFill size={15} /> Saved to watchlist</> : <><IcBookmark size={15} /> Save to watchlist</>}
      </button>

      {variant === "expanded" && (
        <div style={{ marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
          <div className="stat-kicker" style={{ marginBottom: 10 }}>Bid history</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {(history || []).map((b, i, arr) => (
              <div key={i}
                style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", alignItems: "center",
                  fontSize: 13, padding: "8px 8px",
                  borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
                  background: b.you ? "rgba(16,185,129,0.06)" : "transparent",
                  borderRadius: b.you ? 6 : 0 }}>
                <span className="mono num" style={{ fontWeight: 500, textAlign: "left" }}>{fmt$(b.amt)}</span>
                <span style={{ color: b.you ? "var(--emerald)" : "var(--ink-3)", fontSize: 12, fontWeight: b.you ? 600 : 400, textAlign: "center" }}>
                  {b.you ? "You" : b.by}
                </span>
                <span style={{ color: "var(--ink-3)", fontSize: 12, textAlign: "right" }}>{relTime(b.at)}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function relTime(ts) {
  const d = Date.now() - ts;
  const s = Math.floor(d / 1000);
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

function ConfirmBidModal({ confirm, item, onCancel, onConfirm }) {
  const isBuy = confirm.kind === "buy";
  const qty = confirm.qty || 1;
  const isMulti = isBuy && qty > 1;
  const closesAuction = isBuy && qty >= item.quantity;
  return (
    <div onClick={onCancel} style={{
      position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)",
      display: "grid", placeItems: "center", zIndex: 200, padding: 24,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: "var(--bg-elev)", borderRadius: 14, width: "min(480px, 100%)",
        border: "1px solid var(--line)", overflow: "hidden",
      }}>
        <div style={{ padding: "22px 26px 18px", borderBottom: "1px solid var(--line)" }}>
          <div className="stat-kicker">{isBuy ? "Confirm buy now" : "Confirm bid"}</div>
          <div style={{ fontSize: 18, fontWeight: 600, marginTop: 6, letterSpacing: "-0.01em" }}>
            {isBuy
              ? (isMulti
                ? <>Buy <span className="mono" style={{ color: "var(--emerald)" }}>{qty} × {fmt$(item.buyNow)}</span> = <span className="mono" style={{ color: "var(--emerald)" }}>{fmt$(confirm.amount)}</span>?</>
                : <>Instantly close this auction at <span className="mono" style={{ color: "var(--emerald)" }}>{fmt$(confirm.amount)}</span>?</>)
              : <>Place a bid of <span className="mono" style={{ color: "var(--emerald)" }}>{fmt$(confirm.amount)}</span>?</>}
          </div>
        </div>
        <div style={{ padding: "18px 26px", background: "var(--bg-sunken)", borderBottom: "1px solid var(--line)" }}>
          <div className="row gap-12 center" style={{ fontSize: 13, color: "var(--ink-2)" }}>
            <img src={item.photos[0]} style={{ width: 54, height: 54, objectFit: "cover", borderRadius: 6 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 13, color: "var(--ink)", marginBottom: 2, lineClamp: 1 }}>{item.title}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{item.id} · {item.location}</div>
            </div>
          </div>
        </div>
        <div style={{ padding: "16px 26px", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>
          {isBuy
            ? (isMulti && !closesAuction
              ? `Locks ${qty} of ${item.quantity} units to your company. Auction continues on the remaining ${item.quantity - qty}.`
              : "This ends the auction immediately and locks the inventory to your company. You'll be routed to logistics and payment next.")
            : "Bids are binding under your buyer agreement. If you're the highest bidder when the timer ends, the lot is yours."}
        </div>
        <div style={{ padding: "14px 20px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-end", gap: 10 }}>
          <button className="btn btn-secondary" onClick={onCancel}>Cancel</button>
          <button className={isBuy ? "btn btn-dark" : "btn btn-primary"} onClick={onConfirm}>
            {isBuy
              ? (isMulti ? `Buy ${qty} · ${fmt$(confirm.amount)}` : `Buy now · ${fmt$(confirm.amount)}`)
              : `Place bid · ${fmt$(confirm.amount)}`}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ListingDetail });