/* ============================================================
   Carzello — Lot (VDP) + Live bidding room
   ============================================================ */

const NOT_INSPECTED = [
  "Frame thickness gauge (visual only)",
  "Extended road test (> 15 mi)",
  "Cold-start in sub-zero conditions",
  "Underbody on lift",
];

const AREA_LABELS = { exterior: "Exterior", interior: "Interior", mechanical: "Mechanical", frame: "Frame", tires: "Tires" };

function GradeBar({ score }) {
  return (
    <div className="bar"><span style={{ width: `${(score / 5) * 100}%`, background: gradeColor(score) }} /></div>
  );
}

function Lot({ id }) {
  const lot = useLot(id);
  const s = useStore();
  const { t } = useT();
  const [tab, setTab] = useState("condition");
  const [photo, setPhoto] = useState(0);
  const [copied, setCopied] = useState(false);

  // recently viewed
  useEffect(() => {
    if (!lot) return;
    try {
      const ids = JSON.parse(localStorage.getItem("sayarah.recent") || "[]").filter(x => x !== lot.id);
      ids.unshift(lot.id);
      localStorage.setItem("sayarah.recent", JSON.stringify(ids.slice(0, 10)));
    } catch (e) {}
  }, [id]);

  if (!lot) return <Empty title="Lot not found" sub="This vehicle may have been removed." action={<button className="btn primary" onClick={() => navigate("/browse")}>Back to inventory</button>} />;

  function shareWhatsApp() {
    const msg = `${lot.year} ${lot.make} ${lot.model} ${lot.trim} · AutoGrade ${lot.autograde.toFixed(1)} · ${fmtUSD(lot.highBid)} — ${location.href}`;
    window.open("https://wa.me/?text=" + encodeURIComponent(msg), "_blank");
  }
  function copyLink() { try { navigator.clipboard.writeText(location.href); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch (e) {} }

  const mine = lot.highBidder === "you";
  const live = lot.status === "live";
  const titleKind = lot.title === "Clean" ? "green" : lot.title === "Branded" ? "amber" : "red";

  return (
    <div className="fadein">
      <div className="row gap-10" style={{ marginBottom: 14 }}>
        <button className="btn ghost sm" onClick={() => navigate("/browse")}><I.back width="14" height="14" /> {t("c.inventory")}</button>
        <span className="muted" style={{ fontSize: 12.5 }}>Lane {lot.lane} · Run {lot.run} · {lot.owned ? t("tag.owned") : `${t("tag.consigned")} · ${lot.seller}`}</span>
        <span className="spacer" />
        <button className="btn outline sm" onClick={shareWhatsApp}><I.phone width="13" height="13" /> WhatsApp</button>
        <button className="btn ghost sm" onClick={copyLink}>{copied ? "Copied ✓" : "Copy link"}</button>
        <WatchBtn id={lot.id} className="iconbtn" />
      </div>

      <div className="vdp-layout">
        {/* LEFT */}
        <div>
          <div className="row gap-12" style={{ marginBottom: 14, alignItems: "flex-start" }}>
            <AutoGrade score={lot.autograde} size="lg" />
            <div style={{ flex: 1 }}>
              <h1 className="h1" style={{ fontSize: 28 }}>{lot.year} {lot.make} {lot.model}</h1>
              <div className="muted" style={{ fontSize: 15 }}>{lot.trim} · {lot.body}</div>
              <div className="row gap-8 wrap" style={{ marginTop: 8 }}>
                <SaleLight lot={lot} />
                <Pill kind={titleKind}>{lot.title} title</Pill>
                {lot.structural && <Pill kind="red">Structural — grade capped</Pill>}
                <Pill><I.pin width="11" height="11" /> {lot.location}</Pill>
                <Pill>{lot.keys} {lot.keys === 1 ? "key" : "keys"}</Pill>
                <Pill>{lot.odometerCheck} miles</Pill>
              </div>
            </div>
          </div>

          {/* gallery */}
          <div className="gallery">
            <Photo className="main" src={lot.photoUrls && lot.photoUrls[photo]} hue={lot.id.charCodeAt(5) * 6 + photo * 12} label={PHOTO_CATS[photo % PHOTO_CATS.length]} count={`${photo + 1} / ${lot.photos}`} />
            <div className="thumbs">
              {Array.from({ length: Math.max(6, (lot.photoUrls || []).length) }).slice(0, 8).map((_, i) => (
                <Photo key={i} className={"photo " + (i === photo ? "on" : "")} src={lot.photoUrls && lot.photoUrls[i]} hue={lot.id.charCodeAt(5) * 6 + i * 12}
                  style={{ cursor: "pointer" }} {...clickable(() => setPhoto(i), `View photo ${i + 1}`)} aria-pressed={i === photo} />
              ))}
            </div>
          </div>

          {/* tabs */}
          <div className="vdp-tabs">
            {[["condition", "Condition report"], ["damage", "Damage", lot.damages.length], ["announce", "Announcements", lot.announcements.length], ["obd", "OBD scan", lot.obd.length], ["history", "History"], ["specs", "Specs"], ["docs", "Title & docs"]].map(([k, l, ct]) => (
              <button key={k} className={"vdp-tab " + (tab === k ? "on" : "")} onClick={() => setTab(k)}>{l}{ct ? <span className="ct">({ct})</span> : null}</button>
            ))}
          </div>

          {tab === "condition" && (
            <div className="col gap-16 fadein">
              <div className="card card-pad row gap-16" style={{ alignItems: "center" }}>
                <AutoGrade score={lot.autograde} size="lg" />
                <div>
                  <b style={{ fontSize: 16 }}>AutoGrade {lot.autograde.toFixed(1)} · {gradeLabel(lot.autograde)}</b>
                  <div className="muted" style={{ fontSize: 13 }}>Independent inspection across 5 areas, scored 0.0–5.0. Condition guaranteed to match this report.</div>
                </div>
              </div>
              <div className="cr-grid">
                {Object.keys(lot.grades).map(k => (
                  <div className="cr-cell" key={k}>
                    <div className="l">{AREA_LABELS[k]}</div>
                    <GradeBar score={lot.grades[k]} />
                    <div className="sc" style={{ color: gradeColor(lot.grades[k]) }}>{lot.grades[k].toFixed(1)}<span className="muted" style={{ fontSize: 12, fontWeight: 600 }}> / 5</span></div>
                    {lot.crNotes[k] && <div className="note">{lot.crNotes[k]}</div>}
                  </div>
                ))}
              </div>
              <div className="card card-pad">
                <div className="row gap-8" style={{ marginBottom: 6 }}><I.alert width="14" height="14" style={{ color: "var(--amber)" }} /><b style={{ fontSize: 13.5 }}>Not inspected · disclosed</b></div>
                <div className="cr-grid" style={{ gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))" }}>
                  {NOT_INSPECTED.map(n => <div key={n} className="muted" style={{ fontSize: 12.5 }}>◇ {n}</div>)}
                </div>
              </div>
            </div>
          )}

          {tab === "announce" && (
            <div className="card card-pad announce fadein">
              {lot.announcements.map((a, i) => (
                <div className="row" key={i}>
                  <span className={"ic " + (a.ok ? "ok" : "")}>{a.ok ? <I.check width="15" height="15" /> : <I.alert width="15" height="15" />}</span>
                  <div><b style={{ fontSize: 13.5 }}>{a.t}</b><div className="muted" style={{ fontSize: 13 }}>{a.text}</div></div>
                </div>
              ))}
            </div>
          )}

          {tab === "damage" && (
            <div className="fadein col gap-12">
              <div className="feedback warn"><I.alert width="14" height="14" /> {lot.damages.length} disclosed condition points. Each photographed; buyer is bound by these disclosures.</div>
              <div className="dmg-grid">
                {lot.damages.map((d, i) => (
                  <div className="dmg-cell" key={i}>
                    <Photo hue={i * 40 + 20} label={`Item ${i + 1}`} />
                    <div className="meta"><div className="loc">{d.loc}</div><div className="sev">{d.type} · {d.sev}</div></div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === "obd" && (
            <div className="card card-pad fadein">
              <div className="row" style={{ marginBottom: 6 }}><b style={{ fontSize: 13.5 }}>OBD-II diagnostic scan</b><span className="spacer" /><span className="muted" style={{ fontSize: 12 }}>Launch X431 · pre-sale</span></div>
              {lot.obd.map((c, i) => (
                <div className="obd-row" key={i}>
                  <span className="code" style={{ color: c.status === "pass" ? "var(--green)" : c.status === "warn" ? "var(--amber)" : "var(--red)" }}>{c.code}</span>
                  <span>{c.desc} <span className="muted">· {c.when}</span></span>
                  <Pill kind={c.status === "pass" ? "green" : "amber"}>{c.status.toUpperCase()}</Pill>
                </div>
              ))}
            </div>
          )}

          {tab === "history" && (
            <div className="card card-pad fadein">
              <div className="row" style={{ marginBottom: 10 }}><b style={{ fontSize: 13.5 }}>Vehicle history · VIN {lot.vin}</b><span className="spacer" /><Pill kind="amber">SAMPLE DATA</Pill><Pill kind="green"><I.check width="11" height="11" /> No open recalls</Pill></div>
              <dl className="kv" style={{ gridTemplateColumns: "auto 1fr" }}>
                <dt>Reported owners</dt><dd>{1 + (lot.vin.charCodeAt(3) % 3)}</dd>
                <dt>Reported accidents</dt><dd>{lot.damages.some(d => d.sev === "Major") ? "1 (repaired, disclosed above)" : lot.announcements.some(a => !a.ok && /repair|quarter|frame/i.test(a.text)) ? "1 minor (disclosed)" : "None reported"}</dd>
                <dt>Service records</dt><dd>{6 + (lot.vin.charCodeAt(5) % 9)} on file</dd>
                <dt>Last odometer reading</dt><dd>{fmtMiles(Math.max(0, lot.mileage - 900))} · ~3 months ago (consistent)</dd>
                <dt>Usage type</dt><dd>{lot.owned ? "Dealer stock" : (lot.seller.includes("Fleet") || lot.seller.includes("Leasing")) ? "Fleet / lease" : "Dealer consignment"}</dd>
                <dt>Title brands</dt><dd>{lot.title === "Clean" ? "None" : (lot.titleNote || lot.title)}</dd>
                <dt>Export record</dt><dd>Cleared for export · GCC + Central Asia</dd>
              </dl>
              <div className="muted" style={{ fontSize: 11, marginTop: 10 }}>Demo: illustrative history for evaluation only — not a compiled Carfax/AutoCheck/NMVTIS report. Production listings link the real report.</div>
            </div>
          )}

          {tab === "specs" && (
            <div className="card card-pad fadein">
              <dl className="kv" style={{ gridTemplateColumns: "auto 1fr auto 1fr" }}>
                <dt>VIN</dt><dd className="mono">{lot.vin}</dd>
                <dt>Lot</dt><dd>{lot.id}</dd>
                <dt>Mileage</dt><dd>{fmtMiles(lot.mileage)}</dd>
                <dt>Body</dt><dd>{lot.body}</dd>
                <dt>Transmission</dt><dd>{lot.transmission}</dd>
                <dt>Drivetrain</dt><dd>{lot.drivetrain}</dd>
                <dt>Fuel</dt><dd>{lot.fuel}</dd>
                <dt>Ext. color</dt><dd>{lot.colorExt}</dd>
                <dt>Int. color</dt><dd>{lot.colorInt}</dd>
                <dt>Seller</dt><dd>{lot.seller}</dd>
                <dt>Tires</dt><dd style={{ textAlign: "left" }}>{lot.crNotes.tires}</dd>
              </dl>
            </div>
          )}

          {tab === "docs" && (
            <div className="card card-pad fadein">
              <dl className="kv" style={{ gridTemplateColumns: "auto 1fr" }}>
                <dt>Title status</dt><dd>{lot.title}{lot.titleNote ? ` · ${lot.titleNote}` : " · in hand"}</dd>
                <dt>Lien holder</dt><dd>None</dd>
                <dt>Title delivery</dt><dd>Within 5 business days of payment</dd>
                <dt>Bill of sale</dt><dd>Generated at sale</dd>
                <dt>Odometer</dt><dd>{lot.odometerCheck} · {fmtMiles(lot.mileage)}</dd>
              </dl>
              <div style={{ marginTop: 14 }}>
                <div className="l" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--fg-3)", fontWeight: 700, marginBottom: 6 }}>Export eligibility by destination</div>
                {SHIP_DEST.map(d => {
                  const e = eligibleFor(lot, d.code);
                  return (
                    <div key={d.code} className="row gap-8" style={{ padding: "6px 0", borderTop: "1px solid var(--border)", fontSize: 12.5 }}>
                      <span style={{ minWidth: 170 }}>{d.label}</span>
                      {e.ok
                        ? e.warn
                          ? <Pill kind="amber"><I.alert width="10" height="10" /> Restricted</Pill>
                          : <Pill kind="green"><I.check width="10" height="10" /> Eligible</Pill>
                        : <Pill kind="red"><I.x width="10" height="10" /> Not eligible</Pill>}
                      <span className="muted" style={{ fontSize: 11.5 }}>{e.reason || e.warn || ""}</span>
                    </div>
                  );
                })}
                <div className="muted" style={{ fontSize: 10.5, marginTop: 6 }}>Simplified rules (age caps, title-brand bans). Confirm with the destination authority before bidding.</div>
              </div>
            </div>
          )}

          {/* similar vehicles */}
          {(() => {
            const sim = Object.values(s.lots).filter(L => !L.hidden && L.id !== lot.id && L.status !== "ended" && (L.make === lot.make || (L.body === lot.body && Math.abs(L.highBid - lot.highBid) < lot.highBid * 0.35))).slice(0, 3);
            if (!sim.length) return null;
            return (
              <div style={{ marginTop: 22 }}>
                <div className="section-h"><h2 className="h2" style={{ fontSize: 16 }}>Similar vehicles</h2></div>
                <div className="inv-grid">{sim.map(L => <ListingCard key={L.id} lot={L} />)}</div>
              </div>
            );
          })()}
        </div>

        {/* RIGHT — desktop panel */}
        <div className="vdp-aside-desktop"><BidPanel lot={lot} /></div>
      </div>

      {/* stacked bid panel on mobile */}
      <div className="mob-only" style={{ marginTop: 20 }}><BidPanel lot={lot} /></div>

      {/* sticky mobile bid bar */}
      <div className="mob-bidbar">
        <div className="price">{fmtUSD(lot.highBid)}<small>{mine ? t("bid.winning") : live ? `${t("bid.ends")} ${fmtRemaining(lot.endsAt - Date.now())}` : lot.status === "scheduled" ? `Opens ${fmtRemaining(lot.startsAt - Date.now())}` : t("c.ended")}</small></div>
        <span className="spacer" />
        {live && lot.saleType === "live" && <button className="btn outline" aria-label="Live room" onClick={() => navigate(`/live/${lot.id}`)}><I.bolt width="14" height="14" /></button>}
        <button className="btn primary" disabled={!live && lot.status !== "scheduled"} onClick={() => document.getElementById("bidpanel")?.scrollIntoView({ behavior: "smooth" })}>
          <I.gavel width="14" height="14" /> {live ? t("bid.place") : lot.status === "scheduled" ? "Pre-bid" : t("c.ended")}
        </button>
      </div>
    </div>
  );
}

/* ============================================================
   Live bidding room
   ============================================================ */
function LiveRoom({ id }) {
  const lot = useLot(id);
  const [flash, setFlash] = useState(false);
  const extRef = useRef(0);

  useEffect(() => {
    if (!lot) return;
    if (lot.extensions > extRef.current) {
      extRef.current = lot.extensions;
      setFlash(true);
      const t = setTimeout(() => setFlash(false), 2400);
      return () => clearTimeout(t);
    }
  }, [lot && lot.extensions]);

  if (!lot) return <Empty title="Lot not found" action={<button className="btn primary" onClick={() => navigate("/browse")}>Back</button>} />;

  const mine = lot.highBidder === "you";
  const live = lot.status === "live";
  const ms = lot.endsAt - Date.now();
  const lastId = lot.history[0]?.id;

  return (
    <div className="fadein">
      <div className="row gap-10" style={{ marginBottom: 14 }}>
        <button className="btn ghost sm" onClick={() => navigate(`/lot/${lot.id}`)}><I.back width="14" height="14" /> Lot details</button>
        <Pill kind="live" dot>LIVE BIDDING ROOM</Pill>
        <span className="spacer" />
        <Pill kind="amber">DEMO · competing bids are simulated</Pill>
      </div>

      <div className="liveroom">
        <div className="col gap-16">
          <div className="livehero">
            <Photo src={lot.photoUrls && lot.photoUrls[0]} hue={lot.id.charCodeAt(5) * 6} />
            <div className="topbar2">
              <Pill kind="solid-live" dot>LIVE</Pill>
              <span className="mono" style={{ fontSize: 12 }}>LOT {lot.id} · {lot.remote ? `${lot.bidCount || 0} bids` : `${lot.competitors.length + (mine ? 1 : 0)} bidders`}</span>
            </div>
            {flash && <div className="snipe-toast"><b style={{ fontSize: 18 }}>+2:00</b><div><div style={{ fontWeight: 800, fontSize: 13 }}>Anti-snipe extension</div><div style={{ fontSize: 11.5, opacity: .9 }}>Late bid added time</div></div></div>}
            <div className="bottom">
              <div><h2>{lot.year} {lot.make} {lot.model}</h2><div className="sub">{lot.trim} · {fmtMiles(lot.mileage)} · {lot.drivetrain} · AutoGrade {lot.autograde.toFixed(1)}</div></div>
              <div><div className="timer-xl" style={{ color: ms < 60000 ? "#ff6b5e" : "#fff" }}>{fmtRemaining(ms)}</div><div className="mono" style={{ fontSize: 11, textAlign: "right", opacity: .8 }}>{live ? "ENDS IN" : "AUCTION CLOSED"}</div></div>
            </div>
          </div>

          <div className="card card-pad">
            <div className="row gap-16" style={{ marginBottom: 14 }}>
              <div><div className="statline"><div><div className="l">Current bid · {lot.bidCount} bids</div><div className={"big-price tnum " + (mine ? "winning" : "")}>{fmtUSD(lot.highBid)}</div></div></div></div>
              <span className="spacer" />
              <div style={{ textAlign: "right" }}>
                {lot.reserve == null ? <Pill kind="green">No reserve</Pill> : <Pill kind={lot.reserveMet ? "green" : "amber"}>{lot.reserveMet ? "Reserve met" : "Reserve not met"}</Pill>}
                <div style={{ marginTop: 6 }}>{mine ? <Pill kind="green">You're winning</Pill> : lot.yourMax ? <Pill kind="amber">Outbid</Pill> : <Pill>Not bidding yet</Pill>}</div>
              </div>
            </div>
            <BidControls lot={lot} compact />
          </div>
        </div>

        {/* live feed */}
        <div className="feed">
          <div className="head"><Pill kind="live" dot>LIVE FEED</Pill><span style={{ marginLeft: 6 }}>Bid history</span><span className="spacer" /><span className="muted mono" style={{ fontSize: 11 }}>{lot.bidCount} bids</span></div>
          <div className="rows">
            {lot.history.length === 0 && <div className="muted" style={{ padding: 16, fontSize: 13 }}>No bids yet — be the first.</div>}
            {lot.history.map((b) => (
              <div key={b.id} className={"feedrow " + (b.you ? "you " : "") + (b.id === lastId ? "new" : "")}>
                <span className="who">{b.you ? "You" : b.bidder}{b.type === "buynow" ? " · Buy Now" : b.type === "proxy" ? " · proxy" : ""}</span>
                <span className="t">{timeAgo(b.ts)}</span>
                <span className="amt tnum">{fmtUSD(b.amount)}</span>
              </div>
            ))}
          </div>
          <div style={{ padding: "10px 14px", borderTop: "1px solid var(--border)", fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-3)" }}>
            <div className="row" style={{ justifyContent: "space-between" }}><span>HIGH BIDDER</span><span style={{ color: mine ? "var(--green)" : "var(--fg-2)" }}>{mine ? "YOU" : (lot.highBidder ? lot.history[0]?.bidder || "—" : "—")}</span></div>
            <div className="row" style={{ justifyContent: "space-between" }}><span>EXTENSIONS</span><span>{lot.extensions}</span></div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Lot, LiveRoom, NOT_INSPECTED });
