/* ─────────────────────────────────────────────────────
   Equipment Balkans — Auth, Sell wizard, Account screens
───────────────────────────────────────────────────── */
const { useState: useS2, useEffect: useE2, useRef: useR2 } = React;

// ════════════════════════════════════════════════════
// AUTH SHELL
// ════════════════════════════════════════════════════
function AuthShell({ children, sub }) {
  return (
    <div style={{ minHeight: "calc(100vh - 64px)", display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 16px", position: "relative", overflow: "hidden" }}>
      <EquipImage src={"https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=1600&h=1000&fit=crop&auto=format&q=80"} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.18 }} />
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at center, var(--veil), var(--bg) 80%)" }}></div>
      <div style={{ position: "relative", width: "100%", maxWidth: 420, display: "flex", flexDirection: "column", alignItems: "center", gap: 22 }}>
        {children}
        {sub}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════
// SIGN IN
// ════════════════════════════════════════════════════
function SignInScreen({ onAuth, onNav, redirect }) {
  const [mode, setMode] = useS2("password");
  const [email, setEmail] = useS2("");
  const [pw, setPw] = useS2("");
  const [showPw, setShowPw] = useS2(false);
  const [magicSent, setMagicSent] = useS2(false);
  const [code, setCode] = useS2("");
  const [err, setErr] = useS2("");

  const go = (name) => onAuth({ email: email || "buyer@balkans.eu", name: (email || "Marko Petrović").split("@")[0] }, redirect);

  const submit = (e) => {
    e.preventDefault();
    setErr("");
    if (!email) return setErr("Enter your email.");
    if (mode === "password" && !pw) return setErr("Enter your password.");
    go();
  };

  return (
    <AuthShell sub={<p style={{ fontSize: 13, color: "var(--text-3)" }}>Don't have an account? <button onClick={() => onNav({ name: "signup", redirect })} style={linkBtn}>Sign up</button></p>}>
      <div style={authCard}>
        <h1 style={authTitle}>Welcome back</h1>
        <p style={authLede}>Sign in to bid, sell and manage your equipment.</p>

        {err && <div style={errBox}><i data-lucide="alert-triangle" style={{ width: 15, height: 15, color: "#F87171" }}></i><span>{err}</span></div>}

        <div style={segWrap}>
          <button onClick={() => { setMode("password"); setMagicSent(false); setErr(""); }} style={seg(mode === "password")}>Password</button>
          <button onClick={() => { setMode("magic"); setErr(""); }} style={seg(mode === "magic")}>Magic link</button>
        </div>

        {mode === "password" && (
          <form onSubmit={submit} style={formCol}>
            <Field label="Email"><input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" style={inputStyle} /></Field>
            <Field label="Password" right={<button type="button" onClick={() => onNav({ name: "forgot" })} style={linkBtn}>Forgot?</button>}>
              <div style={{ position: "relative" }}>
                <input type={showPw ? "text" : "password"} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" style={inputStyle} />
                <button type="button" onClick={() => setShowPw((s) => !s)} style={eyeBtn}><i data-lucide={showPw ? "eye-off" : "eye"} style={{ width: 15, height: 15 }}></i></button>
              </div>
            </Field>
            <button type="submit" style={igniteBtn}>Sign in</button>
          </form>
        )}

        {mode === "magic" && !magicSent && (
          <form onSubmit={(e) => { e.preventDefault(); if (!email) return setErr("Enter your email."); setMagicSent(true); }} style={formCol}>
            <Field label="Email"><input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" style={inputStyle} /></Field>
            <button type="submit" style={igniteBtn}><i data-lucide="mail" style={{ width: 15, height: 15 }}></i> Send magic code</button>
          </form>
        )}

        {mode === "magic" && magicSent && (
          <form onSubmit={(e) => { e.preventDefault(); if (code.length < 6) return setErr("Enter the 6-digit code."); go(); }} style={formCol}>
            <div style={{ fontSize: 13, color: "var(--text-2)", background: "var(--bg)", border: "1px solid var(--border-s)", borderRadius: 6, padding: "11px 13px" }}>
              We sent a 6-digit code to <strong style={{ color: "var(--text)" }}>{email}</strong>
            </div>
            <Field label="Verification code"><input value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))} placeholder="000000" style={{ ...inputStyle, textAlign: "center", letterSpacing: ".4em", fontSize: 19, fontFamily: "var(--ff-mono)" }} /></Field>
            <button type="submit" style={igniteBtn}>Verify & sign in</button>
            <button type="button" onClick={() => setMagicSent(false)} style={{ fontSize: 12.5, color: "var(--text-3)" }}>Use a different email</button>
          </form>
        )}

        <Divider />
        <SocialButtons onClick={() => go()} />
      </div>
    </AuthShell>
  );
}

