/* mSamex Card — screens 06–09: Cards list, Card detail, Designs showcase, Order card */
const { Icon, MeshMark, CardArt, Spark, Pill, Chip, Tgl, Bar, Sect, TxRow, eur, money, signed } = window.CardKit;
const D2 = window.CARD_DATA;
const finishOf = (id) => D2.finishes.find((f) => f.id === id);
const CUR_SYM = { EUR: "€", USD: "$", AED: "AED " };

/* ============ 06 · Cards list ============ */
function ScrCards({ app }) {
  const { t, go } = app;
  const [f, setF] = React.useState("all");
  const rows = D2.cards.filter((c) => f === "all" || (f === "physical" ? c.physical : !c.physical));
  return (
    <div className="scr">
      <SH app={app} title={t("cards")} backTo="home"
        right={<button className="icbtn" onClick={() => go("order")} aria-label="Order"><Icon name="plus" size={17} /></button>} />
      <div className="mute" style={{ fontSize: 12.5, padding: "0 2px 14px" }}>
        3 {t("cards").toLowerCase()} · 1 {t("physical")} · AED / USD / EUR
      </div>
      <div className="chiprow" style={{ marginBottom: 18 }}>
        {[["all", t("all")], ["physical", t("physical")], ["virtual", t("virtual")]].map(([id, l]) => (
          <Chip key={id} on={f === id} onClick={() => setF(id)}>{l}</Chip>
        ))}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
        {rows.map((c) => {
          const fin = finishOf(c.finish);
          return (
            <button key={c.id} style={{ textAlign: "start" }} onClick={() => go("carddetail")}>
              <CardArt finish={c.finish} w={350} last4={c.last4} exp={c.exp} cur={c.cur}
                virtual={!c.physical} frozen={c.frozen} sheen={app.sheen} />
              <span style={{ display: "flex", alignItems: "center", gap: 8, margin: "12px 2px 0" }}>
                <span style={{ fontSize: 15, fontWeight: 600 }}>{fin.name}</span>
                {!c.physical && <Pill tone="dim">{t("virtual")}</Pill>}
                {c.frozen && <Pill tone="coral">{t("frozen")}</Pill>}
                <span className="mono mute" style={{ fontSize: 11.5, marginInlineStart: "auto" }}>{c.cur} · •• {c.last4} · {c.exp}</span>
              </span>
              <span style={{ display: "block", margin: "10px 2px 0" }}>
                <span style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, marginBottom: 6 }}>
                  <span className="mono">{money(c.spent, CUR_SYM[c.cur])} <span className="mute">{t("spentOf")} {money(c.limit, CUR_SYM[c.cur], 0)}</span></span>
                  <span className="mono mute">{Math.round((c.spent / c.limit) * 100)}%</span>
                </span>
                <Bar v={c.spent} max={c.limit} h={4} tone={c.frozen ? "snow" : "mint"} />
              </span>
            </button>
          );
        })}
      </div>

      <button onClick={() => go("order")} style={{
        width: "100%", height: 92, borderRadius: 18, border: "1.5px dashed var(--m3-line)",
        display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
        color: "var(--m3-snow-mute)", fontSize: 14, fontWeight: 500, marginTop: 22 }}>
        <Icon name="plus" size={18} /> {t("orderNew")}
      </button>
      <button className="lrow" style={{ justifyContent: "center", gap: 7, color: "var(--m3-mint)", fontSize: 13, fontWeight: 500, padding: "16px 0 4px" }}
        onClick={() => go("designs")}>
        {t("seeDesigns")} <Icon name="chev" size={14} />
      </button>
    </div>
  );
}

