/* ─────────────────────────────────────────────────────
   Equipment Balkans — Browse + Detail screens
───────────────────────────────────────────────────── */
const { useState: useStateBD, useEffect: useEffectBD, useMemo, useRef: useRefBD } = React;

// ════════════════════════════════════════════════════
// BROWSE SCREEN
// ════════════════════════════════════════════════════
function BrowseScreen({ store, onNav, onWatch, watchlist, initialCategory }) {
  const [filter, setFilter] = useStateBD("all");
  const [q, setQ] = useStateBD("");
  const [cat, setCat] = useStateBD(initialCategory || "All");
  const [sort, setSort] = useStateBD("ending");

  const auctions = store.auctions.filter((a) => a.channel !== "marketplace");
  const cats = ["All", ...Array.from(new Set(auctions.map((a) => a.category)))];

  const counts = {
    all: auctions.length,
    live: auctions.filter((a) => a.status === "live").length,
    upcoming: auctions.filter((a) => a.status === "upcoming").length,
    ended: auctions.filter((a) => a.status === "ended" || a.status === "settled").length,
  };

  const filtered = useMemo(() => {
    let list = auctions.filter((a) => {
      const statusOk =
        filter === "all" ||
        (filter === "ended" ? a.status === "ended" || a.status === "settled" : a.status === filter);
      const catOk = cat === "All" || a.category === cat;
      const qOk = !q || a.title.toLowerCase().includes(q.toLowerCase()) || a.manufacturer.toLowerCase().includes(q.toLowerCase());
      return statusOk && catOk && qOk;
    });
    list = [...list].sort((a, b) => {
      if (sort === "ending") return a.endsAt - b.endsAt;
      if (sort === "priceLow") return (a.currentBid ?? a.startingPrice) - (b.currentBid ?? b.startingPrice);
      if (sort === "priceHigh") return (b.currentBid ?? b.startingPrice) - (a.currentBid ?? a.startingPrice);
      if (sort === "bids") return b.bidCount - a.bidCount;
      return 0;
    });
    return list;
  }, [auctions, filter, cat, q, sort]);

  const FILTERS = [
    { v: "all", l: "All" },
    { v: "live", l: "Live" },
    { v: "upcoming", l: "Upcoming" },
    { v: "ended", l: "Ended" },
  ];

  return (
    <div>
      {/* Hero strip */}
      <div style={{ position: "relative", overflow: "hidden", borderBottom: "1px solid var(--border)" }}>
        <EquipImage
          src={"https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=1800&h=600&fit=crop&auto=format&q=80"}
          alt=""
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
        />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(15,23,42,1) 0%, rgba(15,23,42,0.78) 42%, rgba(15,23,42,0.20) 100%)" }}></div>
        <div style={{ position: "relative", maxWidth: 1440, margin: "0 auto", padding: "52px 24px 40px" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11, fontWeight: 800, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ignite)", marginBottom: 16 }}>
            <i data-lucide="gavel" style={{ width: 14, height: 14 }}></i>
            Live Equipment Auctions
          </span>
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 52, fontWeight: 900, lineHeight: 1.02, color: "#fff", letterSpacing: "-0.01em", maxWidth: 760, margin: 0, textTransform: "uppercase" }}>
            Bid on heavy equipment<br />across the Balkans.
          </h1>
          <p style={{ fontSize: 15.5, color: "rgba(248,250,252,0.7)", marginTop: 16, maxWidth: 520, lineHeight: 1.6 }}>
            Excavators, cranes, CNC machines and more — inspected, verified and sold to the highest bidder. New lots open daily.
          </p>
          <div style={{ display: "flex", gap: 30, marginTop: 28, flexWrap: "wrap" }}>
            {[
              ["clock", counts.live, "Live now"],
              ["calendar-clock", counts.upcoming, "Upcoming"],
              ["users", "680+", "Verified sellers"],
              ["globe", "32", "Countries"],
            ].map(([ico, val, lbl]) => (
              <div key={lbl} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <i data-lucide={ico} style={{ width: 18, height: 18, color: "var(--text-3)" }}></i>
                <div>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 18, fontWeight: 700, color: "#fff", lineHeight: 1 }}>{val}</div>
                  <div style={{ fontSize: 9.5, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--text-3)", marginTop: 3 }}>{lbl}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Toolbar */}
      <div style={{ position: "sticky", top: "calc(64px + var(--eb-statusbar-h, 0px))", zIndex: 30, background: "var(--header-bg)", backdropFilter: "blur(10px)", borderBottom: "1px solid var(--border)" }}>
        <div style={{ maxWidth: 1440, margin: "0 auto", padding: "14px 24px", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 4, background: "var(--surface)", borderRadius: 8, padding: 4, border: "1px solid var(--border)" }}>
            {FILTERS.map((f) => (
              <button
                key={f.v}
                onClick={() => setFilter(f.v)}
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 6,
                  padding: "7px 14px",
                  borderRadius: 6,
                  fontSize: 12.5,
                  fontWeight: 700,
                  color: filter === f.v ? "#fff" : "var(--text-3)",
                  background: filter === f.v ? "var(--ignite)" : "transparent",
                  transition: "all .15s",
                }}
              >
                {f.l}
                <span style={{ fontSize: 11, opacity: 0.7, fontFamily: "var(--ff-mono)" }}>{counts[f.v]}</span>
              </button>
            ))}
          </div>

          <div style={{ position: "relative", flex: 1, minWidth: 200, maxWidth: 360 }}>
            <i data-lucide="search" style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", width: 15, height: 15, color: "var(--text-3)" }}></i>
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Search make or model…"
              style={{
                width: "100%",
                background: "var(--surface)",
                border: "1px solid var(--border)",
                borderRadius: 8,
                padding: "9px 12px 9px 34px",
                fontSize: 13,
                color: "var(--text)",
                outline: "none",
              }}
            />
          </div>

          <select value={cat} onChange={(e) => setCat(e.target.value)} style={selectStyle}>
            {cats.map((c) => (
              <option key={c} value={c}>{c === "All" ? "All categories" : c}</option>
            ))}
          </select>

          <select value={sort} onChange={(e) => setSort(e.target.value)} style={{ ...selectStyle, marginLeft: "auto" }}>
            <option value="ending">Ending soonest</option>
            <option value="priceLow">Price: low to high</option>
            <option value="priceHigh">Price: high to low</option>
            <option value="bids">Most bids</option>
          </select>
        </div>
      </div>

      {/* Grid */}
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "28px 24px 20px" }}>
        <div style={{ fontSize: 13, color: "var(--text-3)", marginBottom: 18 }}>
          {filtered.length} lot{filtered.length !== 1 ? "s" : ""}
        </div>
        {filtered.length === 0 ? (
          <div style={{ textAlign: "center", padding: "80px 0", color: "var(--text-3)" }}>
            <i data-lucide="search-x" style={{ width: 44, height: 44, opacity: 0.4 }}></i>
            <p style={{ marginTop: 14, fontSize: 14 }}>No auctions match your filters.</p>
          </div>
        ) : (
          <div className="eb-card-grid">
            {filtered.map((a) => (
              <AuctionCard
                key={a.id}
                auction={a}
                onOpen={(id) => onNav({ name: "detail", id })}
                watched={watchlist.includes(a.id)}
                onWatch={onWatch}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

const selectStyle = {
  background: "var(--surface)",
  border: "1px solid var(--border)",
  borderRadius: 8,
  padding: "9px 12px",
  fontSize: 12.5,
  fontWeight: 600,
  color: "var(--text-2)",
  outline: "none",
  cursor: "pointer",
};

// ════════════════════════════════════════════════════
// DETAIL SCREEN
// ════════════════════════════════════════════════════
function DetailScreen({ store, auctionId, user, onNav, onWatch, watchlist, onBid, wallet, onAddCard, onPreauth, onInspect }) {
  const auction = store.auctions.find((a) => a.id === auctionId);
  const [activeImg, setActiveImg] = useStateBD(0);
  const [showVideo, setShowVideo] = useStateBD(false);
  const [bidAmount, setBidAmount] = useStateBD("");
  const [maxBid, setMaxBid] = useStateBD("");
  const [bidErr, setBidErr] = useStateBD("");

  useEffectBD(() => {
    setActiveImg(0);
    setShowVideo(false);
    window.scrollTo(0, 0);
  }, [auctionId]);

  if (!auction) {
    return (
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "80px 24px", textAlign: "center", color: "var(--text-3)" }}>
        <i data-lucide="package-x" style={{ width: 48, height: 48, opacity: 0.4 }}></i>
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 26, color: "var(--text)", margin: "16px 0 8px" }}>Auction not found</h2>
        <button onClick={() => onNav({ name: "auctions" })} style={primaryBtn}>Browse auctions</button>
      </div>
    );
  }

  const isLive = auction.status === "live";
  const isUpcoming = auction.status === "upcoming";
  const isEnded = auction.status === "ended" || auction.status === "settled";
  const isMarket = auction.channel === "marketplace";
  const needsPreauth = (Number(auction.startingPrice) || 0) >= (window.HIGH_VALUE_THRESHOLD || 500);
  const hasCard = !!(wallet && wallet.card);
  const hasPreauth = !!(wallet && wallet.preauths && wallet.preauths[auction.id] && wallet.preauths[auction.id].status === "held");
  const bidEligible = hasCard && (!needsPreauth || hasPreauth);
  const watched = watchlist.includes(auction.id);
  const bids = store.bidHistory[auction.id] || [];
  const price = auction.currentBid ?? auction.startingPrice;
  const minNext = (auction.currentBid ?? auction.startingPrice) + auction.minIncrement;
  const isOwnerView = user && auction.seller.name === user.name;

  const submitBid = (e) => {
    e.preventDefault();
    setBidErr("");
    const amt = Number(bidAmount);
    if (!amt || amt < minNext) {
      setBidErr(`Enter at least ${eur(minNext)}.`);
      return;
    }
    if (maxBid && Number(maxBid) < amt) {
      setBidErr("Max bid must be ≥ your bid.");
      return;
    }
    onBid(auction.id, amt, maxBid ? Number(maxBid) : null);
    setBidAmount("");
    setMaxBid("");
  };

  const galleryImages = auction.images;

  return (
    <div style={{ maxWidth: 1440, margin: "0 auto", padding: "22px 24px 40px" }}>
      {/* Breadcrumb / back */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--text-3)", marginBottom: 18 }}>
        <button onClick={() => onNav({ name: "auctions" })} style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--text-2)", fontWeight: 600 }}>
          <i data-lucide="arrow-left" style={{ width: 15, height: 15 }}></i> Auctions
        </button>
        <span>/</span>
        <span>{auction.category}</span>
        <span>/</span>
        <span style={{ color: "var(--text-2)" }}>{auction.title}</span>
      </div>

      {/* Title row */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 20, marginBottom: 22, flexWrap: "wrap" }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <StatusBadge status={auction.status} big />
            <span style={{ fontSize: 12.5, color: "var(--text-3)", display: "inline-flex", alignItems: "center", gap: 5 }}>
              <i data-lucide="map-pin" style={{ width: 13, height: 13 }}></i> {auction.location}
            </span>
          </div>
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 38, fontWeight: 900, color: "var(--text)", lineHeight: 1.08, margin: 0, textTransform: "uppercase", letterSpacing: "-0.01em" }}>
            {auction.title}
          </h1>
        </div>
        <button
          onClick={() => onWatch(auction.id)}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            border: `1px solid ${watched ? "var(--ignite)" : "var(--border-s)"}`,
            color: watched ? "var(--ignite)" : "var(--text-2)",
            background: watched ? "rgba(249,115,22,0.08)" : "transparent",
            padding: "10px 16px",
            borderRadius: 6,
            fontSize: 13,
            fontWeight: 700,
          }}
        >
          <i data-lucide="heart" style={{ width: 15, height: 15, fill: watched ? "var(--ignite)" : "none" }}></i>
          {watched ? "Watching" : "Watch"}
        </button>
      </div>

      {/* Main grid */}
      <div className="eb-detail-grid">
        {/* Left: media + info */}
        <div style={{ minWidth: 0 }}>
          {/* Gallery / video */}
          <div style={{ borderRadius: 12, overflow: "hidden", border: "1px solid var(--border)", background: "var(--media-bg)" }}>
            <div style={{ position: "relative", aspectRatio: "16/10", background: "var(--media-bg)" }}>
              {showVideo ? (
                <video
                  src={store.video}
                  poster={galleryImages[0]}
                  controls
                  autoPlay
                  style={{ width: "100%", height: "100%", objectFit: "cover", background: "#000" }}
                ></video>
              ) : (
                <EquipImage src={galleryImages[activeImg]} alt={auction.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              )}
              {!showVideo && auction.hasVideo && (
                <button
                  onClick={() => setShowVideo(true)}
                  style={{
                    position: "absolute",
                    inset: 0,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: "rgba(11,19,34,0.25)",
                  }}
                >
                  <span style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
                    <span style={{ width: 64, height: 64, borderRadius: "50%", background: "rgba(249,115,22,0.92)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 28px rgba(249,115,22,0.5)" }}>
                      <i data-lucide="play" style={{ width: 26, height: 26, color: "#fff", fill: "#fff", marginLeft: 3 }}></i>
                    </span>
                    <span style={{ fontSize: 12, fontWeight: 700, color: "#fff", textTransform: "uppercase", letterSpacing: ".08em", textShadow: "0 1px 6px rgba(0,0,0,0.6)" }}>
                      {isLive ? "Watch live walkaround" : "Watch walkaround"}
                    </span>
                  </span>
                </button>
              )}
              {showVideo && (
                <button onClick={() => setShowVideo(false)} style={{ position: "absolute", top: 12, right: 12, width: 32, height: 32, borderRadius: 6, background: "rgba(15,23,42,0.8)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <i data-lucide="x" style={{ width: 16, height: 16 }}></i>
                </button>
              )}
            </div>
            {/* Thumbnails */}
            <div style={{ display: "flex", gap: 8, padding: 10, background: "var(--surface)" }}>
              {auction.hasVideo && (
                <button
                  onClick={() => setShowVideo(true)}
                  style={{ ...thumb, borderColor: showVideo ? "var(--ignite)" : "var(--border)", position: "relative" }}
                >
                  <EquipImage src={galleryImages[0]} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", opacity: 0.6 }} />
                  <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <i data-lucide="play" style={{ width: 16, height: 16, color: "#fff", fill: "#fff" }}></i>
                  </span>
                </button>
              )}
              {galleryImages.map((img, i) => (
                <button
                  key={i}
                  onClick={() => { setShowVideo(false); setActiveImg(i); }}
                  style={{ ...thumb, borderColor: !showVideo && activeImg === i ? "var(--ignite)" : "var(--border)" }}
                >
                  <EquipImage src={img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </button>
              ))}
            </div>
          </div>

          {/* Inspection & guarantee */}
          <div style={{ marginTop: 20 }}>
            <InspectionPanel auction={auction} onOpenReport={() => onInspect(auction)} />
          </div>

          {/* Description */}
          <Section title="Description" icon="file-text">
            <p style={{ fontSize: 14.5, lineHeight: 1.7, color: "var(--text-2)" }}>{auction.description}</p>
          </Section>

          {/* Specs */}
          <Section title="Specifications" icon="list">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, borderRadius: 8, overflow: "hidden", border: "1px solid var(--border)" }} className="eb-spec-grid">
              {auction.specs.map(([k, v], i) => (
                <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "12px 16px", background: i % 2 === 0 ? "var(--surface)" : "var(--card-bg)", borderBottom: "1px solid var(--border)" }}>
                  <span style={{ fontSize: 12.5, color: "var(--text-3)" }}>{k}</span>
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text)", fontFamily: "var(--ff-mono)" }}>{v}</span>
                </div>
              ))}
            </div>
          </Section>

          {/* Seller */}
          <Section title="Seller" icon="store">
            <div onClick={() => onNav({ name: "profile", id: auction.seller.name })} style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 18px", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 10, cursor: "pointer" }}>
              <span style={{ width: 48, height: 48, borderRadius: 8, background: "linear-gradient(135deg,#334155,#1e293b)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--ff-display)", fontSize: 20, fontWeight: 800, color: "#fff" }}>
                {auction.seller.name[0]}
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                  <span style={{ fontSize: 15, fontWeight: 700, color: "var(--text)" }}>{auction.seller.name}</span>
                  {auction.seller.verified && (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 3, fontSize: 10.5, fontWeight: 700, color: "#22C55E" }}>
                      <i data-lucide="badge-check" style={{ width: 13, height: 13 }}></i> Verified
                    </span>
                  )}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 4, fontSize: 12, color: "var(--text-3)" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <i data-lucide="star" style={{ width: 12, height: 12, color: "#F59E0B", fill: "#F59E0B" }}></i>
                    {auction.seller.rating} rating
                  </span>
                  <span>{auction.seller.sales} sales</span>
                </div>
              </div>
              <button style={{ ...ghostBtn, fontSize: 12.5 }}>
                <i data-lucide="chevron-right" style={{ width: 14, height: 14 }}></i> View profile
              </button>
            </div>
          </Section>
        </div>

        {/* Right: bid panel (sticky) */}
        <div>
          <div style={{ position: "sticky", top: "calc(88px + var(--eb-statusbar-h, 0px))", display: "flex", flexDirection: "column", gap: 14 }}>
            {isMarket ? <MarketRail auction={auction} user={user} onNav={onNav} /> : (<React.Fragment>
            {/* Timer card */}
            <div style={panelCard}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--text-3)" }}>
                  {isLive ? "Auction ends in" : isUpcoming ? "Auction opens in" : "Auction"}
                </span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, color: "var(--text-3)" }}>
                  <i data-lucide="eye" style={{ width: 13, height: 13 }}></i> {auction.watchers} watching
                </span>
              </div>
              <div style={{ marginTop: 14 }}>
                {isEnded ? (
                  <span style={{ fontFamily: "var(--ff-display)", fontSize: 26, fontWeight: 800, color: "var(--text-3)", textTransform: "uppercase" }}>
                    {auction.status === "settled" ? "Settled" : "Ended"}
                  </span>
                ) : (
                  <Countdown endsAt={isUpcoming ? auction.startsAt : auction.endsAt} />
                )}
              </div>
              {auction.antiSnipe > 0 && isLive && (
                <div style={{ marginTop: 12, display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--cobalt)" }}>
                  <i data-lucide="shield" style={{ width: 12, height: 12 }}></i>
                  Late bids extend the auction by {auction.antiSnipe}s.
                </div>
              )}
            </div>

            {/* Price card */}
            <div style={panelCard}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                <div>
                  <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".09em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 5 }}>
                    {isUpcoming ? "Starting price" : "Current bid"}
                  </div>
                  <div style={{ fontFamily: "var(--ff-mono)", fontSize: 30, fontWeight: 700, color: "var(--ignite)", lineHeight: 1 }}>{eur(price)}</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 7 }}>{auction.bidCount} bids placed</div>
                </div>
                <div style={{ borderLeft: "1px solid var(--border)", paddingLeft: 14 }}>
                  <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".09em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 5 }}>Reserve</div>
                  <div style={{ marginTop: 4 }}><ReservePill met={auction.reserveMet} /></div>
                  <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 10 }}>Min. increment {eur(auction.minIncrement)}</div>
                </div>
              </div>
            </div>

            {/* Action card */}
            {isLive && !isOwnerView && (
              user ? (
                bidEligible ? (
                <form onSubmit={submitBid} style={panelCard}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "#22C55E", marginBottom: 11, fontWeight: 600 }}>
                    <i data-lucide="shield-check" style={{ width: 14, height: 14 }}></i>
                    {hasPreauth ? `${eur(wallet.preauths[auction.id].amount)} hold authorized · released if you don't win` : `${wallet.card.brand} •••• ${wallet.card.last4} on file`}
                  </div>
                  {bidErr && (
                    <div style={{ background: "rgba(239,68,68,0.1)", color: "#F87171", fontSize: 12, padding: "8px 11px", borderRadius: 6, marginBottom: 11 }}>{bidErr}</div>
                  )}
                  <label style={fieldLabel}>Your bid</label>
                  <div style={{ display: "flex", gap: 8, marginBottom: 11 }}>
                    <span style={eurPrefix}>€</span>
                    <input
                      type="number"
                      value={bidAmount}
                      onChange={(e) => setBidAmount(e.target.value)}
                      placeholder={minNext.toLocaleString()}
                      min={minNext}
                      style={{ ...inputStyle, flex: 1, fontFamily: "var(--ff-mono)" }}
                    />
                  </div>
                  <div style={{ display: "flex", gap: 6, marginBottom: 13 }}>
                    {[0, 1, 2].map((mult) => {
                      const v = minNext + auction.minIncrement * mult;
                      return (
                        <button key={mult} type="button" onClick={() => setBidAmount(String(v))} style={quickBid}>
                          {eur(v)}
                        </button>
                      );
                    })}
                  </div>
                  <label style={fieldLabel}>
                    Max bid <span style={{ color: "var(--text-3)", fontWeight: 500, textTransform: "none", letterSpacing: 0 }}>(optional — we auto-bid for you)</span>
                  </label>
                  <div style={{ display: "flex", gap: 8, marginBottom: 15 }}>
                    <span style={eurPrefix}>€</span>
                    <input
                      type="number"
                      value={maxBid}
                      onChange={(e) => setMaxBid(e.target.value)}
                      placeholder={(minNext + 50 * auction.minIncrement).toLocaleString()}
                      style={{ ...inputStyle, flex: 1, fontFamily: "var(--ff-mono)" }}
                    />
                  </div>
                  <button type="submit" style={{ ...primaryBtn, width: "100%", justifyContent: "center", fontSize: 14, padding: "13px" }}>
                    <i data-lucide="gavel" style={{ width: 16, height: 16 }}></i> Place bid
                  </button>
                  <div style={{ fontSize: 11, color: "var(--text-3)", textAlign: "center", marginTop: 10, display: "flex", alignItems: "center", justifyContent: "center", gap: 5 }}>
                    <i data-lucide="lock" style={{ width: 11, height: 11 }}></i> Bids are binding. Buyer protection included.
                  </div>
                </form>
                ) : (
                  <BidGate auction={auction} wallet={wallet} onAddCard={onAddCard} onPreauth={onPreauth} />
                )
              ) : (
                <div style={{ ...panelCard, textAlign: "center" }}>
                  <span style={{ width: 44, height: 44, borderRadius: 10, background: "rgba(249,115,22,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
                    <i data-lucide="log-in" style={{ width: 20, height: 20, color: "var(--ignite)" }}></i>
                  </span>
                  <div style={{ fontSize: 15.5, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", marginBottom: 5 }}>Sign in to place a bid</div>
                  <div style={{ fontSize: 12.5, color: "var(--text-3)", marginBottom: 15, lineHeight: 1.5 }}>
                    Join thousands of buyers bidding on equipment across the Balkans.
                  </div>
                  <button onClick={() => onNav({ name: "signin", redirect: { name: "detail", id: auction.id } })} style={{ ...primaryBtn, width: "100%", justifyContent: "center" }}>
                    Sign in to bid
                  </button>
                  <button onClick={() => onNav({ name: "signup", redirect: { name: "detail", id: auction.id } })} style={{ ...ghostBtn, width: "100%", justifyContent: "center", marginTop: 9 }}>
                    Create an account
                  </button>
                </div>
              )
            )}

            {isOwnerView && (
              <div style={{ ...panelCard, textAlign: "center", color: "var(--text-3)", fontSize: 13 }}>
                This is your auction. You can manage it from <button onClick={() => onNav({ name: "account", tab: "selling" })} style={{ color: "var(--cobalt)", fontWeight: 700 }}>My Auctions</button>.
              </div>
            )}

            {isUpcoming && (
              <div style={{ ...panelCard, textAlign: "center" }}>
                <div style={{ fontSize: 13.5, color: "var(--text-2)", marginBottom: 12 }}>This auction hasn't opened yet.</div>
                <button onClick={() => onWatch(auction.id)} style={{ ...primaryBtn, width: "100%", justifyContent: "center", background: watched ? "var(--surface-2)" : "var(--ignite)", color: watched ? "var(--text)" : "#fff" }}>
                  <i data-lucide="bell" style={{ width: 15, height: 15 }}></i> {watched ? "We'll notify you" : "Notify me when it opens"}
                </button>
              </div>
            )}

            {isEnded && (
              <div style={{ ...panelCard, textAlign: "center" }}>
                <div style={{ fontSize: 12.5, color: "var(--text-3)", marginBottom: 6 }}>Winning bid</div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 26, fontWeight: 700, color: "var(--text)" }}>{eur(price)}</div>
                <button onClick={() => onNav({ name: "auctions" })} style={{ ...ghostBtn, width: "100%", justifyContent: "center", marginTop: 14 }}>
                  Browse live auctions
                </button>
              </div>
            )}

            {/* Bid history */}
            <div style={panelCard}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
                <span style={{ fontSize: 13, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", textTransform: "uppercase", letterSpacing: ".03em" }}>Bid history</span>
                <span style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "var(--ff-mono)" }}>{bids.length} bids</span>
              </div>
              {bids.length === 0 ? (
                <div style={{ fontSize: 13, color: "var(--text-3)", textAlign: "center", padding: "18px 0" }}>No bids yet. Be the first!</div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 2, maxHeight: 300, overflowY: "auto" }}>
                  {[...bids].reverse().map((b, i) => {
                    const top = i === 0;
                    return (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 10px", borderRadius: 7, background: top ? "rgba(249,115,22,0.07)" : "transparent" }}>
                        <span style={{ width: 30, height: 30, borderRadius: 7, background: b.auto ? "rgba(37,99,235,0.15)" : "var(--surface-2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                          <i data-lucide={b.auto ? "zap" : "user"} style={{ width: 14, height: 14, color: b.auto ? "var(--cobalt)" : "var(--text-3)" }}></i>
                        </span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-2)" }}>
                            Bidder {b.bidder}{" "}
                            {b.auto && <span style={{ fontSize: 9.5, color: "var(--cobalt)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".05em" }}>auto</span>}
                          </div>
                          <div style={{ fontSize: 11, color: "var(--text-3)" }}>{relTime(b.t)}</div>
                        </div>
                        <span style={{ fontFamily: "var(--ff-mono)", fontSize: 14, fontWeight: 700, color: top ? "var(--ignite)" : "var(--text)" }}>{eur(b.amount)}</span>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
            </React.Fragment>)}
          </div>
        </div>
      </div>

      {/* Related */}
      <RelatedRow store={store} auction={auction} onNav={onNav} onWatch={onWatch} watchlist={watchlist} />
    </div>
  );
}

function RelatedRow({ store, auction, onNav, onWatch, watchlist }) {
  const related = store.auctions.filter((a) => a.id !== auction.id && a.status === "live").slice(0, 4);
  if (related.length === 0) return null;
  return (
    <div style={{ marginTop: 48 }}>
      <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 24, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", marginBottom: 18 }}>
        More live auctions
      </h2>
      <div className="eb-card-grid">
        {related.map((a) => (
          <AuctionCard key={a.id} auction={a} onOpen={(id) => onNav({ name: "detail", id })} watched={watchlist.includes(a.id)} onWatch={onWatch} />
        ))}
      </div>
    </div>
  );
}

// ── Small helpers ───────────────────────────────────
function Section({ title, icon, children }) {
  return (
    <div style={{ marginTop: 26 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 13 }}>
        <i data-lucide={icon} style={{ width: 16, height: 16, color: "var(--ignite)" }}></i>
        <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 19, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", letterSpacing: ".02em", margin: 0 }}>{title}</h2>
      </div>
      {children}
    </div>
  );
}

const panelCard = { background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 12, padding: 18 };
const thumb = { width: 60, height: 46, borderRadius: 6, overflow: "hidden", border: "2px solid var(--border)", padding: 0, flexShrink: 0 };
const primaryBtn = { display: "inline-flex", alignItems: "center", gap: 8, background: "var(--ignite)", color: "#fff", border: "none", borderRadius: 6, padding: "10px 20px", fontSize: 13.5, fontWeight: 700, cursor: "pointer" };
const ghostBtn = { display: "inline-flex", alignItems: "center", gap: 7, background: "transparent", color: "var(--text-2)", border: "1px solid var(--border-s)", borderRadius: 6, padding: "10px 16px", fontSize: 13, fontWeight: 600, cursor: "pointer" };
const fieldLabel = { display: "block", fontSize: 10.5, fontWeight: 700, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 7 };
const inputStyle = { background: "var(--bg)", color: "var(--text)", border: "1px solid var(--border-s)", borderRadius: 6, padding: "11px 13px", fontSize: 14, outline: "none", width: "100%" };
const eurPrefix = { display: "flex", alignItems: "center", justifyContent: "center", width: 40, background: "var(--bg)", border: "1px solid var(--border-s)", borderRadius: 6, fontSize: 15, fontWeight: 700, color: "var(--text-3)" };
const quickBid = { flex: 1, padding: "7px 4px", fontSize: 11.5, fontWeight: 700, fontFamily: "var(--ff-mono)", color: "var(--text-2)", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 5, cursor: "pointer" };

Object.assign(window, { BrowseScreen, DetailScreen, Section, primaryBtn, ghostBtn, fieldLabel, inputStyle, eurPrefix, panelCard });
