/* global React, Btn, Progress, WingDivider, CarSilhouette, useGame, fmt, useState, useEffect, scf, scfIdem */

const SUBS = { S: "S-CLASS", A: "A-CLASS", B: "B-CLASS" };
const GLOW = { S: "rgba(124,77,255,.32)", A: "rgba(91,140,255,.30)", B: "rgba(70,214,230,.26)" };
const fmtMat = (m) => {
  if (m == null || m === "") return "未集齊";
  if (Array.isArray(m)) return m.length ? m.map(x => (x.have != null ? x.have : 0) + "/" + (x.need != null ? x.need : 0)).join("　") : "未集齊";
  if (typeof m === "object") return (m.have != null ? m.have : 0) + "/" + (m.need != null ? m.need : 0);
  return String(m);
};

function CarScreen({ onExchangeS }) {
  const g = useGame();
  const [loading, setLoading] = useState(true);
  const [levels, setLevels] = useState([]);
  const [collected, setCollected] = useState(0);
  const [lvl, setLvl] = useState("S");
  const [busy, setBusy] = useState(false);

  const load = async () => {
    setLoading(true);
    try { const d = await scf("car/progress"); setLevels(d.levels || []); setCollected(d.collectedCount || 0); }
    catch (e) { g.showToast("✗ " + e.message); }
    setLoading(false);
  };
  useEffect(() => { load(); }, []);

  if (loading) return React.createElement("div", { style: { padding: "40px 0", textAlign: "center", color: "var(--txt-mute)" } }, "載入中…");

  const levObj = levels.find(l => l.level === lvl) || levels[0];
  const car = (levObj && (levObj.cars || []).find(c => c.refit)) || (levObj && (levObj.cars || [])[0]);
  const sub = SUBS[lvl] || lvl;
  const glow = GLOW[lvl] || GLOW.S;

  const exchange = async () => {
    if (!car || !car.canExchange) { g.showToast("材料不足，繼續送禮集齊藍圖與鑰匙"); return; }
    if (busy) return; setBusy(true);
    try {
      await scf("car/exchange", { carId: car.carId, idemKey: scfIdem() });
      if (lvl === "S" && onExchangeS) onExchangeS();
      else g.showToast("兌換成功！座駕已發放至背包");
      load();
    } catch (e) { g.showToast("✗ " + e.message); } finally { setBusy(false); }
  };
  const sendHint = () => g.showToast("集卡掉落由真實「送禮事件」觸發；本地無送禮入口，此處展示真實後端進度");

  return React.createElement("div", { className: "fade-in", style: { padding: "4px 0 8px" } },
    React.createElement("div", { style: { display: "flex", gap: 8, padding: "10px 14px 0" } },
      levels.map(L => React.createElement("button", {
        key: L.level, onClick: () => setLvl(L.level), className: "subtab" + (L.level === lvl ? " on" : ""),
        style: { flex: 1, flexDirection: "column", display: "flex", alignItems: "center", gap: 1, padding: "7px 0" }
      },
        React.createElement("span", { style: { fontSize: 16, fontWeight: 900 } }, L.level + " 級"),
        React.createElement("span", { className: "disp upper", style: { fontSize: 8, opacity: .8 } }, SUBS[L.level] || L.level)))),

    React.createElement("div", { className: "hero" },
      React.createElement("div", { className: "glow-red", style: { background: `radial-gradient(60% 50% at 50% 40%, ${glow}, transparent 70%)` } }),
      React.createElement("div", { style: { position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", paddingBottom: 30, gap: 6 } },
        React.createElement("div", { className: "art-ph car-float", style: { width: 200, height: 96, border: "none", background: "none" } },
          React.createElement(CarSilhouette, { w: 188, color: "#ff6a52" })),
        React.createElement("div", { style: { fontSize: 11, color: "var(--txt-dim)", letterSpacing: ".1em", textShadow: "0 1px 4px rgba(0,0,0,.85)" } }, "座駕美術 · " + sub)),
      React.createElement("div", { className: "halo" }),
      React.createElement("div", { className: "ring" }),
      React.createElement("div", { style: { position: "absolute", left: 0, right: 0, bottom: 10, textAlign: "center" } },
        React.createElement("div", { style: { fontWeight: 900, fontSize: 18 }, className: "gold-text" }, car ? car.name : "—"),
        car && React.createElement("span", { className: "tag tag-dark", style: { marginTop: 4 } }, "限時 " + (car.duration || 0) + " 天"))),

    React.createElement("div", { className: "panel", style: { margin: "0 14px", padding: "14px 14px 16px" } },
      React.createElement("div", { style: { fontSize: 12.5, color: "var(--txt-dim)", lineHeight: 2 } },
        "📐 車藍圖：", React.createElement("b", { className: "gold-text" }, fmtMat(car && car.blueprints)),
        React.createElement("br"),
        "🔑 車鑰匙：", React.createElement("b", { className: "gold-text" }, fmtMat(car && car.keys))),
      React.createElement("div", { className: "hr-gold", style: { margin: "14px 0 12px" } }),
      React.createElement("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between" } },
        React.createElement("div", { style: { fontSize: 13, color: "var(--txt-dim)", whiteSpace: "nowrap" } }, "已收集 ",
          React.createElement("b", { className: "gold-text", style: { fontSize: 18, fontFamily: "var(--font-disp)" } }, collected), " 輛"),
        React.createElement(Btn, { kind: car && car.canExchange ? "red" : "gold", size: "md", disabled: !car || !car.canExchange || busy, onClick: exchange, style: { minWidth: 120 } }, car && car.canExchange ? "立即兌換" : "材料不足"))),

    React.createElement("div", { style: { display: "flex", gap: 8, padding: "12px 14px 0" } },
      React.createElement(Btn, { kind: "ghost", size: "sm", full: true, onClick: sendHint }, "🎁 送禮獲取藍圖"),
      React.createElement(Btn, { kind: "ghost", size: "sm", full: true, onClick: sendHint }, "🎁 送禮獲取鑰匙")),
    React.createElement("div", { style: { fontSize: 11, color: "var(--txt-mute)", lineHeight: 1.7, padding: "10px 16px 0", textWrap: "pretty" } },
      "房間內送出指定禮物有概率掉落車藍圖／車鑰匙（真實由送禮事件 MQ 觸發）；集齊即可兌換限時座駕。S 級可進一步定制。")
  );
}

Object.assign(window, { CarScreen });
