// Crews & Jobs board — the craigslist layer. Visible to everyone.
// Seed posts + user board posts (rl-my-listings, kind === "board").

// Extra individual sellers for board posts
if (window.MP_SELLERS) {
  Object.assign(window.MP_SELLERS, {
    torres: { name: "Luis Torres", type: "Foreman", rating: 4.9, reviews: 41, verified: true, member: false, resp: "~30 min", grad: "linear-gradient(140deg,#4A3F30,#847562)" },
    diaz:   { name: "Ana Diaz",    type: "Office admin", rating: 5.0, reviews: 12, verified: true, member: false, resp: "~1 hr", grad: "linear-gradient(140deg,#2C4A3E,#6B8A66)" },
  });
}

const BOARD_SEED = [
  { id: "b1", postType: "crew",   chip: "Crew for hire", title: "4-man tear-off crew — available next week", detail: "Insured · 300 sq/day · own tools & truck", price: 280, unit: "/day per man", loc: "Mesa, AZ", dist: 6, seller: "cardenas", at: 1 },
  { id: "b2", postType: "job",    chip: "Job opening",   title: "Hiring: roofing estimator, full-time", detail: "2+ yrs · Xactimate a plus · trucks provided", price: 32, unit: "/hr", loc: "Chandler, AZ", dist: 8, seller: "ridgeline", at: 2 },
  { id: "b3", postType: "wanted", chip: "Wanted",        title: "Need 30 bundles Driftwood — this week", detail: "Owens Corning Duration preferred · will pick up", price: 0, unit: "", loc: "Gilbert, AZ", dist: 5, seller: "halcon", at: 3 },
  { id: "b4", postType: "work",   chip: "For hire",      title: "Foreman, 8 yrs — open to work", detail: "Bilingual · OSHA 30 · tear-off to final inspection", price: 38, unit: "/hr", loc: "Phoenix, AZ", dist: 14, seller: "torres", at: 4 },
  { id: "b5", postType: "work",   chip: "For hire",      title: "Roofing office admin — invoicing & permits", detail: "5 yrs with a $6M shop · QuickBooks, AccuLynx", price: 26, unit: "/hr", loc: "Tempe, AZ", dist: 11, seller: "diaz", at: 5 },
  { id: "b6", postType: "crew",   chip: "Crew for hire", title: "Metal roof specialists — 2-man crew", detail: "Standing seam · flashing details · portfolio on request", price: 340, unit: "/day per man", loc: "Scottsdale, AZ", dist: 18, seller: "summit", at: 6 },
];

const BOARD_FILTERS = ["All", "Crew for hire", "Job opening", "For hire", "Wanted"];
const BOARD_CHIP_STYLE = {
  "Crew for hire": { background: "var(--green-soft)", color: "var(--green)", borderColor: "#c5d9c9" },
  "Job opening":   { background: "var(--gold-bg)", color: "var(--gold-dark)", borderColor: "var(--gold-soft)" },
  "For hire":      { background: "#EAF0FA", color: "var(--blue)", borderColor: "#c9d8ee" },
  "Wanted":        { background: "#FBE3DF", color: "var(--red)", borderColor: "#f0c8c2" },
};

function boardPosts() {
  let mine = [];
  try {
    mine = (window.RLS ? window.RLS.myListings() : []).filter(l => l.kind === "board" && !l.sold);
  } catch (e) {}
  return mine.concat(BOARD_SEED);
}

function BoardRow({ post, onReply, index }) {
  const seller = window.MP_SELLERS[post.seller];
  const SellerAvatar = window.SellerAvatar;
  const isMine = post.seller === "you";
  return (
    <div className="mpx-row mpx-enter" style={{ animationDelay: (index * 45) + "ms", alignItems: "center" }}>
      <SellerAvatar seller={seller} size={44} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
          <span className="chip" style={BOARD_CHIP_STYLE[post.chip] || null}>{post.chip}</span>
          {isMine && <span className="chip gold">Your post</span>}
          <span style={{ fontSize: 12, color: "var(--text-3)" }}>{post.loc} · {post.dist} mi</span>
        </div>
        <div style={{ fontSize: 16, fontWeight: 600, marginTop: 5 }}>{post.title}</div>
        <div style={{ fontSize: 13.5, color: "var(--text-2)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{post.detail}</div>
        <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4 }}>
          {seller.name}{seller.verified ? " · ✓ verified" : ""} · responds {seller.resp}
        </div>
      </div>
      <div style={{ textAlign: "right", flexShrink: 0, display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
        {post.price > 0 && (
          <div style={{ fontWeight: 700, fontSize: 18 }}>${post.price}<span style={{ fontSize: 12, color: "var(--text-3)", fontWeight: 400 }}>{post.unit}</span></div>
        )}
        {!isMine && <button className="btn gold sm" onClick={() => onReply(post.seller)}>Reply</button>}
      </div>
    </div>
  );
}

function MarketBoard({ onReply, onPost }) {
  const [filter, setFilter] = React.useState("All");
  const posts = boardPosts().filter(p => filter === "All" || p.chip === filter);
  return (
    <div data-screen-label="Crews & jobs board">
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center", marginBottom: 16 }}>
        {BOARD_FILTERS.map(f => (
          <button key={f} className={"filter-pill" + (filter === f ? " active" : "")} onClick={() => setFilter(f)}>{f}</button>
        ))}
        <button className="btn primary sm" style={{ marginLeft: "auto" }} onClick={onPost}>+ Post to the board</button>
      </div>
      <div key={filter} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {posts.map((p, i) => <BoardRow key={p.id} post={p} onReply={onReply} index={i} />)}
      </div>
      {posts.length === 0 && (
        <div style={{ textAlign: "center", padding: "60px 0", color: "var(--text-3)", fontSize: 13.5 }}>
          Nothing here yet — be the first to post.
        </div>
      )}
    </div>
  );
}

window.MarketBoard = MarketBoard;
