/* ─────────────────────────────────────────────────────
   Equipment Balkans — Vendor (seller) experience
   Sales / orders · rate the buyer · respond to reviews (two-way)
───────────────────────────────────────────────────── */
const { useState: useVen } = React;

const SALE_STATUS = {
  awaiting_payment: { label: "Awaiting payment", color: "#F59E0B", icon: "clock" },
  in_escrow: { label: "Paid · in escrow", color: "#2563EB", icon: "lock" },
  awaiting_handover: { label: "Arrange handover", color: "#F97316", icon: "truck" },
  completed: { label: "Completed", color: "#22C55E", icon: "check-circle-2" },
};

// ── Star picker ─────────────────────────────────────
function StarPick({ value, onChange, size = 22 }) {
  const [hover, setHover] = useVen(0);
  return (
    <span style={{ display: "inline-flex", gap: 3 }}>
      {[1, 2, 3, 4, 5].map((i) => (
        <button key={i} type="button" onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(0)} onClick={() => onChange(i)} style={{ lineHeight: 0, padding: 0 }}>
          <i data-lucide="star" style={{ width: size, height: size, color: "#F59E0B", fill: i <= (hover || value) ? "#F59E0B" : "none" }}></i>
        </button>
      ))}
    </span>
  );
}

// ── Rate-the-buyer modal ────────────────────────────
function RateBuyerModal({ sale, onClose, onSubmit }) {
  const [stars, setStars] = useVen(5);
  const [comm, setComm] = useVen(5);
  const [pay, setPay] = useVen(5);
  const [handover, setHandover] = useVen(5);
  const [text, setText] = useVen("");
  const [reco, setReco] = useVen(true);

  return (
    <div onClick={onClose} style={venOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...venModal, maxWidth: 460 }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 13, padding: "22px 22px 0" }}>
          <span style={{ width: 42, height: 42, borderRadius: 11, background: "rgba(245,158,11,0.14)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <i data-lucide="star" style={{ width: 20, height: 20, color: "#F59E0B" }}></i>
          </span>
          <div style={{ flex: 1 }}>
            <h2 style={venTitle}>Rate this buyer</h2>
            <p style={{ fontSize: 12.5, color: "var(--text-3)", marginTop: 4 }}>{sale.buyer} · {sale.item}</p>
          </div>
          <button onClick={onClose} style={venClose}><i data-lucide="x" style={{ width: 17, height: 17 }}></i></button>
        </div>
        <div style={{ padding: "16px 22px 22px" }}>
          <div style={{ textAlign: "center", marginBottom: 16 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--text-3)", marginBottom: 8 }}>Overall experience</div>
            <StarPick value={stars} onChange={setStars} size={28} />
          </div>
          {[["Communication", comm, setComm], ["Payment promptness", pay, setPay], ["Smooth handover", handover, setHandover]].map(([l, v, set]) => (
            <div key={l} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid var(--border)" }}>
              <span style={{ fontSize: 13, color: "var(--text-2)" }}>{l}</span>
              <StarPick value={v} onChange={set} size={17} />
            </div>
          ))}
          <label style={{ ...fieldLabel, marginTop: 16, display: "block" }}>Comment</label>
          <textarea value={text} onChange={(e) => setText(e.target.value)} rows={3} placeholder="How was dealing with this buyer? Prompt payment, easy handover…" style={{ ...inputStyle, marginTop: 6, resize: "vertical", lineHeight: 1.5 }} />
          <button onClick={() => setReco(!reco)} style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 12, fontSize: 12.5, color: "var(--text-2)", fontWeight: 600 }}>
            <span style={{ width: 18, height: 18, borderRadius: 5, border: `1px solid ${reco ? "#22C55E" : "var(--border-s)"}`, background: reco ? "#22C55E" : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>{reco && <i data-lucide="check" style={{ width: 12, height: 12, color: "#fff" }}></i>}</span>
            I'd happily deal with this buyer again
          </button>
          <button onClick={() => onSubmit(sale, { stars, axes: { comm, pay, handover }, text, reco })} style={{ ...primaryBtn, width: "100%", justifyContent: "center", marginTop: 18, background: "#F59E0B" }}>
            <i data-lucide="send" style={{ width: 15, height: 15 }}></i> Submit rating
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Respond-to-review modal ─────────────────────────
function RespondModal({ review, onClose, onSubmit }) {
  const [text, setText] = useVen("");
  return (
    <div onClick={onClose} style={venOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...venModal, maxWidth: 460 }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 13, padding: "22px 22px 0" }}>
          <span style={{ width: 42, height: 42, borderRadius: 11, background: "rgba(37,99,235,0.14)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <i data-lucide="reply" style={{ width: 20, height: 20, color: "var(--cobalt)" }}></i>
          </span>
          <div style={{ flex: 1 }}>
            <h2 style={venTitle}>Respond to review</h2>
            <p style={{ fontSize: 12.5, color: "var(--text-3)", marginTop: 4 }}>Your reply is public, under {review.by}'s review.</p>
          </div>
          <button onClick={onClose} style={venClose}><i data-lucide="x" style={{ width: 17, height: 17 }}></i></button>
        </div>
        <div style={{ padding: "16px 22px 22px" }}>
          <div style={{ background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 9, padding: "12px 14px", marginBottom: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5 }}>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text)" }}>{review.by}</span>
              <Stars value={review.stars} size={12} />
            </div>
            <p style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.5, margin: 0 }}>{review.text}</p>
          </div>
          <label style={{ ...fieldLabel, display: "block" }}>Your response</label>
          <textarea value={text} onChange={(e) => setText(e.target.value)} rows={4} placeholder="Thank the buyer, address any concerns professionally…" style={{ ...inputStyle, marginTop: 6, resize: "vertical", lineHeight: 1.5 }} />
          <button onClick={() => text.trim() && onSubmit(review, text.trim())} style={{ ...primaryBtn, width: "100%", justifyContent: "center", marginTop: 16, background: "var(--cobalt)" }}>
            <i data-lucide="reply" style={{ width: 15, height: 15 }}></i> Post response
          </button>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════
// SALES TAB (seller orders)
// ════════════════════════════════════════════════════
function SalesTab({ vendor, onNav, onRateBuyer, onAdvance, toast }) {
  const [rating, setRating] = useVen(null);
  const sales = vendor.sales || [];
  const earnings = sales.filter((s) => s.status === "completed" || s.status === "in_escrow").reduce((t, s) => t + s.amount, 0);

  if (sales.length === 0) {
    return <Empty ico="shopping-bag" title="No sales yet" sub="When a buyer wins your auction or buys a listing, the order appears here." cta="Sell equipment" onCta={() => onNav({ name: "sell" })} />;
  }

  return (
    <div>
      {/* summary */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 22 }} className="eb-stat-grid">
        {[
          ["Orders", sales.length, "shopping-bag", "var(--cobalt)"],
          ["In escrow", sales.filter((s) => s.status === "in_escrow").length, "lock", "#2563EB"],
          ["To action", sales.filter((s) => s.status === "awaiting_handover" || s.status === "awaiting_payment").length, "bell", "var(--ignite)"],
          ["Net earnings", eur(Math.round(earnings * 0.95)), "wallet", "#22C55E"],
        ].map(([l, v, ico, col]) => (
          <div key={l} style={{ background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 12, padding: "15px 16px" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".07em", textTransform: "uppercase", color: "var(--text-3)" }}>{l}</span>
              <i data-lucide={ico} style={{ width: 15, height: 15, color: col }}></i>
            </div>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 21, fontWeight: 700, color: "var(--text)", marginTop: 7 }}>{v}</div>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {sales.map((s) => {
          const cfg = SALE_STATUS[s.status] || SALE_STATUS.completed;
          const next = s.status === "awaiting_payment" ? null : s.status === "in_escrow" ? "awaiting_handover" : s.status === "awaiting_handover" ? "completed" : null;
          const nextLabel = s.status === "in_escrow" ? "Mark dispatched" : s.status === "awaiting_handover" ? "Confirm handover" : null;
          return (
            <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 16, padding: 14, background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 12, flexWrap: "wrap" }}>
              <EquipImage src={s.img} alt="" style={{ width: 80, height: 60, borderRadius: 8, objectFit: "cover", flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 160 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 700, color: cfg.color, background: cfg.color + "1f", padding: "3px 9px", borderRadius: 4 }}>
                    <i data-lucide={cfg.icon} style={{ width: 12, height: 12 }}></i>{cfg.label}
                  </span>
                  <span style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em" }}>{s.channel}</span>
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--text)", fontFamily: "var(--ff-display)" }}>{s.item}</div>
                <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2, display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><i data-lucide="user" style={{ width: 12, height: 12 }}></i>{s.buyer}</span>
                  <span>·</span><span>{s.date}</span>
                </div>
              </div>
              <div style={{ textAlign: "right", minWidth: 90 }}>
                <div style={{ fontSize: 9.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".06em" }}>Sale price</div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 18, fontWeight: 700, color: "var(--ignite)" }}>{eur(s.amount)}</div>
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                <button onClick={() => onNav({ name: "account", tab: "reviews" })} style={{ ...ghostBtn, fontSize: 12, padding: "8px 12px" }}><i data-lucide="message-square" style={{ width: 14, height: 14 }}></i> Message</button>
                {next && nextLabel && <button onClick={() => onAdvance(s.id, next)} style={{ ...primaryBtn, fontSize: 12, padding: "8px 13px", background: cfg.color }}><i data-lucide="arrow-right" style={{ width: 14, height: 14 }}></i> {nextLabel}</button>}
                {s.status === "completed" && (s.ratedBuyer ? (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 700, color: "#22C55E", padding: "8px 12px" }}><i data-lucide="check" style={{ width: 14, height: 14 }}></i> Buyer rated</span>
                ) : (
                  <button onClick={() => setRating(s)} style={{ ...primaryBtn, fontSize: 12, padding: "8px 13px", background: "#F59E0B" }}><i data-lucide="star" style={{ width: 14, height: 14 }}></i> Rate buyer</button>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {rating && <RateBuyerModal sale={rating} onClose={() => setRating(null)} onSubmit={(sale, data) => { onRateBuyer(sale, data); setRating(null); }} />}
    </div>
  );
}

// ════════════════════════════════════════════════════
// REVIEWS TAB (received w/ respond + given to buyers)
// ════════════════════════════════════════════════════
function ReviewsTab({ vendor, profile, onRespond }) {
  const [sub, setSub] = useVen("received");
  const [responding, setResponding] = useVen(null);
  const received = vendor.reviewsReceived || [];
  const given = vendor.reviewsGiven || [];

  return (
    <div>
      <div style={{ display: "inline-flex", gap: 4, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 9, padding: 4, marginBottom: 20 }}>
        {[["received", "About me", received.length], ["given", "By me", given.length]].map(([v, l, n]) => (
          <button key={v} onClick={() => setSub(v)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 15px", borderRadius: 6, fontSize: 13, fontWeight: 700, color: sub === v ? "#fff" : "var(--text-2)", background: sub === v ? "var(--ignite)" : "transparent" }}>
            {l} <span style={{ fontSize: 11, fontFamily: "var(--ff-mono)", opacity: 0.7 }}>{n}</span>
          </button>
        ))}
      </div>

      {sub === "received" && (
        received.length === 0 ? <Empty ico="message-square-quote" title="No reviews yet" sub="Buyer reviews of you appear here — you can reply to each one." /> :
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {received.map((r) => (
            <div key={r.id} style={{ background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 12, padding: "16px 18px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 7 }}>
                <span style={{ width: 8, height: 8, borderRadius: "50%", background: r.stars >= 4 ? "#22C55E" : r.stars >= 3 ? "#F59E0B" : "#EF4444" }}></span>
                <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text)" }}>{r.by}</span>
                <Stars value={r.stars} size={13} />
                <span style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--text-3)" }}>{r.date}</span>
              </div>
              <p style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.55, margin: "0 0 4px" }}>{r.text}</p>
              {r.lot && <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--text-3)", marginBottom: 4 }}><i data-lucide="badge-check" style={{ width: 12, height: 12, color: "#22C55E" }}></i> Verified transaction · {r.lot}</div>}
              {r.response ? (
                <div style={{ marginTop: 10, marginLeft: 14, paddingLeft: 14, borderLeft: "2px solid var(--ignite)" }}>
                  <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ignite)", marginBottom: 3, display: "flex", alignItems: "center", gap: 5 }}><i data-lucide="reply" style={{ width: 12, height: 12 }}></i> Your response</div>
                  <p style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.5, margin: 0 }}>{r.response}</p>
                </div>
              ) : (
                <button onClick={() => setResponding(r)} style={{ ...ghostBtn, fontSize: 12, padding: "7px 13px", marginTop: 8 }}><i data-lucide="reply" style={{ width: 13, height: 13 }}></i> Respond</button>
              )}
            </div>
          ))}
        </div>
      )}

      {sub === "given" && (
        given.length === 0 ? <Empty ico="star" title="You haven't rated any buyers yet" sub="After a completed sale, rate the buyer from the Sales tab." /> :
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {given.map((r) => (
            <div key={r.id} style={{ background: "var(--card-bg)", border: "1px solid var(--border)", borderRadius: 12, padding: "16px 18px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 7 }}>
                <i data-lucide="user" style={{ width: 15, height: 15, color: "var(--text-3)" }}></i>
                <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text)" }}>{r.buyer}</span>
                <Stars value={r.stars} size={13} />
                {r.reco && <span style={{ fontSize: 10.5, fontWeight: 700, color: "#22C55E", background: "rgba(34,197,94,0.12)", padding: "2px 8px", borderRadius: 4 }}>Would deal again</span>}
                <span style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--text-3)" }}>{r.date}</span>
              </div>
              <p style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.55, margin: 0 }}>{r.text || <span style={{ color: "var(--text-3)" }}>No comment</span>}</p>
              {r.lot && <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--text-3)", marginTop: 5 }}><i data-lucide="package" style={{ width: 12, height: 12 }}></i> {r.lot}</div>}
            </div>
          ))}
        </div>
      )}

      {responding && <RespondModal review={responding} onClose={() => setResponding(null)} onSubmit={(rev, txt) => { onRespond(rev, txt); setResponding(null); }} />}
    </div>
  );
}

const venOverlay = { position: "fixed", inset: 0, zIndex: 160, background: "rgba(8,12,22,0.62)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 };
const venModal = { width: "100%", background: "var(--surface)", border: "1px solid var(--border-s)", borderRadius: 16, boxShadow: "0 24px 60px rgba(0,0,0,0.5)", maxHeight: "92vh", overflowY: "auto" };
const venTitle = { fontFamily: "var(--ff-display)", fontSize: 20, fontWeight: 800, color: "var(--text)", textTransform: "uppercase", margin: 0 };
const venClose = { width: 30, height: 30, borderRadius: 7, color: "var(--text-3)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 };

Object.assign(window, { SalesTab, ReviewsTab, SALE_STATUS });