// ════════════════════════════════════════════════════
// SIGN UP
// ════════════════════════════════════════════════════
function SignUpScreen({ onAuth, onNav, redirect }) {
  const [name, setName] = useS2("");
  const [email, setEmail] = useS2("");
  const [pw, setPw] = useS2("");
  const [acctType, setAcctType] = useS2("buyer");
  const [showPw, setShowPw] = useS2(false);
  const [err, setErr] = useS2("");

  const submit = (e) => {
    e.preventDefault();
    setErr("");
    if (!name || !email || !pw) return setErr("Fill in all fields.");
    if (pw.length < 8) return setErr("Password must be at least 8 characters.");
    onAuth({ email, name, role: acctType }, redirect);
  };

  return (
    <AuthShell sub={<p style={{ fontSize: 13, color: "var(--text-3)" }}>Already have an account? <button onClick={() => onNav({ name: "signin", redirect })} style={linkBtn}>Sign in</button></p>}>
      <div style={authCard}>
        <h1 style={authTitle}>Create your account</h1>
        <p style={authLede}>Bid on equipment or list your own — free to join.</p>

        {err && <div style={errBox}><i data-lucide="alert-triangle" style={{ width: 15, height: 15, color: "#F87171" }}></i><span>{err}</span></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9, marginBottom: 18 }}>
          {[
            { v: "buyer", ico: "gavel", t: "I want to buy/bid", s: "Bid in auctions" },
            { v: "seller", ico: "tag", t: "I want to sell/auction", s: "List & auction gear" },
          ].map((o) => (
            <button key={o.v} onClick={() => setAcctType(o.v)} style={{
              textAlign: "left", padding: "13px 14px", borderRadius: 8, cursor: "pointer",
              border: `1px solid ${acctType === o.v ? "var(--ignite)" : "var(--border-s)"}`,
              background: acctType === o.v ? "rgba(249,115,22,0.08)" : "var(--bg)",
            }}>
              <i data-lucide={o.ico} style={{ width: 18, height: 18, color: acctType === o.v ? "var(--ignite)" : "var(--text-3)" }}></i>
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text)", marginTop: 8 }}>{o.t}</div>
              <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{o.s}</div>
            </button>
          ))}
        </div>

        <form onSubmit={submit} style={formCol}>
          <Field label="Full name"><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Marko Petrović" style={inputStyle} /></Field>
          <Field label="Email"><input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" style={inputStyle} /></Field>
          <Field label="Password">
            <div style={{ position: "relative" }}>
              <input type={showPw ? "text" : "password"} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="At least 8 characters" style={inputStyle} />
              <button type="button" onClick={() => setShowPw((s) => !s)} style={eyeBtn}><i data-lucide={showPw ? "eye-off" : "eye"} style={{ width: 15, height: 15 }}></i></button>
            </div>
          </Field>
          <button type="submit" style={igniteBtn}>Create account</button>
          <p style={{ fontSize: 11, color: "var(--text-3)", textAlign: "center", lineHeight: 1.5 }}>
            By creating an account you agree to our Terms and Privacy Policy.
          </p>
        </form>

        <Divider />
        <SocialButtons onClick={() => onAuth({ email: email || "new@balkans.eu", name: name || "New User", role: acctType }, redirect)} />
      </div>
    </AuthShell>
  );
}

