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

const SCENE_NAMES = ["霓虹都會", "賽道之夜", "海岸公路", "星軌之境", "熔岩工廠"];
const SCENE_BASE = ["rgba(124,77,255,.30)", "rgba(91,140,255,.28)", "rgba(70,214,230,.24)", "rgba(224,53,156,.24)", "rgba(245,166,35,.22)"];
const PAINT_HEX = ["#e22320", "#e6c065", "#7a4dd0", "#1fb5a8", "#2f6bd8", "#ff7ed4"];
const PAINT_NAMES = ["焰金紅", "鎏金", "暗夜紫", "極地青", "深海藍", "霓粉"];

function RefitScreen({ onConfirm }) {
  const g = useGame();
  const [loading, setLoading] = useState(true);
  const [carId, setCarId] = useState(null);
  const [combos, setCombos] = useState([]);
  const [scene, setScene] = useState(null);
  const [paint, setPaint] = useState(null);
  const [busy, setBusy] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const prog = await scf("car/progress");
      const s = (prog.levels || []).find(l => l.level === "S");
      const car = ((s && s.cars) || []).find(c => c.refit) || ((s && s.cars) || [])[0];
      if (!car) { setCombos([]); setLoading(false); return; }
      setCarId(car.carId);
      const d = await scf("refit/options?carId=" + car.carId);
      const cs = d.combos || [];
      setCombos(cs);
      if (cs.length) { setScene(cs[0].sceneId); setPaint(cs[0].paintId); }
    } 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)" } }, "載入中…");
  if (!combos.length) return React.createElement("div", { style: { padding: "40px 16px", textAlign: "center", color: "var(--txt-mute)" } }, "暫無可定制座駕");

  const sceneIds = [...new Set(combos.map(c => c.sceneId))];
  const paintIds = [...new Set(combos.map(c => c.paintId))];
  const sIdx = Math.max(0, sceneIds.indexOf(scene));
  const pIdx = Math.max(0, paintIds.indexOf(paint));
  const combo = combos.find(c => c.sceneId === scene && c.paintId === paint);
  const base = SCENE_BASE[sIdx] || SCENE_BASE[0];
  const hex = PAINT_HEX[pIdx] || "#ff6a52";
  const sName = SCENE_NAMES[sIdx] || ("場景" + (sIdx + 1));
  const pName = PAINT_NAMES[pIdx] || ("顏色" + (pIdx + 1));

  const buy = async () => {
    if (!combo) { g.showToast("該組合不存在"); return; }
    if (busy) return; setBusy(true);
    try { await scf("refit/buy", { carId, sceneId: scene, paintId: paint, idemKey: scfIdem() }); if (onConfirm) onConfirm(sName + " · " + pName); g.showToast("定制款座駕已發放至背包！"); await g.refreshWallet(); }
    catch (e) { g.showToast("✗ " + e.message); } finally { setBusy(false); }
  };

  return React.createElement("div", { className: "fade-in", style: { padding: "6px 0 8px" } },
    React.createElement("div", { className: "panel-head", style: { paddingTop: 8 } },
      React.createElement(WingDivider, { w: 60 }),
      React.createElement("span", { className: "ph-title gold-text", style: { fontSize: 19 } }, "座駕定制"),
      React.createElement(WingDivider, { w: 60 })),
    React.createElement("div", { className: "disp upper", style: { textAlign: "center", fontSize: 9, letterSpacing: ".3em", color: "var(--txt-mute)", marginTop: -4 } }, "S-CLASS REFIT"),

    React.createElement("div", { className: "hero", style: { height: 220 } },
      React.createElement("div", { className: "glow-red", style: { background: `radial-gradient(60% 50% at 50% 42%, ${base}, transparent 72%)` } }),
      React.createElement("div", { style: { position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", paddingBottom: 26, gap: 8 } },
        React.createElement("div", { className: "car-float" }, React.createElement(CarSilhouette, { w: 196, color: hex })),
        React.createElement("div", { style: { fontSize: 11, color: "var(--txt-dim)", letterSpacing: ".1em", textShadow: "0 1px 4px rgba(0,0,0,.85)" } }, "座駕美術 · " + sName + " · " + pName)),
      React.createElement("div", { className: "halo" }),
      React.createElement("div", { className: "ring" })),

    React.createElement("div", { style: { padding: "16px 16px 0" } },
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6, marginBottom: 9 } },
        React.createElement("span", { style: { color: "var(--red-hi)" } }, "◆"),
        React.createElement("span", { style: { fontWeight: 700, fontSize: 14 } }, "場景")),
      React.createElement("div", { style: { display: "flex", gap: 8, flexWrap: "wrap" } },
        sceneIds.map((id, i) => React.createElement("div", { key: id, className: "scene-chip" + (id === scene ? " on" : ""), onClick: () => setScene(id) }, SCENE_NAMES[i] || ("場景" + (i + 1)))))),

    React.createElement("div", { style: { padding: "16px 16px 0" } },
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 6, marginBottom: 9 } },
        React.createElement("span", { style: { color: "var(--red-hi)" } }, "◆"),
        React.createElement("span", { style: { fontWeight: 700, fontSize: 14 } }, "噴漆顏色")),
      React.createElement("div", { style: { display: "flex", gap: 12, flexWrap: "wrap" } },
        paintIds.map((id, i) => React.createElement("div", { key: id, className: "swatch" + (id === paint ? " on" : ""), onClick: () => setPaint(id), style: { background: PAINT_HEX[i] || "#888" } })))),

    React.createElement("div", { className: "panel", style: { margin: "18px 14px 0", padding: 14, display: "flex", alignItems: "center", justifyContent: "space-between" } },
      React.createElement("div", null,
        React.createElement("div", { style: { fontSize: 11, color: "var(--txt-mute)" } }, "本組合需"),
        React.createElement("div", { className: "disp", style: { fontSize: 24, fontWeight: 700, color: "var(--gold-100)", display: "flex", alignItems: "center", gap: 6 } },
          React.createElement("span", { className: "coin", style: { fontSize: 18 } }), combo ? fmt(combo.coinCost) : "—")),
      React.createElement(Btn, { kind: combo ? "red" : "off", size: "lg", disabled: !combo || busy, onClick: buy }, "確認購買")),
    React.createElement("div", { style: { fontSize: 11, color: "var(--txt-mute)", lineHeight: 1.7, padding: "12px 16px 0", textWrap: "pretty" } },
      "S 級座駕定制（場景＋噴漆）；外形不隨定制改變，確認購買後發放定制款至背包。")
  );
}

Object.assign(window, { RefitScreen });