/* ============ 07 · Card detail ============ */
function ScrCardDetail({ app }) {
  const { t, go } = app;
  const c = D2.cards[0];
  const [frozen, setFrozen] = React.useState(false);
  const [wallets, setWallets] = React.useState({ apple: true, google: false });
  const [ctrl, setCtrl] = React.useState({ online: true, tap: true, atm: true, foreign: false });
  const cats = [
    { name: "Food & Drink", spent: 424.60, cap: 600 },
    { name: "Travel", spent: 889.00, cap: 1200 },
    { name: "Subscriptions", spent: 63.99, cap: 100 },
  ];
  const mine = D2.txs.filter((x) => x.card === "4417").slice(0, 4);
  const ctrlRows = [["online", t("onlinePay")], ["tap", t("contactless")], ["atm", t("atm")], ["foreign", t("foreign")]];
  return (
    <div className="scr">
      <SH app={app} title="Graphite" backTo="cards"
        right={<button className="icbtn" aria-label="More"><Icon name="dots" size={17} /></button>} />
      <div style={{ display: "flex", justifyContent: "center" }}>
        <CardArt finish="graphite" w={350} last4={c.last4} exp={c.exp} cur="EUR" frozen={frozen} sheen={app.sheen} />
      </div>

      <div className="qa-row" style={{ marginTop: 20 }}>
        <button className="qa" onClick={() => { setFrozen(!frozen); app.toast(frozen ? t("unfreeze") + " · Graphite" : t("freeze") + " · Graphite"); }}>
          <span className="qa-ic" style={frozen ? { background: "var(--m3-mint)", color: "var(--m3-ink)", border: "none" } : null}>
            <Icon name="snow" size={20} /></span>
          {frozen ? t("unfreeze") : t("freeze")}
        </button>
        <button className="qa"><span className="qa-ic"><Icon name="eye" size={20} /></span>{t("details")}</button>
        <button className="qa" onClick={() => app.toast(t("share") + " · •• " + c.last4)}><span className="qa-ic"><Icon name="share" size={20} /></span>{t("share")}</button>
        <button className="qa" onClick={() => go("order")}><span className="qa-ic"><Icon name="repeat" size={20} /></span>{t("replace")}</button>
      </div>

      <Sect title={t("mobileWallet")} />
      <div className="card-blk" style={{ padding: "4px 16px" }}>
        {[["apple", "Apple Pay", "A PAY"], ["google", "Google Pay", "G PAY"]].map(([k, name, glyph]) => (
          <div className="wrow" key={k}>
            <span className="wg mono">{glyph}</span>
            <span style={{ flex: 1 }}>
              <span style={{ fontSize: 14, fontWeight: 500, display: "block" }}>{name}</span>
              <span className="mute" style={{ fontSize: 11.5 }}>
                {wallets[k] ? t("added") + " · Graphite •• " + c.last4 : "—"}
              </span>
            </span>
            <button className={"wbtn" + (wallets[k] ? " rm" : "")}
              onClick={() => { setWallets({ ...wallets, [k]: !wallets[k] }); app.toast(name + " · " + (wallets[k] ? t("remove") : t("added"))); }}>
              {wallets[k] ? t("remove") : t("addBtn")}
            </button>
          </div>
        ))}
        <div className="mute" style={{ fontSize: 10.5, lineHeight: 1.5, padding: "10px 0 12px", borderTop: "1px solid var(--m3-line-soft)" }}>
          {t("walletNote")}
        </div>
      </div>

      <Sect title={t("spendingMonth")} />
      <div className="card-blk">
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 10 }}>
          <span className="mono" style={{ fontSize: 22, fontWeight: 600 }}>{eur(c.spent)}</span>
          <span className="mute" style={{ fontSize: 12 }}>{t("spentOf")} {eur(c.limit, 0)} {t("limit")}</span>
        </div>
        <Bar v={c.spent} max={c.limit} h={5} />
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontSize: 11.5 }} className="mute mono">
          <span>{Math.round((c.spent / c.limit) * 100)}% {t("used")}</span>
          <span>{eur(c.limit - c.spent)} {t("remaining")}</span>
        </div>
      </div>

      <Sect title={t("controls")} />
      <div className="card-blk" style={{ padding: "4px 16px" }}>
        {ctrlRows.map(([k, label]) => (
          <div className="kv" key={k}>
            <span style={{ fontSize: 14, fontWeight: 500 }}>{label}</span>
            <Tgl on={ctrl[k]} onChange={(v) => setCtrl({ ...ctrl, [k]: v })} />
          </div>
        ))}
      </div>

      <Sect title={t("catLimits")} action={t("edit")} />
      <div className="card-blk" style={{ display: "flex", flexDirection: "column", gap: 13 }}>
        {cats.map((x) => (
          <div key={x.name}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 6 }}>
              <span style={{ fontWeight: 500 }}>{x.name}</span>
              <span className="mono mute">{eur(x.spent)} / {eur(x.cap, 0)}</span>
            </div>
            <Bar v={x.spent} max={x.cap} h={4} tone={x.spent / x.cap > 0.72 ? "warn" : "mint"} />
          </div>
        ))}
      </div>

      <Sect title={t("recentTx")} action={t("seeAll")} onAction={() => go("activity")} />
      <div className="list card-blk" style={{ padding: "2px 16px", marginBottom: 6 }}>
        {mine.map((tx) => <TxRow key={tx.id} tx={tx} onClick={() => go("tx")} />)}
      </div>
    </div>
  );
}