// ════════════════════════════════════════════════════
// FORGOT PASSWORD
// ════════════════════════════════════════════════════
function ForgotScreen({ onNav }) {
  const [email, setEmail] = useS2("");
  const [sent, setSent] = useS2(false);
  return (
    <AuthShell sub={<button onClick={() => onNav({ name: "signin" })} style={linkBtn}>← Back to sign in</button>}>
      <div style={authCard}>
        {sent ? (
          <div style={{ 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: 14 }}>
              <i data-lucide="mail-check" style={{ width: 22, height: 22, color: "#22C55E" }}></i>
            </span>
            <h1 style={authTitle}>Check your inbox</h1>
            <p style={authLede}>We sent a password reset link to <strong style={{ color: "var(--text)" }}>{email}</strong>.</p>
          </div>
        ) : (
          <>
            <h1 style={authTitle}>Reset password</h1>
            <p style={authLede}>Enter your email and we'll send you a reset link.</p>
            <form onSubmit={(e) => { e.preventDefault(); if (email) setSent(true); }} style={formCol}>
              <Field label="Email"><input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" style={inputStyle} /></Field>
              <button type="submit" style={igniteBtn}>Send reset link</button>
            </form>
          </>
        )}
      </div>
    </AuthShell>
  );
}

// ── Auth sub-components ──────────────────────────────
function 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 Divider() {
  return (
    <div style={{ position: "relative", margin: "22px 0 18px" }}>
      <div style={{ height: 1, background: "var(--border)" }}></div>
      <span style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)", background: "var(--surface)", padding: "0 12px", fontSize: 10.5, fontWeight: 700, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--text-3)" }}>or continue with</span>
    </div>
  );
}
function SocialButtons({ onClick }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
      <button onClick={onClick} style={socialBtn}>
        <svg width="15" height="15" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
        Google
      </button>
      <button onClick={onClick} style={socialBtn}>
        <svg width="15" height="15" viewBox="0 0 24 24"><rect x="1" y="1" width="10" height="10" fill="#F25022"/><rect x="13" y="1" width="10" height="10" fill="#7FBA00"/><rect x="1" y="13" width="10" height="10" fill="#00A4EF"/><rect x="13" y="13" width="10" height="10" fill="#FFB900"/></svg>
        Microsoft
      </button>
    </div>
  );
}

// ════════════════════════════════════════════════════
// SELL WIZARD (create auction)
// ════════════════════════════════════════════════════
const SAMPLE_UPLOADS = [
  "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_STEPS = [
  { n: 1, label: "Equipment", icon: "package" },
  { n: 2, label: "Details", icon: "file-text" },
  { n: 3, label: "Media", icon: "camera" },
  { n: 4, label: "Pricing", icon: "tag" },
  { n: 5, label: "Review", icon: "check-circle" },
];
const SELL_CATS = ["Excavator", "Wheel Loader", "Bulldozer", "Forklift", "CNC Machine", "Generator", "Crane", "Dump Truck", "Telehandler", "Other"];
const SELL_CAT_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" };

