/* ─────────────────────────────────────────────────────
   Equipment Balkans — Sell: two doors (Auction + Marketplace)
   Shared core material, diverging pricing flows, cross-listing.
───────────────────────────────────────────────────── */
const { useState: useSell, useEffect: useSellE } = React;

const SELL_SAMPLES = [
  "https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=800&h=600&fit=crop&auto=format&q=80",
  "https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=800&h=600&fit=crop&auto=format&q=80",
  "https://images.unsplash.com/photo-1565043666747-69f6646db940?w=800&h=600&fit=crop&auto=format&q=80",
  "https://images.unsplash.com/photo-1530124566582-a618bc2615dc?w=800&h=600&fit=crop&auto=format&q=80",
  "https://images.unsplash.com/photo-1599707367072-cd6ada2bc375?w=800&h=600&fit=crop&auto=format&q=80",
];
const SELL_CATEGORIES = ["Excavator", "Wheel Loader", "Bulldozer", "Forklift", "CNC Machine", "Generator", "Crane", "Dump Truck", "Telehandler", "Other"];
const SELL_ICONS = { Excavator: "shovel", "Wheel Loader": "truck", Bulldozer: "wrench", Forklift: "package", "CNC Machine": "cog", Generator: "zap", Crane: "construction", "Dump Truck": "truck", Telehandler: "move-vertical", Other: "more-horizontal" };

// ── Small local helpers (own scope) ─────────────────
function SF_Field({ label, right, children }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
        <label style={fieldLabel}>{label}</label>
        {right}
      </div>
      {children}
    </div>
  );
}
function SF_Head({ title, sub }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 23, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", margin: "0 0 4px" }}>{title}</h2>
      <p style={{ fontSize: 13, color: "var(--text-3)" }}>{sub}</p>
    </div>
  );
}
const sfPill = (on) => ({ padding: "9px 16px", borderRadius: 7, fontSize: 13, fontWeight: 600, cursor: "pointer", border: `1px solid ${on ? "var(--ignite)" : "var(--border-s)"}`, background: on ? "rgba(249,115,22,0.08)" : "var(--surface)", color: on ? "var(--ignite)" : "var(--text-2)" });
const sfFormCol = { display: "flex", flexDirection: "column", gap: 15 };

// ════════════════════════════════════════════════════
// SELL CHOICE — two doors
// ════════════════════════════════════════════════════
function SellChoiceScreen({ onNav }) {
  const DOORS = [
    {
      mode: "auction",
      icon: "gavel",
      accent: "var(--ignite)",
      tint: "rgba(249,115,22,0.10)",
      title: "Sell by Auction",
      tag: "Competitive · time-boxed",
      blurb: "Let verified buyers bid each other up. Best for in-demand or hard-to-price machines.",
      points: ["Set a starting price & optional reserve", "Live bidding with anti-snipe protection", "Sells to the highest bidder on a deadline", "Real-time bids, watchers & proxy bidding"],
    },
    {
      mode: "marketplace",
      icon: "store",
      accent: "var(--cobalt)",
      tint: "rgba(37,99,235,0.10)",
      title: "List on Marketplace",
      tag: "Fixed price · always-on",
      blurb: "Post a classified listing at your asking price. Best when you know the value and aren't in a rush.",
      points: ["Set one asking price, accept offers", "Stays live until you mark it sold", "Buyers message you or make an offer", "No deadline, edit anytime"],
    },
  ];

  return (
    <div style={{ maxWidth: 980, margin: "0 auto", padding: "40px 24px 60px" }}>
      <button onClick={() => onNav({ name: "auctions" })} style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--text-2)", fontSize: 12.5, fontWeight: 600, marginBottom: 22 }}>
        <i data-lucide="arrow-left" style={{ width: 15, height: 15 }}></i> Back
      </button>
      <div style={{ textAlign: "center", marginBottom: 36 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11, fontWeight: 800, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ignite)", marginBottom: 14 }}>
          <i data-lucide="package-plus" style={{ width: 14, height: 14 }}></i> Sell your equipment
        </span>
        <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 40, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: 0, lineHeight: 1.02 }}>
          Two ways to sell
        </h1>
        <p style={{ fontSize: 15, color: "var(--text-2)", marginTop: 12, maxWidth: 560, marginInline: "auto", lineHeight: 1.6 }}>
          Pick the route that fits your machine. Same photos, specs and video either way — choose one now, add the other anytime.
        </p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }} className="eb-form-2">
        {DOORS.map((d) => (
          <div key={d.mode} style={{ display: "flex", flexDirection: "column", background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 16, padding: 28, transition: "border-color .15s, transform .15s" }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = d.accent; e.currentTarget.style.transform = "translateY(-3px)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.transform = "none"; }}>
            <span style={{ width: 52, height: 52, borderRadius: 13, background: d.tint, display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 18 }}>
              <i data-lucide={d.icon} style={{ width: 24, height: 24, color: d.accent }}></i>
            </span>
            <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: d.accent, marginBottom: 6 }}>{d.tag}</div>
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 26, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", margin: "0 0 8px" }}>{d.title}</h2>
            <p style={{ fontSize: 13.5, color: "var(--text-2)", lineHeight: 1.6, marginBottom: 18 }}>{d.blurb}</p>
            <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 10, marginBottom: 24, flex: 1 }}>
              {d.points.map((p) => (
                <li key={p} style={{ display: "flex", alignItems: "flex-start", gap: 9, fontSize: 13, color: "var(--text-2)" }}>
                  <i data-lucide="check" style={{ width: 15, height: 15, color: d.accent, flexShrink: 0, marginTop: 1 }}></i>
                  <span>{p}</span>
                </li>
              ))}
            </ul>
            <button onClick={() => onNav({ name: "sellflow", mode: d.mode })} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, width: "100%", padding: "13px", borderRadius: 8, fontSize: 14, fontWeight: 700, color: "#fff", background: d.accent }}>
              <i data-lucide={d.icon} style={{ width: 16, height: 16 }}></i> {d.mode === "auction" ? "Start an auction" : "Create a listing"}
            </button>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 12, justifyContent: "center", marginTop: 24, padding: "14px 18px", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 10, maxWidth: 640, marginInline: "auto" }}>
        <i data-lucide="git-merge" style={{ width: 18, height: 18, color: "var(--text-3)", flexShrink: 0 }}></i>
        <span style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.5 }}>
          <strong style={{ color: "var(--text)" }}>List once, sell both ways.</strong> Publish to one channel and we'll let you mirror the same item to the other — your media and specs carry over automatically.
        </span>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════