/* ============ 08 · Card designs showcase ============ */
function ScrDesigns({ app }) {
  const { t, go } = app;
  return (
    <div className="scr">
      <SH app={app} title={t("designsTitle")} backTo="cards" />
      <h1 style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.03em", margin: "6px 2px 10px", lineHeight: 1.15 }}>
        {t("designsTitle")}.
      </h1>
      <p className="mute" style={{ fontSize: 13.5, lineHeight: 1.6, margin: "0 2px 26px" }}>{t("designsIntro")}</p>

      <div style={{ display: "flex", flexDirection: "column", gap: 34 }}>
        {D2.finishes.map((f, i) => (
          <div key={f.id}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10, margin: "0 2px 10px" }}>
              <span className="mono" style={{ fontSize: 11, color: "var(--m3-mint)" }}>0{i + 1}</span>
              <span style={{ fontSize: 17, fontWeight: 700, letterSpacing: "-0.01em" }}>{f.name}</span>
              <Pill tone={f.id === "void" ? "ink" : "dim"}>{f.tierName}</Pill>
            </div>
            <CardArt finish={f.id} w={350} sheen={app.sheen} virtual={!!f.virtual}
              last4={["3359", "8802", "5518", "4417", "0042", "7731"][i]} />
            <div style={{ display: "flex", gap: 12, alignItems: "flex-start", margin: "12px 2px 0" }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, lineHeight: 1.55 }}>{f.desc}</div>
                <div className="mono mute" style={{ fontSize: 10, letterSpacing: "0.08em", marginTop: 6, textTransform: "uppercase" }}>{f.material}</div>
              </div>
              <button className="wbtn" onClick={() => go("order")}>{t("order")}</button>
            </div>
          </div>
        ))}
      </div>
      <div style={{ height: 10 }}></div>
    </div>
  );
}