function SellScreen({ onNav, onPublish }) {
  const [step, setStep] = useS2(1);
  const [done, setDone] = useS2(false);
  const [f, setF] = useS2({
    category: "", condition: "Used", title: "", manufacturer: "", year: "", hours: "",
    location: "", description: "",
    images: [null, null, null, null, null], hasVideo: false,
    startingPrice: "", reservePrice: "", minIncrement: "250", antiSnipe: "120",
    duration: "7",
  });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));

  const fillImage = (i) => {
    setF((p) => {
      const imgs = [...p.images];
      imgs[i] = SAMPLE_UPLOADS[i % SAMPLE_UPLOADS.length];
      return { ...p, images: imgs };
    });
  };
  const clearImage = (i) => setF((p) => { const imgs = [...p.images]; imgs[i] = null; return { ...p, images: imgs }; });

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

  if (done) {
    return (
      <div style={{ maxWidth: 560, margin: "0 auto", padding: "70px 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: 34, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: 0 }}>Auction submitted</h1>
        <p style={{ fontSize: 14.5, color: "var(--text-2)", marginTop: 12, lineHeight: 1.6 }}>
          <strong style={{ color: "var(--text)" }}>{f.title}</strong> is under review. Our team verifies every listing — you'll be notified when it goes live, typically within a few hours.
        </p>
        <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 26 }}>
          <button onClick={() => onNav({ name: "account", tab: "selling" })} style={primaryBtn}>View my auctions</button>
          <button onClick={() => onNav({ name: "auctions" })} style={ghostBtn}>Back to auctions</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 1000, margin: "0 auto", padding: "26px 24px 50px" }}>
      <button onClick={() => onNav({ name: "auctions" })} 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> Cancel
      </button>
      <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 34, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: "0 0 4px" }}>Sell your equipment</h1>
      <p style={{ fontSize: 14, color: "var(--text-3)", marginBottom: 26 }}>List a machine for auction. Verified buyers across 32 countries.</p>

      {/* Stepper */}
      <div style={{ display: "flex", alignItems: "center", marginBottom: 30 }}>
        {SELL_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 ? "var(--ignite)" : "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 < SELL_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 */}
        {step === 1 && (
          <div>
            <StepHead 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_CATS.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 ? "var(--ignite)" : "var(--border)"}`,
                  background: f.category === c ? "rgba(249,115,22,0.08)" : "var(--surface)",
                }}>
                  <i data-lucide={SELL_CAT_ICONS[c]} style={{ width: 22, height: 22, color: f.category === c ? "var(--ignite)" : "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={pill(f.condition === c)}>{c}</button>
              ))}
            </div>
          </div>
        )}

        {/* STEP 2 */}
        {step === 2 && (
          <div>
            <StepHead title="Tell buyers about it" sub="Accurate details get more bids and fewer questions." />
            <div style={formCol}>
              <Field label="Listing title"><input value={f.title} onChange={(e) => set("title", e.target.value)} placeholder="e.g. Caterpillar 320D L Excavator" style={inputStyle} /></Field>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }} className="eb-form-3">
                <Field label="Manufacturer"><input value={f.manufacturer} onChange={(e) => set("manufacturer", e.target.value)} placeholder="Caterpillar" style={inputStyle} /></Field>
                <Field label="Year"><input value={f.year} onChange={(e) => set("year", e.target.value.replace(/\D/g, "").slice(0, 4))} placeholder="2018" style={inputStyle} /></Field>
                <Field label="Hours / km"><input value={f.hours} onChange={(e) => set("hours", e.target.value)} placeholder="6,420" style={inputStyle} /></Field>
              </div>
              <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></Field>
              <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 }} />
              </Field>
            </div>
          </div>
        )}

        {/* STEP 3 */}
        {step === 3 && (
          <div>
            <StepHead title="Add photos & video" sub="Listings with video get up to 3× more bids. 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: "var(--ignite)", 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 ? "var(--ignite)" : "var(--border-s)"}`, background: f.hasVideo ? "rgba(249,115,22,0.06)" : "var(--surface)",
            }}>
              <span style={{ width: 44, height: 44, borderRadius: 10, background: f.hasVideo ? "var(--ignite)" : "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 */}
        {step === 4 && (
          <div>
            <StepHead title="Pricing & schedule" sub="Set your opening bid, optional reserve and auction length." />
            <div style={formCol}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="eb-form-2">
                <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></Field>
                <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></Field>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="eb-form-2">
                <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></Field>
                <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></Field>
              </div>
              <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={pill(f.duration === d)}>{d} days</button>
                  ))}
                </div>
              </Field>
              <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)" }}>5% seller fee</strong> only when your item sells. Listing is free.</span>
              </div>
            </div>
          </div>
        )}

        {/* STEP 5 */}
        {step === 5 && (
          <div>
            <StepHead title="Review & publish" sub="Check everything looks right. You can still edit after submitting." />
            <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] || SAMPLE_UPLOADS[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: "var(--ignite)" }}></i></span>}
                </div>
              </div>
              <div>
                <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 listing"}</h3>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 16 }}>{[f.category, f.year, f.condition].filter(Boolean).join(" · ")}</div>
                {[
                  ["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 || "—"],
                ].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 buttons */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 28, paddingTop: 22, borderTop: "1px solid var(--border)" }}>
          <button onClick={() => (step === 1 ? onNav({ name: "auctions" }) : setStep(step - 1))} style={ghostBtn}>
            <i data-lucide="chevron-left" style={{ width: 15, height: 15 }}></i> {step === 1 ? "Cancel" : "Back"}
          </button>
          {step < 5 ? (
            <button onClick={() => canNext && setStep(step + 1)} disabled={!canNext} style={{ ...primaryBtn, 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 }); setDone(true); }} style={{ ...primaryBtn, background: "#22C55E" }}>
              <i data-lucide="rocket" style={{ width: 15, height: 15 }}></i> Submit auction
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function StepHead({ 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>
  );
}