// UNIFIED SELL WIZARD
// ════════════════════════════════════════════════════
function SellFlow({ mode, prefill, onNav, onPublish }) {
  const isAuction = mode === "auction";
  const accent = isAuction ? "var(--ignite)" : "var(--cobalt)";
  const crossListing = !!(prefill && prefill.groupId);

  const [step, setStep] = useSell(crossListing ? 4 : 1);
  const [done, setDone] = useSell(false);
  const [groupId] = useSell(() => (prefill && prefill.groupId) || "grp-" + Date.now());
  const [f, setF] = useSell({
    category: prefill?.category || "",
    condition: prefill?.condition || "Used",
    title: prefill?.title || "",
    manufacturer: prefill?.manufacturer || "",
    year: prefill?.year ? String(prefill.year) : "",
    hours: prefill?.hours || "",
    location: prefill?.location || "",
    description: prefill?.description || "",
    images: prefill?.images ? [...prefill.images, null, null, null, null, null].slice(0, 5) : [null, null, null, null, null],
    hasVideo: prefill?.hasVideo || false,
    // auction
    startingPrice: "", reservePrice: "", minIncrement: "250", antiSnipe: "120", duration: "7",
    // marketplace
    askingPrice: "", negotiable: true, acceptOffers: true,
  });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));

  const fillImage = (i) => setF((p) => { const im = [...p.images]; im[i] = SELL_SAMPLES[i % SELL_SAMPLES.length]; return { ...p, images: im }; });
  const clearImage = (i) => setF((p) => { const im = [...p.images]; im[i] = null; return { ...p, images: im }; });
  const filledImages = f.images.filter(Boolean);

  const STEPS = [
    { n: 1, label: "Equipment", icon: "package" },
    { n: 2, label: "Details", icon: "file-text" },
    { n: 3, label: "Media", icon: "camera" },
    { n: 4, label: isAuction ? "Auction" : "Price", icon: isAuction ? "gavel" : "tag" },
    { n: 5, label: "Review", icon: "check-circle" },
  ];

  const canNext = {
    1: !!f.category,
    2: f.title && f.manufacturer && f.year && f.location && f.description.length >= 20,
    3: filledImages.length >= 1,
    4: isAuction ? (f.startingPrice && Number(f.startingPrice) > 0) : (f.askingPrice && Number(f.askingPrice) > 0),
    5: true,
  }[step];

  const sharedCore = () => ({
    category: f.category, condition: f.condition, title: f.title, manufacturer: f.manufacturer,
    year: f.year, hours: f.hours, location: f.location, description: f.description,
    images: filledImages, hasVideo: f.hasVideo, groupId,
  });

  // ── Success ──
  if (done) {
    const other = isAuction ? "marketplace" : "auction";
    return (
      <div style={{ maxWidth: 560, margin: "0 auto", padding: "64px 24px", textAlign: "center" }}>
        <span style={{ width: 72, height: 72, borderRadius: 18, background: "rgba(34,197,94,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 22 }}>
          <i data-lucide="party-popper" style={{ width: 34, height: 34, color: "#22C55E" }}></i>
        </span>
        <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 32, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: 0 }}>
          {isAuction ? "Auction submitted" : "Listing published"}
        </h1>
        <p style={{ fontSize: 14.5, color: "var(--text-2)", marginTop: 12, lineHeight: 1.6 }}>
          <strong style={{ color: "var(--text)" }}>{f.title}</strong> {isAuction ? "is under review and will go live shortly." : "is now live on the marketplace."}
        </p>

        {/* Cross-list card */}
        <div style={{ marginTop: 26, padding: "20px", background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 14, textAlign: "left", display: "flex", gap: 14, alignItems: "center" }}>
          <span style={{ width: 46, height: 46, borderRadius: 11, background: isAuction ? "rgba(37,99,235,0.1)" : "rgba(249,115,22,0.1)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <i data-lucide={isAuction ? "store" : "gavel"} style={{ width: 22, height: 22, color: isAuction ? "var(--cobalt)" : "var(--ignite)" }}></i>
          </span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--text)" }}>
              {isAuction ? "Also list it on the Marketplace?" : "Also sell it by Auction?"}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--text-3)", marginTop: 2 }}>Your photos, specs and video are already done — just set the {isAuction ? "asking price" : "auction terms"}.</div>
          </div>
          <button onClick={() => onNav({ name: "sellflow", mode: other, prefill: sharedCore() })} style={{ ...ghostBtn, borderColor: isAuction ? "var(--cobalt)" : "var(--ignite)", color: isAuction ? "var(--cobalt)" : "var(--ignite)", whiteSpace: "nowrap" }}>
            <i data-lucide="plus" style={{ width: 14, height: 14 }}></i> {isAuction ? "Add listing" : "Add auction"}
          </button>
        </div>

        <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 22 }}>
          <button onClick={() => onNav({ name: "account", tab: "selling" })} style={primaryBtn}>View my listings</button>
          <button onClick={() => onNav({ name: "auctions" })} style={ghostBtn}>Back to auctions</button>
        </div>
      </div>
    );
  }

  const firstStep = crossListing ? 4 : 1;

  return (
    <div style={{ maxWidth: 1000, margin: "0 auto", padding: "26px 24px 50px" }}>
      <button onClick={() => onNav({ name: "sell" })} style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--text-2)", fontSize: 12.5, fontWeight: 600, marginBottom: 18 }}>
        <i data-lucide="arrow-left" style={{ width: 15, height: 15 }}></i> Choose a different way to sell
      </button>
      <div style={{ marginBottom: 22 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11, fontWeight: 800, letterSpacing: ".12em", textTransform: "uppercase", color: accent, marginBottom: 10 }}>
          <i data-lucide={isAuction ? "gavel" : "store"} style={{ width: 14, height: 14 }}></i> {isAuction ? "Auction" : "Marketplace"}
        </span>
        <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 32, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: "0 0 4px", lineHeight: 1.05 }}>
          {isAuction ? "New auction" : "New listing"}
        </h1>
        <p style={{ fontSize: 14, color: "var(--text-3)", margin: 0 }}>
          {isAuction ? "Sell to the highest bidder over a fixed window." : "Post at a fixed asking price on the marketplace."}
        </p>
      </div>

      {/* Cross-list banner */}
      {crossListing && (
        <div style={{ display: "flex", alignItems: "center", gap: 11, background: "rgba(34,197,94,0.08)", border: "1px solid rgba(34,197,94,0.25)", borderRadius: 10, padding: "12px 16px", marginBottom: 22 }}>
          <i data-lucide="git-merge" style={{ width: 17, height: 17, color: "#22C55E", flexShrink: 0 }}></i>
          <span style={{ fontSize: 13, color: "var(--text-2)" }}>
            Mirroring <strong style={{ color: "var(--text)" }}>{f.title}</strong> — details &amp; media carried over. Just set your {isAuction ? "auction terms" : "price"}.
          </span>
        </div>
      )}

      {/* Stepper */}
      <div style={{ display: "flex", alignItems: "center", marginBottom: 30, opacity: crossListing ? 0.6 : 1 }}>
        {STEPS.map((s, i) => (
          <React.Fragment key={s.n}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{
                width: 34, height: 34, borderRadius: 9, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                background: step > s.n ? "#22C55E" : step === s.n ? accent : "var(--surface)",
                border: `1px solid ${step >= s.n ? "transparent" : "var(--border)"}`,
                color: step >= s.n ? "#fff" : "var(--text-3)",
              }}>
                {step > s.n ? <i data-lucide="check" style={{ width: 16, height: 16 }}></i> : <i data-lucide={s.icon} style={{ width: 15, height: 15 }}></i>}
              </span>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: step >= s.n ? "var(--text)" : "var(--text-3)", whiteSpace: "nowrap" }} className="eb-hide-sm">{s.label}</span>
            </div>
            {i < STEPS.length - 1 && <div style={{ flex: 1, height: 1, background: step > s.n ? "#22C55E" : "var(--border)", margin: "0 12px" }}></div>}
          </React.Fragment>
        ))}
      </div>

      <div style={{ background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 14, padding: 28 }}>
        {/* STEP 1 — Equipment */}
        {step === 1 && (
          <div>
            <SF_Head title="What are you selling?" sub="Pick the category that best fits your machine." />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))", gap: 10, marginBottom: 26 }}>
              {SELL_CATEGORIES.map((c) => (
                <button key={c} onClick={() => set("category", c)} style={{
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 9, padding: "20px 12px", borderRadius: 10, cursor: "pointer",
                  border: `1px solid ${f.category === c ? accent : "var(--border)"}`,
                  background: f.category === c ? (isAuction ? "rgba(249,115,22,0.08)" : "rgba(37,99,235,0.08)") : "var(--surface)",
                }}>
                  <i data-lucide={SELL_ICONS[c]} style={{ width: 22, height: 22, color: f.category === c ? accent : "var(--text-2)" }}></i>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text)", textAlign: "center" }}>{c}</span>
                </button>
              ))}
            </div>
            <label style={fieldLabel}>Condition</label>
            <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
              {["New", "Used", "Refurbished"].map((c) => <button key={c} onClick={() => set("condition", c)} style={sfPill(f.condition === c)}>{c}</button>)}
            </div>
          </div>
        )}

        {/* STEP 2 — Details */}
        {step === 2 && (
          <div>
            <SF_Head title="Tell buyers about it" sub="Accurate details get more interest and fewer questions." />
            <div style={sfFormCol}>
              <SF_Field label="Listing title"><input value={f.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. Caterpillar 320D L Excavator" style={inputStyle} /></SF_Field>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }} className="eb-form-3">
                <SF_Field label="Manufacturer"><input value={f.manufacturer} onChange={(e) => set("manufacturer", e.target.value)} placeholder="Caterpillar" style={inputStyle} /></SF_Field>
                <SF_Field label="Year"><input value={f.year} onChange={(e) => set("year", e.target.value.replace(/\D/g, "").slice(0, 4))} placeholder="2018" style={inputStyle} /></SF_Field>
                <SF_Field label="Hours / km"><input value={f.hours} onChange={(e) => set("hours", e.target.value)} placeholder="6,420" style={inputStyle} /></SF_Field>
              </div>
              <SF_Field label="Location"><div style={{ position: "relative" }}><i data-lucide="map-pin" style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", width: 15, height: 15, color: "var(--text-3)" }}></i><input value={f.location} onChange={(e) => set("location", e.target.value)} placeholder="Belgrade, Serbia" style={{ ...inputStyle, paddingLeft: 34 }} /></div></SF_Field>
              <SF_Field label="Description" right={<span style={{ fontSize: 11, color: f.description.length >= 20 ? "#22C55E" : "var(--text-3)" }}>{f.description.length}/20 min</span>}>
                <textarea value={f.description} onChange={(e) => set("description", e.target.value)} rows={5} placeholder="Service history, attachments included, condition notes, reason for sale…" style={{ ...inputStyle, resize: "vertical", lineHeight: 1.6 }} />
              </SF_Field>
            </div>
          </div>
        )}

        {/* STEP 3 — Media */}
        {step === 3 && (
          <div>
            <SF_Head title="Add photos & video" sub="Listings with video get up to 3× more interest. First photo is the cover." />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))", gap: 12, marginBottom: 24 }}>
              {f.images.map((img, i) => (
                <div key={i} style={{ position: "relative", aspectRatio: "4/3", borderRadius: 10, overflow: "hidden", border: `1px dashed ${img ? "transparent" : "var(--border-s)"}`, background: "var(--surface)" }}>
                  {img ? (
                    <>
                      <EquipImage src={img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                      {i === 0 && <span style={{ position: "absolute", top: 7, left: 7, fontSize: 9.5, fontWeight: 800, letterSpacing: ".06em", textTransform: "uppercase", background: accent, color: "#fff", padding: "3px 7px", borderRadius: 4 }}>Cover</span>}
                      <button onClick={() => clearImage(i)} style={{ position: "absolute", top: 7, right: 7, width: 24, height: 24, borderRadius: 6, background: "rgba(15,23,42,0.8)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><i data-lucide="x" style={{ width: 13, height: 13 }}></i></button>
                    </>
                  ) : (
                    <button onClick={() => fillImage(i)} style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 7, color: "var(--text-3)" }}>
                      <i data-lucide="image-plus" style={{ width: 22, height: 22 }}></i>
                      <span style={{ fontSize: 11.5, fontWeight: 600 }}>{i === 0 ? "Add cover" : "Add photo"}</span>
                    </button>
                  )}
                </div>
              ))}
            </div>
            <button onClick={() => set("hasVideo", !f.hasVideo)} style={{
              width: "100%", display: "flex", alignItems: "center", gap: 14, padding: "16px 18px", borderRadius: 10, cursor: "pointer", textAlign: "left",
              border: `1px solid ${f.hasVideo ? accent : "var(--border-s)"}`, background: f.hasVideo ? (isAuction ? "rgba(249,115,22,0.06)" : "rgba(37,99,235,0.06)") : "var(--surface)",
            }}>
              <span style={{ width: 44, height: 44, borderRadius: 10, background: f.hasVideo ? accent : "var(--surface-2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <i data-lucide={f.hasVideo ? "video" : "video-off"} style={{ width: 20, height: 20, color: f.hasVideo ? "#fff" : "var(--text-3)" }}></i>
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text)" }}>Walkaround video {f.hasVideo && <span style={{ color: "#22C55E", fontSize: 11.5 }}>· Added</span>}</div>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{f.hasVideo ? "video-walkaround.mp4 · 24 MB" : "Tap to attach a video file (MP4, MOV)"}</div>
              </div>
              <i data-lucide={f.hasVideo ? "check-circle-2" : "upload"} style={{ width: 18, height: 18, color: f.hasVideo ? "#22C55E" : "var(--text-3)" }}></i>
            </button>
          </div>
        )}

        {/* STEP 4 — Pricing (diverges) */}
        {step === 4 && isAuction && (
          <div>
            <SF_Head title="Auction terms" sub="Set your opening bid, optional reserve and how long bidding runs." />
            <div style={sfFormCol}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="eb-form-2">
                <SF_Field label="Starting price"><div style={{ display: "flex", gap: 8 }}><span style={eurPrefix}>€</span><input value={f.startingPrice} onChange={(e) => set("startingPrice", e.target.value.replace(/[^\d]/g, ""))} placeholder="28000" style={{ ...inputStyle, fontFamily: "var(--ff-mono)" }} /></div></SF_Field>
                <SF_Field label="Reserve price" right={<span style={{ fontSize: 11, color: "var(--text-3)", textTransform: "none", letterSpacing: 0, fontWeight: 500 }}>optional</span>}><div style={{ display: "flex", gap: 8 }}><span style={eurPrefix}>€</span><input value={f.reservePrice} onChange={(e) => set("reservePrice", e.target.value.replace(/[^\d]/g, ""))} placeholder="30000" style={{ ...inputStyle, fontFamily: "var(--ff-mono)" }} /></div></SF_Field>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="eb-form-2">
                <SF_Field label="Min. bid increment"><div style={{ display: "flex", gap: 8 }}><span style={eurPrefix}>€</span><input value={f.minIncrement} onChange={(e) => set("minIncrement", e.target.value.replace(/[^\d]/g, ""))} style={{ ...inputStyle, fontFamily: "var(--ff-mono)" }} /></div></SF_Field>
                <SF_Field label="Anti-snipe window"><select value={f.antiSnipe} onChange={(e) => set("antiSnipe", e.target.value)} style={{ ...inputStyle, cursor: "pointer" }}><option value="0">Off</option><option value="60">60 seconds</option><option value="120">2 minutes</option><option value="180">3 minutes</option></select></SF_Field>
              </div>
              <SF_Field label="Auction duration">
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>{["3", "5", "7", "10", "14"].map((d) => <button key={d} onClick={() => set("duration", d)} style={sfPill(f.duration === d)}>{d} days</button>)}</div>
              </SF_Field>
              <FeeNote pct="5% seller fee" detail="charged only when your item sells. Listing is free." />
            </div>
          </div>
        )}

        {step === 4 && !isAuction && (
          <div>
            <SF_Head title="Set your price" sub="Post at a fixed asking price. You decide whether to take offers." />
            <div style={sfFormCol}>
              <SF_Field label="Asking price"><div style={{ display: "flex", gap: 8, maxWidth: 280 }}><span style={eurPrefix}>€</span><input value={f.askingPrice} onChange={(e) => set("askingPrice", e.target.value.replace(/[^\d]/g, ""))} placeholder="29500" style={{ ...inputStyle, fontFamily: "var(--ff-mono)", fontSize: 17 }} /></div></SF_Field>
              <ToggleRow label="Accept offers" sub="Let buyers propose a lower price you can accept or counter." on={f.acceptOffers} onClick={() => set("acceptOffers", !f.acceptOffers)} accent={accent} />
              <ToggleRow label="Price negotiable" sub="Show a 'negotiable' tag so buyers know there's room to talk." on={f.negotiable} onClick={() => set("negotiable", !f.negotiable)} accent={accent} />
              <FeeNote pct="3% marketplace fee" detail="charged only when your item sells. Listing is free." />
            </div>
          </div>
        )}

        {/* STEP 5 — Review */}
        {step === 5 && (
          <div>
            <SF_Head title="Review & publish" sub="Check everything looks right. You can still edit after publishing." />
            <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 280px", gap: 20 }} className="eb-form-2">
              <div>
                <div style={{ borderRadius: 10, overflow: "hidden", border: "1px solid var(--border)", marginBottom: 14 }}>
                  <EquipImage src={filledImages[0] || SELL_SAMPLES[0]} alt="" style={{ width: "100%", aspectRatio: "16/10", objectFit: "cover" }} />
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  {filledImages.slice(1).map((img, i) => <EquipImage key={i} src={img} alt="" style={{ width: 64, height: 48, objectFit: "cover", borderRadius: 6 }} />)}
                  {f.hasVideo && <span style={{ width: 64, height: 48, borderRadius: 6, background: "var(--surface-2)", display: "flex", alignItems: "center", justifyContent: "center" }}><i data-lucide="video" style={{ width: 16, height: 16, color: accent }}></i></span>}
                </div>
              </div>
              <div>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 10.5, fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase", color: accent, marginBottom: 10 }}>
                  <i data-lucide={isAuction ? "gavel" : "store"} style={{ width: 13, height: 13 }}></i> {isAuction ? "Auction" : "Marketplace"}
                </span>
                <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 22, fontWeight: 800, color: "var(--text)", margin: "0 0 4px", textTransform: "uppercase", lineHeight: 1.1 }}>{f.title || "Untitled"}</h3>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 16 }}>{[f.category, f.year, f.condition].filter(Boolean).join(" · ")}</div>
                {(isAuction
                  ? [["Starting price", f.startingPrice ? eur(Number(f.startingPrice)) : "—"], ["Reserve", f.reservePrice ? eur(Number(f.reservePrice)) : "None"], ["Increment", eur(Number(f.minIncrement || 0))], ["Duration", f.duration + " days"], ["Location", f.location || "—"]]
                  : [["Asking price", f.askingPrice ? eur(Number(f.askingPrice)) : "—"], ["Offers", f.acceptOffers ? "Accepted" : "Off"], ["Negotiable", f.negotiable ? "Yes" : "No"], ["Location", f.location || "—"]]
                ).map(([k, v]) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", 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>
            </div>
          </div>
        )}

        {/* Nav */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 28, paddingTop: 22, borderTop: "1px solid var(--border)" }}>
          <button onClick={() => (step === firstStep ? onNav({ name: "sell" }) : setStep(step - 1))} style={ghostBtn}>
            <i data-lucide="chevron-left" style={{ width: 15, height: 15 }}></i> {step === firstStep ? "Back" : "Previous"}
          </button>
          {step < 5 ? (
            <button onClick={() => canNext && setStep(step + 1)} disabled={!canNext} style={{ ...primaryBtn, background: accent, opacity: canNext ? 1 : 0.5, cursor: canNext ? "pointer" : "not-allowed" }}>
              Continue <i data-lucide="chevron-right" style={{ width: 15, height: 15 }}></i>
            </button>
          ) : (
            <button onClick={() => { onPublish({ ...f, filledImages, groupId }, mode); setDone(true); }} style={{ ...primaryBtn, background: "#22C55E" }}>
              <i data-lucide={isAuction ? "rocket" : "check"} style={{ width: 15, height: 15 }}></i> {isAuction ? "Submit auction" : "Publish listing"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function FeeNote({ pct, detail }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, background: "rgba(37,99,235,0.07)", border: "1px solid rgba(37,99,235,0.2)", borderRadius: 8, padding: "12px 14px" }}>
      <i data-lucide="info" style={{ width: 16, height: 16, color: "var(--cobalt)", flexShrink: 0 }}></i>
      <span style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.5 }}>Equipment Balkans charges a <strong style={{ color: "var(--text)" }}>{pct}</strong> {detail}</span>
    </div>
  );
}