/* ============ 09 · Order card ============ */
function ScrOrder({ app }) {
  const { t, go } = app;
  const [fin, setFin] = React.useState("graphite");
  const [tier, setTier] = React.useState("aurum");
  const [cur, setCur] = React.useState("EUR");
  const [vEmail, setVEmail] = React.useState("");
  const [onList, setOnList] = React.useState(() => !!localStorage.getItem("msx-void-waitlist"));
  const fees = { pulse: "€0", sterling: "€0", graphite: "€29", aurum: "€0", void: "—", paper: "€0" };
  const isPhysical = fin === "graphite" || fin === "void";
  return (
    <div className="scr">
      <SH app={app} title={t("orderCard")} backTo="cards" />
      <div style={{ display: "flex", justifyContent: "center", marginBottom: 16 }}>
        <CardArt finish={fin} w={330} sheen={app.sheen} virtual={!isPhysical} cur={cur} last4="0000" exp="07/31" />
      </div>
      <div className="chiprow">
        {D2.finishes.map((f) => (
          <Chip key={f.id} on={fin === f.id} onClick={() => setFin(f.id)}>{f.name}</Chip>
        ))}
      </div>
      <div className="chiprow" style={{ marginTop: 10 }}>
        {["EUR", "USD", "AED"].map((cc) => (
          <Chip key={cc} on={cur === cc} onClick={() => setCur(cc)}><span className="mono">{cc}</span></Chip>
        ))}
        <span className="mute" style={{ fontSize: 11, alignSelf: "center", whiteSpace: "nowrap" }}>· hold one in each</span>
      </div>

      <Sect title={t("tier")} />
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {D2.tiers.map((p) => (
          <button key={p.id} className={"plan" + (tier === p.id ? " on" : "")} onClick={() => setTier(p.id)}>
            <span className="radio"></span>
            <span style={{ flex: 1 }}>
              <span style={{ display: "flex", justifyContent: "space-between", fontSize: 14.5, fontWeight: 600 }}>
                {p.name}<span className="mono" style={{ color: tier === p.id ? "var(--m3-mint)" : "var(--m3-mute)", fontSize: 13 }}>{p.fee}{p.fee.startsWith("€") ? t("perMonth") : ""}</span>
              </span>
              <span className="mute" style={{ display: "block", fontSize: 11, marginTop: 3 }}>{p.perks}</span>
            </span>
          </button>
        ))}
      </div>

      {fin === "void" ? (<>
        <Sect title={t("voidWait")} />
        <div className="card-blk">
          <div className="mute" style={{ fontSize: 12.5, lineHeight: 1.6, marginBottom: 14 }}>{t("voidWaitSub")}</div>
          {onList ? (
            <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--m3-mint)", fontSize: 14, fontWeight: 600 }}>
              <Icon name="check" size={17} /> {t("onList")} · @kertu
            </div>
          ) : (<>
            <div className="searchbar" style={{ marginBottom: 10 }}>
              <Icon name="contact" size={15} style={{ opacity: 0.4 }} />
              <input type="email" value={vEmail} onChange={(e) => setVEmail(e.target.value)} placeholder={t("emailPh")} />
              <span className="mono mute" style={{ fontSize: 11 }}>@kertu</span>
            </div>
            <button className="btn btn-sm" onClick={() => {
              if(!vEmail.includes("@")) { app.toast(t("emailPh")); return; }
              localStorage.setItem("msx-void-waitlist", JSON.stringify({ email: vEmail, at: Date.now() }));
              setOnList(true); app.toast(t("waitOk"));
            }}>{t("requestInvite")}</button>
          </>)}
        </div>
      </>) : (<>
      <Sect title={t("shipping")} />
      <div className="card-blk" style={{ padding: "4px 16px" }}>
        {isPhysical && <div className="kv"><span className="kk">{t("address")}</span><span className="vv">Pikk 12-4, 10123 Tallinn</span></div>}
        <div className="kv"><span className="kk">Currency</span><span className="vv mono">{cur}</span></div>
        <div className="kv"><span className="kk">{t("shipping")}</span><span className="vv">{isPhysical ? t("delivery") : "Instant · issued in-app"}</span></div>
        <div className="kv"><span className="kk">{t("issuance")}</span><span className="vv mono" style={{ color: "var(--m3-mint)" }}>{fees[fin]}</span></div>
      </div>

      <button className="btn" style={{ margin: "18px 0 10px" }}
        onClick={() => app.toast(t("confirmOrder") + " · " + finishOf(fin).name)}>
        {t("confirmOrder")}
      </button>
      <div className="mute" style={{ fontSize: 11, textAlign: "center", paddingBottom: 6 }}>{t("cancelNote")}</div>
      </>)}
    </div>
  );
}

Object.assign(window, { ScrCards, ScrCardDetail, ScrDesigns, ScrOrder });
