/* ─────────────────────────────────────────────────────
   Equipment Balkans — Auction prototype shared components
───────────────────────────────────────────────────── */
const { useState, useEffect, useRef, useCallback } = React;

// ── Format helpers ──────────────────────────────────
const eur = (n) =>
  n == null ? "—" : "€" + Number(n).toLocaleString("en-US");

// ── React-safe lucide renderer ──────────────────────
// Fills each <i data-lucide> with an inline <svg> WITHOUT replacing the
// node, so React keeps owning the <i> and never hits removeChild crashes.
function lucidePascal(name) {
  return String(name).split("-").map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
}
function renderIcons() {
  const lib = window.lucide;
  if (!lib || !lib.icons) return;
  document.querySelectorAll("[data-lucide]").forEach((el) => {
    const name = el.getAttribute("data-lucide");
    const w = el.style.width || "16px";
    const h = el.style.height || "16px";
    const fill = el.style.fill || "none";
    const sig = name + "|" + w + "|" + h + "|" + fill;
    if (el.getAttribute("data-licon") === sig) return;
    const node = lib.icons[lucidePascal(name)];
    if (!node) return;
    const inner = node.map(([tag, attrs]) => {
      const a = Object.entries(attrs || {}).map(([k, v]) => `${k}="${v}"`).join(" ");
      return `<${tag} ${a}/>`;
    }).join("");
    el.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="${parseFloat(w) || 16}" height="${parseFloat(h) || 16}" viewBox="0 0 24 24" fill="${fill}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block">${inner}</svg>`;
    el.style.display = el.style.display || "inline-flex";
    el.setAttribute("data-licon", sig);
  });
}

function timeLeft(endsAt) {
  const diff = endsAt - Date.now();
  if (diff <= 0) return { ended: true, d: 0, h: 0, m: 0, s: 0, urgent: false };
  const d = Math.floor(diff / 86400000);
  const h = Math.floor((diff % 86400000) / 3600000);
  const m = Math.floor((diff % 3600000) / 60000);
  const s = Math.floor((diff % 60000) / 1000);
  return { ended: false, d, h, m, s, urgent: diff < 3600000 };
}

function relTime(t) {
  const diff = Date.now() - t;
  const m = Math.floor(diff / 60000);
  if (m < 1) return "just now";
  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";
}

// ── Equipment image with branded fallback ───────────
function EquipImage({ src, alt, style, className }) {
  const [failed, setFailed] = useState(false);
  if (failed || !src) {
    return (
      <div
        className={className}
        style={{
          ...style,
          background:
            "repeating-linear-gradient(135deg, var(--surface), var(--surface) 14px, var(--surface-2) 14px, var(--surface-2) 28px)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: "var(--text-3)",
        }}
      >
        <i data-lucide="package" style={{ width: 34, height: 34, opacity: 0.4 }}></i>
      </div>
    );
  }
  return (
    <img
      src={src}
      alt={alt || ""}
      className={className}
      style={style}
      loading="lazy"
      onError={() => setFailed(true)}
    />
  );
}

// ── Status badge ────────────────────────────────────
const STATUS_CFG = {
  live: { label: "Live", color: "#F97316", dot: "#F97316", bg: "rgba(249,115,22,0.12)" },
  upcoming: { label: "Upcoming", color: "#3B82F6", dot: "#3B82F6", bg: "rgba(59,130,246,0.12)" },
  ended: { label: "Ended", color: "#94A3B8", dot: "#64748B", bg: "rgba(148,163,184,0.14)" },
  settled: { label: "Settled", color: "#22C55E", dot: "#22C55E", bg: "rgba(34,197,94,0.12)" },
  canceled: { label: "Canceled", color: "#EF4444", dot: "#EF4444", bg: "rgba(239,68,68,0.12)" },
  listed: { label: "For Sale", color: "#16A34A", dot: "#16A34A", bg: "rgba(22,163,74,0.12)" },
};

// Theme-aware logo source
function logoSrc() {
  const t = window.__ebTheme || document.documentElement.getAttribute("data-theme");
  return t === "light" ? "assets/EB_logo_horizontal_light.png" : "assets/EB_logo_horizontal_dark.png";
}
function markSrc() {
  const t = window.__ebTheme || document.documentElement.getAttribute("data-theme");
  return t === "light" ? "assets/EB_mark_light_visible.png" : "assets/EB_mark_dark_visible.png";
}
function wordmarkSrc() {
  const t = window.__ebTheme || document.documentElement.getAttribute("data-theme");
  return t === "light" ? "assets/EB_wordmark_light.svg" : "assets/EB_wordmark_dark.svg";
}

function StatusBadge({ status, big }) {
  const c = STATUS_CFG[status] || STATUS_CFG.ended;
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        background: c.bg,
        color: c.color,
        fontSize: big ? 12 : 10.5,
        fontWeight: 800,
        letterSpacing: ".09em",
        textTransform: "uppercase",
        padding: big ? "6px 12px" : "4px 9px",
        borderRadius: 4,
        fontFamily: "var(--ff-sans)",
      }}
    >
      <span
        style={{
          width: 6,
          height: 6,
          borderRadius: "50%",
          background: c.dot,
          boxShadow: status === "live" ? `0 0 0 0 ${c.dot}` : "none",
          animation: status === "live" ? "pulse 1.6s infinite" : "none",
        }}
      ></span>
      {c.label}
    </span>
  );
}

// ── Reserve pill ────────────────────────────────────
function ReservePill({ met }) {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 5,
        fontSize: 10.5,
        fontWeight: 700,
        letterSpacing: ".05em",
        textTransform: "uppercase",
        color: met ? "#22C55E" : "#64748B",
        fontFamily: "var(--ff-sans)",
      }}
    >
      <i
        data-lucide={met ? "shield-check" : "shield-off"}
        style={{ width: 13, height: 13 }}
      ></i>
      {met ? "Reserve met" : "Reserve not met"}
    </span>
  );
}

// ── Countdown timer ─────────────────────────────────
function Countdown({ endsAt, compact }) {
  const [, force] = useState(0);
  useEffect(() => {
    const id = setInterval(() => force((x) => x + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const t = timeLeft(endsAt);

  if (t.ended) {
    return (
      <span style={{ color: "var(--text-3)", fontWeight: 700, fontFamily: "var(--ff-mono)" }}>
        Ended
      </span>
    );
  }

  const Unit = ({ v, l }) => (
    <span style={{ display: "inline-flex", flexDirection: "column", alignItems: "center" }}>
      <span
        style={{
          fontFamily: "var(--ff-mono)",
          fontSize: compact ? 15 : 20,
          fontWeight: 700,
          color: t.urgent ? "#F97316" : "var(--text)",
          lineHeight: 1,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {String(v).padStart(2, "0")}
      </span>
      <span
        style={{
          fontSize: 8.5,
          color: "var(--text-3)",
          textTransform: "uppercase",
          letterSpacing: ".1em",
          marginTop: 3,
        }}
      >
        {l}
      </span>
    </span>
  );
  const Sep = () => (
    <span style={{ color: "var(--text-3)", fontWeight: 700, alignSelf: "flex-start", marginTop: 1 }}>:</span>
  );

  return (
    <span style={{ display: "inline-flex", alignItems: "flex-start", gap: compact ? 7 : 10 }}>
      {t.d > 0 && (
        <>
          <Unit v={t.d} l="days" />
          <Sep />
        </>
      )}
      <Unit v={t.h} l="hrs" />
      <Sep />
      <Unit v={t.m} l="min" />
      <Sep />
      <Unit v={t.s} l="sec" />
    </span>
  );
}

// ── Header (dovetails with EB website) ──────────────
function Header({ route, user, onNav, onLogout, theme, onToggleTheme }) {
  const [acctOpen, setAcctOpen] = useState(false);
  const links = [
    { label: "Marketplace", to: "marketplace" },
    { label: "Auctions", to: "auctions" },
    { label: "Categories", to: "categories" },
    { label: "Services", to: "services" },
    { label: "About", to: "about" },
  ];
  const isAuctions = route.name === "auctions" || route.name === "detail";

  return (
    <header
      style={{
        position: "sticky",
        top: 0,
        zIndex: 60,
        background: "var(--header-bg)",
        backdropFilter: "blur(12px)",
        borderBottom: "1px solid var(--border)",
      }}
    >
      <div
        style={{
          maxWidth: 1440,
          margin: "0 auto",
          padding: "0 24px",
          height: 64,
          display: "flex",
          alignItems: "center",
          gap: 22,
        }}
      >
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault();
            onNav({ name: "auctions" });
          }}
          style={{ display: "flex", alignItems: "center", flexShrink: 0 }}
        >
          <img src={markSrc()} alt="Equipment Balkans" style={{ height: 34, width: "auto" }} />
        </a>

        <nav style={{ display: "flex", alignItems: "center", gap: 2, flex: 1 }} className="eb-nav-links">
          {links.map((l) => {
            const active = route.name === l.to || (l.to === "auctions" && route.name === "detail");
            return (
              <a
                key={l.label}
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  onNav({ name: l.to });
                }}
                style={{
                  fontSize: 11.5,
                  fontWeight: 600,
                  letterSpacing: ".06em",
                  textTransform: "uppercase",
                  color: active ? "var(--ignite)" : "var(--text-2)",
                  padding: "6px 10px",
                  borderRadius: 4,
                }}
              >
                {l.label}
              </a>
            );
          })}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <button className="eb-themebtn" title="Toggle light / dark" onClick={onToggleTheme} style={iconBtn}>
            <i data-lucide={theme === "light" ? "moon" : "sun"} style={{ width: 17, height: 17 }}></i>
          </button>
          {user ? (
            <>
              <button className="eb-iconbtn" title="Messages" onClick={() => onNav({ name: "messages" })} style={iconBtn}>
                <i data-lucide="bell" style={{ width: 17, height: 17 }}></i>
                <span style={notifDot}></span>
              </button>
              <div style={{ position: "relative" }} className="eb-acct">
                <button
                  onClick={() => setAcctOpen((o) => !o)}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    padding: "5px 8px 5px 5px",
                    borderRadius: 6,
                    color: "var(--text)",
                  }}
                >
                  <span style={avatar}>{(user.name || user.email)[0].toUpperCase()}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, maxWidth: 110, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {user.name || user.email.split("@")[0]}
                  </span>
                  <i data-lucide="chevron-down" style={{ width: 14, height: 14, opacity: 0.6 }}></i>
                </button>
                {acctOpen && (
                  <div style={dropdown}>
                    <button style={dropItem} onClick={() => { setAcctOpen(false); onNav({ name: "account", tab: "profile" }); }}>
                      <i data-lucide="user" style={dropIco}></i> Profile &amp; settings
                    </button>
                    <button style={dropItem} onClick={() => { setAcctOpen(false); onNav({ name: "account", tab: "bids" }); }}>
                      <i data-lucide="gavel" style={dropIco}></i> My Bids
                    </button>
                    <button style={dropItem} onClick={() => { setAcctOpen(false); onNav({ name: "messages" }); }}>
                      <i data-lucide="message-circle" style={dropIco}></i> Messages
                    </button>
                    <button style={dropItem} onClick={() => { setAcctOpen(false); onNav({ name: "account", tab: "selling" }); }}>
                      <i data-lucide="tag" style={dropIco}></i> My Auctions
                    </button>
                    <button style={dropItem} onClick={() => { setAcctOpen(false); onNav({ name: "account", tab: "watchlist" }); }}>
                      <i data-lucide="heart" style={dropIco}></i> Watchlist
                    </button>
                    <div style={{ height: 1, background: "var(--border)", margin: "5px 0" }}></div>
                    <button style={{ ...dropItem, color: "#F87171" }} onClick={() => { setAcctOpen(false); onLogout(); }}>
                      <i data-lucide="log-out" style={dropIco}></i> Sign out
                    </button>
                  </div>
                )}
              </div>
            </>
          ) : (
            <>
              <button
                onClick={() => onNav({ name: "signin" })}
                style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-2)", padding: "8px 12px", borderRadius: 4 }}
                className="eb-ghostbtn"
              >
                Sign in
              </button>
              <button
                onClick={() => onNav({ name: "signup" })}
                style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-2)", padding: "8px 12px", borderRadius: 4 }}
                className="eb-ghostbtn eb-hide-sm"
              >
                Sign up
              </button>
            </>
          )}
          {!user && (
            <button
              onClick={() => onNav({ name: "signin", redirect: { name: "sell" } })}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                background: "var(--ignite)",
                color: "#fff",
                fontSize: 12.5,
                fontWeight: 700,
                padding: "9px 15px",
                borderRadius: 4,
              }}
              className="eb-cta"
            >
              <i data-lucide="plus" style={{ width: 15, height: 15 }}></i>
              <span className="eb-hide-sm">Sell Equipment</span>
            </button>
          )}
        </div>
      </div>
    </header>
  );
}

const iconBtn = {
  position: "relative",
  width: 36,
  height: 36,
  borderRadius: 6,
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  color: "var(--text-2)",
};
const notifDot = {
  position: "absolute",
  top: 8,
  right: 9,
  width: 7,
  height: 7,
  borderRadius: "50%",
  background: "var(--ignite)",
  border: "2px solid var(--bg)",
};
const avatar = {
  width: 28,
  height: 28,
  borderRadius: 6,
  background: "linear-gradient(135deg, #2563EB, #1D4ED8)",
  color: "#fff",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  fontSize: 12,
  fontWeight: 800,
  fontFamily: "var(--ff-display)",
};
const dropdown = {
  position: "absolute",
  right: 0,
  top: "calc(100% + 8px)",
  width: 190,
  background: "var(--surface)",
  border: "1px solid var(--border-s)",
  borderRadius: 8,
  padding: 6,
  boxShadow: "0 12px 32px rgba(0,0,0,0.5)",
  zIndex: 80,
};
const dropItem = {
  width: "100%",
  display: "flex",
  alignItems: "center",
  gap: 10,
  padding: "9px 10px",
  borderRadius: 5,
  fontSize: 13,
  fontWeight: 600,
  color: "var(--text-2)",
  textAlign: "left",
};
const dropIco = { width: 15, height: 15 };

// ── Footer ──────────────────────────────────────────
function Footer({ onNav }) {
  const go = (r) => { if (onNav) onNav(r); };
  const cols = [
    { h: "Marketplace", items: [["Browse Equipment", { name: "marketplace" }], ["Auctions", { name: "auctions" }], ["Categories", { name: "categories" }], ["Sell Equipment", { name: "sell" }]] },
    { h: "Services", items: [["Inspection", { name: "service", id: "inspection" }], ["90-Day Guarantee", { name: "service", id: "guarantee" }], ["Extended Warranty", { name: "service", id: "warranty" }], ["All Services", { name: "services" }]] },
    { h: "Company", items: [["About Us", { name: "about" }], ["Services", { name: "services" }], ["Transport & Logistics", { name: "service", id: "transport" }], ["Title & Export", { name: "service", id: "title-export" }]] },
    { h: "Support", items: [["Buyer Protection", { name: "service", id: "guarantee" }], ["Financing", { name: "service", id: "financing" }], ["Valuation", { name: "service", id: "valuation" }], ["Maintenance & Parts", { name: "service", id: "maintenance" }]] },
  ];
  return (
    <footer style={{ borderTop: "1px solid var(--border)", background: "var(--bg)", marginTop: 40 }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "44px 24px 28px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr repeat(4, 1fr)", gap: 32 }} className="eb-foot-grid">
          <div>
            <a href="#" onClick={(e) => { e.preventDefault(); go({ name: "auctions" }); }} style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 18 }}>
              <img src={markSrc()} alt="Equipment Balkans" style={{ height: 46, width: "auto" }} />
              <img src={wordmarkSrc()} alt="Equipment Balkans" style={{ height: 42, width: "auto" }} />
            </a>
            <p style={{ fontSize: 12.5, color: "var(--text-3)", lineHeight: 1.7, maxWidth: 240 }}>
              The industrial marketplace and auction house for heavy equipment across the Balkans and beyond.
            </p>
          </div>
          {cols.map((c) => (
            <div key={c.h}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--text-2)", marginBottom: 14 }}>
                {c.h}
              </div>
              <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 9 }}>
                {c.items.map(([label, r]) => (
                  <li key={label}>
                    <a href="#" onClick={(e) => { e.preventDefault(); go(r); }} style={{ fontSize: 12.5, color: "var(--text-3)" }} className="eb-footlink">
                      {label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 36, paddingTop: 20, borderTop: "1px solid var(--border)", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
          <span style={{ fontSize: 12, color: "var(--text-3)" }}>© 2026 Equipment Balkans. All rights reserved.</span>
          <span style={{ fontSize: 12, color: "var(--text-3)" }}>Belgrade · Zagreb · Ljubljana · Sarajevo</span>
        </div>
      </div>
    </footer>
  );
}

// ── Auction card (rich, image-led) ──────────────────
function AuctionCard({ auction, onOpen, watched, onWatch, note }) {
  const c = STATUS_CFG[auction.status] || STATUS_CFG.ended;
  const isLive = auction.status === "live";
  const isUpcoming = auction.status === "upcoming";
  const price = auction.currentBid ?? auction.startingPrice;
  const priceLabel = isLive ? "Current bid" : isUpcoming ? "Starting price" : "Final price";
  const [hover, setHover] = useState(false);

  return (
    <div
      onClick={() => onOpen(auction.id)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: "var(--card-bg)",
        border: `1px solid ${hover ? "rgba(249,115,22,0.5)" : "var(--border)"}`,
        borderRadius: 12,
        overflow: "hidden",
        cursor: "pointer",
        transition: "border-color .18s ease, transform .18s ease, box-shadow .18s ease",
        transform: hover ? "translateY(-3px)" : "none",
        boxShadow: hover ? "0 14px 34px rgba(0,0,0,0.45)" : "var(--shadow-card)",
        display: "flex",
        flexDirection: "column",
      }}
    >
      {/* Image */}
      <div style={{ position: "relative", aspectRatio: "16/10", overflow: "hidden" }}>
        <EquipImage
          src={auction.images[0]}
          alt={auction.title}
          style={{
            width: "100%",
            height: "100%",
            objectFit: "cover",
            transition: "transform .4s ease",
            transform: hover ? "scale(1.05)" : "scale(1)",
          }}
        />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(15,23,42,0.55), transparent 45%)" }}></div>
        <div style={{ position: "absolute", top: 11, left: 11, display: "flex", gap: 7 }}>
          <StatusBadge status={auction.status} />
        </div>
        <div style={{ position: "absolute", top: 9, right: 9, display: "flex", gap: 6 }}>
          {auction.hasVideo && (
            <span style={badgeChip}>
              <i data-lucide="video" style={{ width: 12, height: 12 }}></i>
            </span>
          )}
          <button
            onClick={(e) => { e.stopPropagation(); onWatch(auction.id); }}
            style={{ ...badgeChip, color: watched ? "#F97316" : "#fff" }}
            title={watched ? "Watching" : "Watch"}
          >
            <i data-lucide="heart" style={{ width: 12, height: 12, fill: watched ? "#F97316" : "none" }}></i>
          </button>
        </div>
        {isLive && (
          <div style={{ position: "absolute", bottom: 10, left: 11, display: "flex", alignItems: "center", gap: 5, background: "rgba(15,23,42,0.7)", backdropFilter: "blur(4px)", padding: "4px 9px", borderRadius: 5 }}>
            <i data-lucide="clock" style={{ width: 12, height: 12, color: "#F97316" }}></i>
            <CompactClock endsAt={auction.endsAt} />
          </div>
        )}
      </div>

      {/* Body */}
      <div style={{ padding: "14px 16px 16px", display: "flex", flexDirection: "column", gap: 11, flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11, color: "var(--text-3)" }}>
          <span style={{ fontWeight: 700, textTransform: "uppercase", letterSpacing: ".05em", color: "var(--text-2)" }}>{auction.category}</span>
          <span>·</span>
          <span>{auction.year}</span>
          <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 4 }}>
            <i data-lucide="map-pin" style={{ width: 11, height: 11 }}></i>
            {auction.location.split(",")[1]?.trim() || auction.location}
          </span>
        </div>

        <h3
          style={{
            fontFamily: "var(--ff-display)",
            fontSize: 19,
            fontWeight: 800,
            color: "var(--text)",
            lineHeight: 1.15,
            margin: 0,
          }}
        >
          {auction.title}
        </h3>

        <div style={{ marginTop: "auto", display: "flex", alignItems: "flex-end", justifyContent: "space-between", paddingTop: 4 }}>
          <div>
            <div style={{ fontSize: 9.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 3 }}>{priceLabel}</div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 22, fontWeight: 700, color: isLive ? "var(--ignite)" : "var(--text)", lineHeight: 1 }}>
              {eur(price)}
            </div>
          </div>
          <div style={{ textAlign: "right" }}>
            <ReservePill met={auction.reserveMet} />
            <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 5, fontFamily: "var(--ff-mono)" }}>
              {auction.bidCount} bid{auction.bidCount !== 1 ? "s" : ""}
            </div>
          </div>
        </div>
        {note && (
          <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 10.5, fontWeight: 700, color: "var(--cobalt)", borderTop: "1px solid var(--border)", paddingTop: 9 }}>
            <i data-lucide="link" style={{ width: 12, height: 12 }}></i>{note}
          </div>
        )}
      </div>
    </div>
  );
}

const badgeChip = {
  width: 26,
  height: 26,
  borderRadius: 6,
  background: "rgba(15,23,42,0.65)",
  backdropFilter: "blur(4px)",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  color: "#fff",
};

function CompactClock({ endsAt }) {
  const [, force] = useState(0);
  useEffect(() => {
    const id = setInterval(() => force((x) => x + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const t = timeLeft(endsAt);
  if (t.ended) return <span style={{ fontSize: 12, fontWeight: 700, color: "#fff", fontFamily: "var(--ff-mono)" }}>Ended</span>;
  const txt = t.d > 0 ? `${t.d}d ${t.h}h` : `${String(t.h).padStart(2, "0")}:${String(t.m).padStart(2, "0")}:${String(t.s).padStart(2, "0")}`;
  return <span style={{ fontSize: 12, fontWeight: 700, color: t.urgent ? "#F97316" : "#fff", fontFamily: "var(--ff-mono)", fontVariantNumeric: "tabular-nums" }}>{txt}</span>;
}

// ── Toast ───────────────────────────────────────────
function Toast({ toast }) {
  if (!toast) return null;
  const ok = toast.type !== "error";
  return (
    <div
      style={{
        position: "fixed",
        bottom: 24,
        left: "50%",
        transform: "translateX(-50%)",
        zIndex: 200,
        display: "flex",
        alignItems: "center",
        gap: 10,
        background: "var(--surface)",
        border: `1px solid ${ok ? "rgba(34,197,94,0.4)" : "rgba(239,68,68,0.4)"}`,
        borderRadius: 8,
        padding: "12px 18px",
        boxShadow: "0 12px 34px rgba(0,0,0,0.55)",
        animation: "toastIn .25s ease",
      }}
    >
      <i data-lucide={ok ? "check-circle-2" : "alert-circle"} style={{ width: 17, height: 17, color: ok ? "#22C55E" : "#EF4444" }}></i>
      <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text)" }}>{toast.msg}</span>
    </div>
  );
}

// ── Bid status bar (site-wide, when logged in with active bids) ──
function bidStatusFor(auction, ub) {
  const ended = auction.status === "ended" || auction.status === "settled";
  if (ended && ub.won && !ub.paid) {
    return { kind: "won", prio: 3, color: "var(--ignite)", bg: "rgba(249,115,22,0.12)", icon: "trophy", label: "You won — arrange payment" };
  }
  if (ended && ub.won && ub.paid) {
    return { kind: "paid", prio: 0, color: "#22C55E", bg: "rgba(34,197,94,0.10)", icon: "shield-check", label: "Won — funds in escrow" };
  }
  if (auction.status === "live") {
    if (ub.winning) return { kind: "winning", prio: 1, color: "#16A34A", bg: "rgba(34,197,94,0.12)", icon: "trending-up", label: "You're the highest bidder" };
    return { kind: "outbid", prio: 2, color: "#EF4444", bg: "rgba(239,68,68,0.12)", icon: "alert-triangle", label: "You've been outbid" };
  }
  return null;
}

function BidStatusBar({ store, onNav }) {
  const [, tick] = useState(0);
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => tick((x) => x + 1), 1000);
    return () => clearInterval(id);
  }, []);

  // 1) Bid-status alerts
  const bidAlerts = store.auctions
    .map((a) => {
      const ub = store.userBids[a.id];
      if (!ub) return null;
      const s = bidStatusFor(a, ub);
      if (!s) return null;
      const isLive = a.status === "live";
      let timeText = null;
      let urgent = false;
      if (isLive) {
        const t = timeLeft(a.endsAt);
        if (!t.ended) { urgent = t.urgent; timeText = t.d > 0 ? `${t.d}d ${String(t.h).padStart(2, "0")}h` : `${String(t.h).padStart(2, "0")}:${String(t.m).padStart(2, "0")}:${String(t.s).padStart(2, "0")}`; }
      } else if (s.kind === "won" && ub.won) {
        const diff = ub.won.at + 24 * 3600 * 1000 - Date.now();
        const h = Math.max(0, Math.floor(diff / 3600000)), m = Math.max(0, Math.floor((diff % 3600000) / 60000)), sec = Math.max(0, Math.floor((diff % 60000) / 1000));
        urgent = true; timeText = `pay within ${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`;
      }
      return {
        prio: s.prio, color: s.color, bg: s.bg, icon: s.icon, label: s.label, sub: a.title, timeText, urgent, pulse: s.kind === "outbid" || s.kind === "won",
        cta: s.kind === "won" ? "Pay now" : s.kind === "outbid" ? "Bid again" : "View lot",
        onClick: () => (s.kind === "won" ? onNav({ name: "checkout", id: a.id, mode: "won" }) : onNav({ name: "detail", id: a.id })),
      };
    })
    .filter(Boolean);

  // 2) Notification alerts (messages / actions that need attention)
  const notifAlerts = (store.notifications || []).map((n) => {
    if (n.kind === "message") {
      return { prio: 2.5, color: "var(--cobalt)", bg: "rgba(37,99,235,0.12)", icon: "message-square", label: "New message", sub: `${n.sender} · ${n.body}`, timeText: null, urgent: false, pulse: true, cta: "Read", onClick: () => onNav(n.target || { name: "auctions" }) };
    }
    return { prio: n.prio != null ? n.prio : 6, color: "var(--ignite)", bg: "rgba(249,115,22,0.12)", icon: n.icon || "alert-circle", label: n.label || "Action needed", sub: n.body || "", timeText: null, urgent: true, pulse: true, cta: n.cta || "Review", onClick: () => onNav(n.target || { name: "account", tab: "bids" }) };
  });

  const alerts = [...bidAlerts, ...notifAlerts].sort((x, y) => y.prio - x.prio);

  useEffect(() => {
    document.documentElement.style.setProperty("--eb-statusbar-h", alerts.length ? "44px" : "0px");
  }, [alerts.length]);

  if (alerts.length === 0) return null;
  const cur = alerts[Math.min(idx, alerts.length - 1)];

  return (
    <div style={{ position: "sticky", top: 64, zIndex: 55, height: 44, background: cur.bg, backdropFilter: "blur(8px)", borderBottom: "1px solid var(--border)" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto", padding: "0 24px", height: "100%", display: "flex", alignItems: "center", gap: 12 }}>
        <span style={{ width: 7, height: 7, borderRadius: "50%", background: cur.color, flexShrink: 0, animation: cur.pulse ? "pulse 1.6s infinite" : "none" }}></span>
        <button onClick={cur.onClick} style={{ flex: 1, minWidth: 0, display: "flex", alignItems: "center", gap: 9, textAlign: "left" }}>
          <i data-lucide={cur.icon} style={{ width: 15, height: 15, color: cur.color, flexShrink: 0 }}></i>
          <span style={{ fontSize: 12.5, fontWeight: 800, color: cur.color, whiteSpace: "nowrap", flexShrink: 0 }}>{cur.label}</span>
          <span style={{ color: "var(--text-3)", flexShrink: 0 }}>·</span>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{cur.sub}</span>
          {cur.timeText && <span style={sbTime(cur.urgent)}><i data-lucide="clock" style={{ width: 12, height: 12 }}></i>{cur.timeText}</span>}
        </button>

        {alerts.length > 1 && (
          <div style={{ display: "flex", alignItems: "center", gap: 6, flexShrink: 0 }}>
            <button onClick={() => setIdx((i) => (i - 1 + alerts.length) % alerts.length)} style={sbArrow}><i data-lucide="chevron-left" style={{ width: 14, height: 14 }}></i></button>
            <span style={{ fontSize: 11, fontFamily: "var(--ff-mono)", color: "var(--text-2)", minWidth: 28, textAlign: "center" }}>{Math.min(idx, alerts.length - 1) + 1}/{alerts.length}</span>
            <button onClick={() => setIdx((i) => (i + 1) % alerts.length)} style={sbArrow}><i data-lucide="chevron-right" style={{ width: 14, height: 14 }}></i></button>
          </div>
        )}

        <button onClick={cur.onClick} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 700, color: cur.color, flexShrink: 0, whiteSpace: "nowrap" }}>
          {cur.cta}
          <i data-lucide="chevron-right" style={{ width: 14, height: 14 }}></i>
        </button>

        <span style={{ width: 1, height: 20, background: "var(--border-s)", flexShrink: 0 }}></span>

        <button onClick={() => onNav({ name: "account", tab: "bids" })} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 700, color: "var(--text-2)", flexShrink: 0, whiteSpace: "nowrap" }} title="View all bids & alerts">
          <i data-lucide="layout-list" style={{ width: 14, height: 14 }}></i>
          <span className="eb-hide-sm">View all</span>
        </button>
      </div>
    </div>
  );
}
const sbTime = (urgent) => ({ display: "inline-flex", alignItems: "center", gap: 4, marginLeft: 4, fontSize: 12, fontWeight: 700, fontFamily: "var(--ff-mono)", color: urgent ? "var(--ignite)" : "var(--text-2)", flexShrink: 0, fontVariantNumeric: "tabular-nums" });
const sbArrow = { width: 26, height: 26, borderRadius: 6, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-2)", background: "rgba(127,127,127,0.12)" };

Object.assign(window, {
  eur, timeLeft, relTime,
  EquipImage, StatusBadge, ReservePill, Countdown, CompactClock,
  Header, Footer, AuctionCard, Toast, STATUS_CFG, logoSrc, markSrc, wordmarkSrc, renderIcons,
  BidStatusBar,
});