function ToggleRow({ label, sub, on, onClick, accent }) {
  return (
    <button onClick={onClick} style={{ width: "100%", display: "flex", alignItems: "center", gap: 14, padding: "13px 16px", borderRadius: 10, cursor: "pointer", textAlign: "left", border: "1px solid var(--border)", background: "var(--surface)" }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text)" }}>{label}</div>
        <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{sub}</div>
      </div>
      <span style={{ width: 40, height: 23, borderRadius: 12, background: on ? accent : "var(--surface-2)", position: "relative", transition: "background .15s", flexShrink: 0 }}>
        <span style={{ position: "absolute", top: 2, left: on ? 19 : 2, width: 19, height: 19, borderRadius: "50%", background: "#fff", transition: "left .15s", boxShadow: "0 1px 3px rgba(0,0,0,0.3)" }}></span>
      </span>
    </button>
  );
}

// ════════════════════════════════════════════════════
// MARKETPLACE CARD (account selling)
// ════════════════════════════════════════════════════
function MarketplaceCard({ listing, onOpen, note }) {
  const [hover, setHover] = useSell(false);
  return (
    <div onClick={() => onOpen(listing.id)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ background: "var(--card-bg)", border: `1px solid ${hover ? "rgba(37,99,235,0.5)" : "var(--border)"}`, borderRadius: 12, overflow: "hidden", cursor: "pointer", transition: "border-color .18s, transform .18s, box-shadow .18s", transform: hover ? "translateY(-3px)" : "none", boxShadow: hover ? "var(--shadow-hover)" : "var(--shadow-card)", display: "flex", flexDirection: "column" }}>
      <div style={{ position: "relative", aspectRatio: "16/10", overflow: "hidden" }}>
        <EquipImage src={listing.images[0]} alt={listing.title} style={{ width: "100%", height: "100%", objectFit: "cover", transition: "transform .4s", transform: hover ? "scale(1.05)" : "scale(1)" }} />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(15,23,42,0.5), transparent 45%)" }}></div>
        <div style={{ position: "absolute", top: 11, left: 11 }}><StatusBadge status="listed" /></div>
        {listing.hasVideo && <span style={{ position: "absolute", top: 9, right: 9, width: 26, height: 26, borderRadius: 6, background: "rgba(15,23,42,0.65)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff" }}><i data-lucide="video" style={{ width: 12, height: 12 }}></i></span>}
      </div>
      <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)" }}>{listing.category}</span>
          <span>·</span><span>{listing.year}</span>
          <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 4 }}><i data-lucide="map-pin" style={{ width: 11, height: 11 }}></i>{listing.location.split(",")[1]?.trim() || listing.location}</span>
        </div>
        <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 19, fontWeight: 800, color: "var(--text)", lineHeight: 1.15, margin: 0 }}>{listing.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 }}>Asking price</div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 22, fontWeight: 700, color: "var(--cobalt)", lineHeight: 1 }}>{eur(listing.askingPrice)}</div>
          </div>
          <div style={{ textAlign: "right" }}>
            {listing.negotiable && <span style={{ fontSize: 10, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em" }}>Negotiable</span>}
            <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 5, fontFamily: "var(--ff-mono)" }}>{listing.offers || 0} offer{(listing.offers || 0) !== 1 ? "s" : ""}</div>
          </div>
        </div>
        {note && (
          <div style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 10.5, fontWeight: 700, color: "var(--ignite)", borderTop: "1px solid var(--border)", paddingTop: 9 }}>
            <i data-lucide="link" style={{ width: 12, height: 12 }}></i>{note}
          </div>
        )}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════