// ════════════════════════════════════════════════════
// ACCOUNT DASHBOARD
// ════════════════════════════════════════════════════
function AccountScreen({ store, user, tab, onNav, onWatch, watchlist, wallet, onAddCard, onReleasePreauth, onReleaseEscrow, profile, onSaveProfile, onVerify, vendor, onRateBuyer, onAdvanceSale, onRespondReview }) {
  const [active, setActive] = useS2(tab || "bids");
  useE2(() => { if (tab) setActive(tab); }, [tab]);

  const myBids = store.auctions.filter((a) => store.userBids[a.id]);
  const mySelling = store.auctions.filter((a) => user && a.seller.name === user.name);
  const watched = store.auctions.filter((a) => watchlist.includes(a.id));

  const TABS = [
    { v: "bids", l: "My Bids", ico: "gavel", n: myBids.length },
    { v: "selling", l: "Selling", ico: "tag", n: mySelling.length },
    { v: "sales", l: "Sales", ico: "shopping-bag", n: (vendor && vendor.sales ? vendor.sales.length : 0) },
    { v: "reviews", l: "Reviews", ico: "star", n: (vendor && vendor.reviewsReceived ? vendor.reviewsReceived.length : 0) },
    { v: "watchlist", l: "Watchlist", ico: "heart", n: watched.length },
    { v: "payments", l: "Payments", ico: "wallet", n: (wallet && wallet.escrow ? wallet.escrow.length : 0) },
    { v: "profile", l: "Profile", ico: "user", n: null },
  ];

  return (
    <div style={{ maxWidth: 1200, margin: "0 auto", padding: "30px 24px 50px" }}>
      {/* Profile head */}
      <div style={{ display: "flex", alignItems: "center", gap: 18, marginBottom: 28 }}>
        <span style={{ width: 64, height: 64, borderRadius: 14, background: "linear-gradient(135deg,#2563EB,#1D4ED8)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 26, fontWeight: 800, color: "#fff", fontFamily: "var(--ff-display)" }}>
          {(user?.name || user?.email || "U")[0].toUpperCase()}
        </span>
        <div style={{ flex: 1 }}>
          <h1 style={{ fontFamily: "var(--ff-display)", fontSize: 30, fontWeight: 900, color: "var(--text)", textTransform: "uppercase", margin: 0, lineHeight: 1 }}>{user?.name || "My account"}</h1>
          <div style={{ fontSize: 13, color: "var(--text-3)", marginTop: 5 }}>{user?.email} · Member since 2026</div>
        </div>
        <button onClick={() => onNav({ name: "sell" })} style={primaryBtn}><i data-lucide="plus" style={{ width: 15, height: 15 }}></i> Sell equipment</button>
      </div>

      {/* Stat tiles */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 26 }} className="eb-stat-grid">
        {[
          ["Active bids", myBids.filter((a) => a.status === "live").length, "gavel", "var(--ignite)"],
          ["Winning", myBids.filter((a) => store.userBids[a.id]?.winning).length, "trophy", "#22C55E"],
          ["Listings", mySelling.length, "tag", "var(--cobalt)"],
          ["Watching", watched.length, "heart", "#F59E0B"],
        ].map(([l, n, ico, col]) => (
          <div key={l} style={{ background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 12, padding: "16px 18px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".07em", textTransform: "uppercase", color: "var(--text-3)" }}>{l}</span>
              <i data-lucide={ico} style={{ width: 16, height: 16, color: col }}></i>
            </div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 28, fontWeight: 700, color: "var(--text)", marginTop: 8 }}>{n}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", gap: 4, borderBottom: "1px solid var(--border)", marginBottom: 24 }}>
        {TABS.map((t) => (
          <button key={t.v} onClick={() => { setActive(t.v); onNav({ name: "account", tab: t.v }, true); }} style={{
            display: "inline-flex", alignItems: "center", gap: 7, padding: "11px 16px", fontSize: 13, fontWeight: 700,
            color: active === t.v ? "var(--text)" : "var(--text-3)",
            borderBottom: `2px solid ${active === t.v ? "var(--ignite)" : "transparent"}`, marginBottom: -1,
          }}>
            <i data-lucide={t.ico} style={{ width: 15, height: 15 }}></i> {t.l}
            {t.n != null && <span style={{ fontSize: 11, fontFamily: "var(--ff-mono)", opacity: 0.7 }}>{t.n}</span>}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {active === "bids" && (
        myBids.length === 0 ? <Empty ico="gavel" title="No bids yet" sub="When you bid on equipment, it shows up here." cta="Browse auctions" onCta={() => onNav({ name: "auctions" })} /> :
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {myBids.map((a) => {
            const ub = store.userBids[a.id];
            return (
              <BidRow key={a.id} auction={a} userBid={ub} onOpen={() => onNav({ name: "detail", id: a.id })} onPay={() => onNav({ name: "checkout", id: a.id, mode: "won" })} />
            );
          })}
        </div>
      )}

      {active === "selling" && (
        mySelling.length === 0 ? <Empty ico="tag" title="Nothing listed yet" sub="Sell a machine by auction or on the marketplace — reach verified buyers either way." cta="Sell equipment" onCta={() => onNav({ name: "sell" })} /> :
        <div className="eb-card-grid">
          {mySelling.map((a) => {
            const sibling = mySelling.find((x) => x.groupId && x.groupId === a.groupId && x.channel !== a.channel);
            const note = sibling ? (sibling.channel === "auction" ? "Also at auction" : "Also on marketplace") : null;
            return a.channel === "marketplace"
              ? <MarketplaceCard key={a.id} listing={a} onOpen={(id) => onNav({ name: "detail", id })} note={note} />
              : <AuctionCard key={a.id} auction={a} onOpen={(id) => onNav({ name: "detail", id })} watched={watchlist.includes(a.id)} onWatch={onWatch} note={note} />;
          })}
        </div>
      )}

      {active === "watchlist" && (
        watched.length === 0 ? <Empty ico="heart" title="Your watchlist is empty" sub="Tap the heart on any auction to track it here." cta="Browse auctions" onCta={() => onNav({ name: "auctions" })} /> :
        <div className="eb-card-grid">
          {watched.map((a) => <AuctionCard key={a.id} auction={a} onOpen={(id) => onNav({ name: "detail", id })} watched={true} onWatch={onWatch} />)}
        </div>
      )}

      {active === "payments" && (
        <PaymentsTab wallet={wallet} store={store} onAddCard={onAddCard} onRelease={onReleaseEscrow} onReleasePreauth={onReleasePreauth} onNav={onNav} />
      )}

      {active === "profile" && (
        <AccountManagement user={user} profile={profile} onSave={onSaveProfile} onVerify={onVerify} onNav={onNav} />
      )}

      {active === "sales" && (
        <SalesTab vendor={vendor || {}} onNav={onNav} onRateBuyer={onRateBuyer} onAdvance={onAdvanceSale} />
      )}

      {active === "reviews" && (
        <ReviewsTab vendor={vendor || {}} profile={profile} onRespond={onRespondReview} />
      )}
    </div>
  );
}

function BidRow({ auction, userBid, onOpen, onPay }) {
  const winning = userBid.winning;
  const isLive = auction.status === "live";
  const isEnded = auction.status === "ended" || auction.status === "settled";
  const won = isEnded && userBid.won;
  const paid = userBid.paid;
  return (
    <div onClick={onOpen} style={{ display: "flex", alignItems: "center", gap: 16, padding: 12, background: "var(--card-bg)", border: `1px solid ${won && !paid ? "rgba(34,197,94,0.4)" : "var(--border)"}`, borderRadius: 12, cursor: "pointer" }}>
      <EquipImage src={auction.images[0]} alt="" style={{ width: 88, height: 66, borderRadius: 8, objectFit: "cover", flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 4 }}>
          <StatusBadge status={auction.status} />
          {isLive && (
            <span style={{ fontSize: 11, fontWeight: 700, padding: "2px 8px", borderRadius: 4, background: winning ? "rgba(34,197,94,0.14)" : "rgba(239,68,68,0.12)", color: winning ? "#22C55E" : "#F87171" }}>
              {winning ? "Winning" : "Outbid"}
            </span>
          )}
          {won && (
            <span style={{ fontSize: 11, fontWeight: 700, padding: "2px 8px", borderRadius: 4, background: paid ? "rgba(34,197,94,0.14)" : "rgba(249,115,22,0.14)", color: paid ? "#22C55E" : "var(--ignite)" }}>
              {paid ? "Paid · in escrow" : "You won"}
            </span>
          )}
        </div>
        <div style={{ fontSize: 15, fontWeight: 700, color: "var(--text)", fontFamily: "var(--ff-display)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{auction.title}</div>
        <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 3 }}>Your bid {eur(userBid.amount)}{userBid.max ? ` · max ${eur(userBid.max)}` : ""}</div>
      </div>
      <div style={{ textAlign: "right", flexShrink: 0 }}>
        {won && !paid ? (
          <button onClick={(e) => { e.stopPropagation(); onPay(); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "#22C55E", color: "#fff", borderRadius: 6, padding: "9px 16px", fontSize: 13, fontWeight: 700 }}>
            <i data-lucide="lock" style={{ width: 14, height: 14 }}></i> Pay now
          </button>
        ) : (
          <>
            <div style={{ fontSize: 9.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".07em" }}>{won ? "Winning bid" : "Current bid"}</div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 19, fontWeight: 700, color: "var(--ignite)" }}>{eur(auction.currentBid ?? auction.startingPrice)}</div>
            {isLive && <div style={{ marginTop: 3 }}><CompactClock endsAt={auction.endsAt} /></div>}
          </>
        )}
      </div>
      <i data-lucide="chevron-right" style={{ width: 18, height: 18, color: "var(--text-3)" }}></i>
    </div>
  );
}

function Empty({ ico, title, sub, cta, onCta }) {
  return (
    <div style={{ textAlign: "center", padding: "70px 0" }}>
      <span style={{ width: 56, height: 56, borderRadius: 14, background: "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }}>
        <i data-lucide={ico} style={{ width: 24, height: 24, color: "var(--text-3)" }}></i>
      </span>
      <h3 style={{ fontFamily: "var(--ff-display)", fontSize: 21, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", margin: "0 0 6px" }}>{title}</h3>
      <p style={{ fontSize: 13.5, color: "var(--text-3)", marginBottom: 18 }}>{sub}</p>
      <button onClick={onCta} style={primaryBtn}>{cta}</button>
    </div>
  );
}

// ── shared auth styles ──────────────────────────────
const authCard = { background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, padding: "30px 26px", width: "100%", boxShadow: "0 12px 40px rgba(0,0,0,0.4)" };
const authTitle = { fontFamily: "var(--ff-display)", fontSize: 27, fontWeight: 800, color: "var(--text)", textAlign: "center", textTransform: "uppercase", letterSpacing: "-0.01em", margin: "0 0 4px" };
const authLede = { fontSize: 13, color: "var(--text-3)", textAlign: "center", marginBottom: 22, lineHeight: 1.5 };
const errBox = { display: "flex", alignItems: "center", gap: 9, background: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.25)", borderRadius: 6, padding: "10px 13px", marginBottom: 16, fontSize: 12.5, color: "#F87171" };
const segWrap = { display: "flex", background: "var(--bg)", border: "1px solid var(--border-s)", borderRadius: 7, padding: 3, marginBottom: 20 };
const seg = (on) => ({ flex: 1, padding: "8px 0", fontSize: 12.5, fontWeight: 700, borderRadius: 5, background: on ? "var(--surface-2)" : "transparent", color: on ? "var(--text)" : "var(--text-3)", cursor: "pointer" });
const formCol = { display: "flex", flexDirection: "column", gap: 15 };
const igniteBtn = { display: "flex", alignItems: "center", justifyContent: "center", gap: 8, width: "100%", padding: "12px", background: "var(--ignite)", color: "#fff", fontSize: 14, fontWeight: 700, letterSpacing: ".03em", textTransform: "uppercase", borderRadius: 6, cursor: "pointer", border: "none" };
const eyeBtn = { position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)", display: "flex" };
const linkBtn = { color: "var(--cobalt)", fontWeight: 700, fontSize: "inherit", background: "none", border: "none", cursor: "pointer", padding: 0 };
const socialBtn = { display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "10px", background: "var(--bg)", color: "var(--text)", fontSize: 13, fontWeight: 600, border: "1px solid var(--border-s)", borderRadius: 6, cursor: "pointer" };
const pill = (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)" });

Object.assign(window, { SignInScreen, SignUpScreen, ForgotScreen, SellScreen, AccountScreen, Empty });
