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

const ICO = { CAR: "🏎️", FRAME: "💍", BUBBLE: "💬" };

function WelfareScreen() {
  const g = useGame();
  const [loading, setLoading] = useState(true);
  const [isNewUser, setIsNewUser] = useState(false);
  const [accRecharge, setAccRecharge] = useState(0);
  const [tiers, setTiers] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [busy, setBusy] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const d = await scf("welfare/recharge");
      setIsNewUser(!!d.isNewUser); setAccRecharge(Number(d.accRecharge || 0)); setTiers(d.tiers || []);
    } catch (e) { g.showToast("✗ " + e.message); }
    try { const t = await scf("welfare/tasks"); setTasks((t && t.tasks) || []); } catch (e) { }
    setLoading(false);
  };
  useEffect(() => { load(); }, []);

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

  const focus = tiers.find(t => t.state === "CLAIMABLE") || tiers.find(t => t.state === "LOCKED") || tiers[0];
  const need = focus ? Number(focus.needCoin) : 10000;

  const claimRecharge = async (tier, choice) => {
    if (busy) return; setBusy(true);
    try { await scf("welfare/recharge/claim", { tier, choice, idemKey: scfIdem() }); g.showToast("已領取，發放至背包"); g.refreshWallet(); load(); }
    catch (e) { g.showToast("✗ " + e.message); } finally { setBusy(false); }
  };
  const claimTask = async (taskId) => {
    if (busy) return; setBusy(true);
    try { await scf("welfare/tasks/claim", { taskId, idemKey: scfIdem() }); g.showToast("任務獎勵已領取"); load(); }
    catch (e) { g.showToast("✗ " + e.message); } finally { setBusy(false); }
  };

  return React.createElement("div", { className: "fade-in", style: { padding: "12px 14px 8px" } },
    React.createElement("div", { className: "panel", style: { padding: "12px 12px 14px" } },
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 12 } },
        React.createElement("span", { className: "tag tag-gold", style: { fontSize: 14, fontWeight: 900, padding: "5px 11px" } }, "3 選 1"),
        React.createElement("span", { style: { fontSize: 13, color: "var(--txt-dim)" } }, "累計儲值達到 ",
          React.createElement("b", { className: "gold-text" }, fmt(need)), " 金幣")),
      focus
        ? React.createElement("div", { style: { display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 9 } },
          (focus.options || []).map(o => React.createElement("div", { key: o.choice, className: "rcard" },
            React.createElement("div", { className: "rcard-art" }, ICO[o.choice] || "🎁",
              React.createElement("span", { className: "rcard-tag tag tag-dark", style: { fontSize: 10 } }, (o.duration || 0) + " 天")),
            React.createElement("div", { className: "rcard-name" }, o.name),
            React.createElement(Btn, {
              kind: focus.state === "CLAIMABLE" ? "red" : (focus.state === "CLAIMED" ? "gold" : "off"), size: "sm", full: true,
              disabled: focus.state !== "CLAIMABLE" || busy,
              onClick: () => claimRecharge(focus.tier, o.choice), style: { marginTop: 6 }
            }, focus.state === "CLAIMED" ? "已領取" : "領取"))))
        : React.createElement("div", { style: { padding: "16px 0", textAlign: "center", color: "var(--txt-mute)" } }, "暫無可領檔位"),
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginTop: 13 } },
        React.createElement("span", { style: { fontSize: 12, color: "var(--txt-dim)", flex: "none" } }, "已儲 ", fmt(accRecharge)),
        React.createElement("div", { style: { flex: 1 } }, React.createElement(Progress, { value: accRecharge, max: need })),
        React.createElement(Btn, { kind: "gold", size: "sm", onClick: () => g.showToast("前往儲值中心") }, "儲值")),
      React.createElement("div", { style: { fontSize: 10.5, color: "var(--txt-mute)", marginTop: 9, textWrap: "pretty" } },
        "〈3選1〉僅限活動開始前從未儲值過的新用戶參與。" + (isNewUser ? "" : "（您目前不符合新用戶資格）"))),

    React.createElement("div", { style: { display: "flex", alignItems: "center", justifyContent: "center", gap: 10, margin: "18px 0 12px" } },
      React.createElement(WingDivider, { w: 80 }),
      React.createElement("span", { className: "gold-text", style: { fontWeight: 900, fontSize: 16, whiteSpace: "nowrap" } }, "全民任務"),
      React.createElement(WingDivider, { w: 80 })),
    React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 9 } },
      tasks.length ? tasks.map((t) => React.createElement("div", { key: t.taskId, className: "task" },
        React.createElement("div", { className: "task-ic" }, "🎁", t.duration ? React.createElement("span", { className: "ti-time" }, t.duration + "天") : null),
        React.createElement("div", { style: { flex: 1 } },
          React.createElement("div", { style: { fontSize: 13.5, fontWeight: 700 } }, t.name),
          React.createElement("div", { style: { fontSize: 11, color: "var(--txt-mute)", marginTop: 3 } }, "（已送出 " + t.progress + " / " + t.need + "）")),
        React.createElement(Btn, { kind: t.state === "CLAIMABLE" ? "gold" : "off", size: "sm", disabled: t.state !== "CLAIMABLE" || busy, onClick: () => claimTask(t.taskId) },
          t.state === "CLAIMED" ? "已領取" : t.state === "CLAIMABLE" ? "領取" : "進行中")))
        : React.createElement("div", { style: { padding: "16px 0", textAlign: "center", color: "var(--txt-mute)" } }, "暫無任務"))
  );
}

Object.assign(window, { WelfareScreen });