// MARKETPLACE DETAIL RAIL (right column of DetailScreen)
// ════════════════════════════════════════════════════
function MarketRail({ auction, user, onNav }) {
  const [showOffer, setShowOffer] = useSell(false);
  const [offer, setOffer] = useSell("");
  const [feedback, setFeedback] = useSell(null); // 'offer' | 'buy'
  const listing = auction;

  if (feedback) {
    return (
      <div style={{ ...panelCard, textAlign: "center" }}>
        <span style={{ width: 48, height: 48, borderRadius: 12, background: "rgba(34,197,94,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
          <i data-lucide={feedback === "buy" ? "shopping-bag" : "send"} style={{ width: 22, height: 22, color: "#22C55E" }}></i>
        </span>
        <div style={{ fontSize: 15.5, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", marginBottom: 5 }}>
          {feedback === "buy" ? "Purchase request sent" : "Offer sent"}
        </div>
        <div style={{ fontSize: 12.5, color: "var(--text-3)", marginBottom: 14, lineHeight: 1.5 }}>
          {feedback === "buy" ? "The seller will confirm availability and payment details shortly." : `You offered ${eur(Number(offer))}. We'll notify you when the seller responds.`}
        </div>
        <button onClick={() => onNav({ name: "auctions" })} style={{ ...ghostBtn, width: "100%", justifyContent: "center" }}>Keep browsing</button>
      </div>
    );
  }

  return (
    <>
      {/* Price card */}
      <div style={panelCard}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".09em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 5 }}>Asking price</div>
        <div style={{ fontFamily: "var(--ff-mono)", fontSize: 34, fontWeight: 700, color: "var(--cobalt)", lineHeight: 1 }}>{eur(listing.askingPrice)}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 10 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, color: "var(--text-3)" }}><i data-lucide="store" style={{ width: 13, height: 13 }}></i> Marketplace listing</span>
          {listing.negotiable && <span style={{ fontSize: 10.5, fontWeight: 700, color: "#16A34A", textTransform: "uppercase", letterSpacing: ".05em" }}>· Negotiable</span>}
        </div>
      </div>

      {/* Action card */}
      <div style={panelCard}>
        {user ? (
          <>
            <button onClick={() => onNav({ name: "checkout", id: listing.id, mode: "buy" })} style={{ ...primaryBtn, width: "100%", justifyContent: "center", background: "var(--cobalt)", fontSize: 14, padding: "13px" }}>
              <i data-lucide="shopping-bag" style={{ width: 16, height: 16 }}></i> Buy now · {eur(listing.askingPrice)}
            </button>
            {listing.acceptOffers && !showOffer && (
              <button onClick={() => setShowOffer(true)} style={{ ...ghostBtn, width: "100%", justifyContent: "center", marginTop: 9 }}>
                <i data-lucide="hand-coins" style={{ width: 15, height: 15 }}></i> Make an offer
              </button>
            )}
            {listing.acceptOffers && showOffer && (
              <div style={{ marginTop: 11 }}>
                <label style={fieldLabel}>Your offer</label>
                <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
                  <span style={eurPrefix}>€</span>
                  <input type="number" value={offer} onChange={(e) => setOffer(e.target.value)} placeholder={Math.round(listing.askingPrice * 0.9).toLocaleString()} style={{ ...inputStyle, flex: 1, fontFamily: "var(--ff-mono)" }} />
                  <button onClick={() => offer && Number(offer) > 0 && setFeedback("offer")} style={{ ...primaryBtn, background: "var(--cobalt)" }}>Send</button>
                </div>
              </div>
            )}
            <button style={{ ...ghostBtn, width: "100%", justifyContent: "center", marginTop: 9 }}>
              <i data-lucide="message-square" style={{ width: 15, height: 15 }}></i> Message seller
            </button>
            <div style={{ fontSize: 11, color: "var(--text-3)", textAlign: "center", marginTop: 11, display: "flex", alignItems: "center", justifyContent: "center", gap: 5 }}>
              <i data-lucide="shield-check" style={{ width: 11, height: 11 }}></i> Buyer protection on every purchase.
            </div>
          </>
        ) : (
          <div style={{ textAlign: "center" }}>
            <span style={{ width: 44, height: 44, borderRadius: 10, background: "rgba(37,99,235,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
              <i data-lucide="log-in" style={{ width: 20, height: 20, color: "var(--cobalt)" }}></i>
            </span>
            <div style={{ fontSize: 15.5, fontWeight: 800, color: "var(--text)", fontFamily: "var(--ff-display)", marginBottom: 5 }}>Sign in to buy or offer</div>
            <div style={{ fontSize: 12.5, color: "var(--text-3)", marginBottom: 15, lineHeight: 1.5 }}>Create a free account to purchase, make offers and message sellers.</div>
            <button onClick={() => onNav({ name: "signin", redirect: { name: "detail", id: listing.id } })} style={{ ...primaryBtn, width: "100%", justifyContent: "center", background: "var(--cobalt)" }}>Sign in</button>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { SellChoiceScreen, SellFlow, MarketplaceCard, MarketRail });
