/* mSamex Card — screens 14–17: Activity (+filter sheet), Transaction detail, Earn, Analytics */
const { Icon, Pill, Chip, Bar, Sect, Area, Bars, Donut, catColor, TxRow, eur, money, signed, fmtNum } = window.CardKit;
const D4 = window.CARD_DATA;

/* ============ 14 · Activity ============ */
function ScrActivity({ app }) {
  const { t, go } = app;
  const [type, setType] = React.useState("all");
  const [search, setSearch] = React.useState(false);
  const [q, setQ] = React.useState("");
  const [sheet, setSheet] = React.useState(false);
  const [preset, setPreset] = React.useState("7d");
  const [accs, setAccs] = React.useState(["EUR"]);
  const [cats, setCats] = React.useState([]);
  const [crd, setCrd] = React.useState([]);
  const flt = (arr, v) => arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v];
  const nFilters = (accs.length ? 1 : 0) + (cats.length ? 1 : 0) + (crd.length ? 1 : 0) + 1;

  const match = (x) =>
    (type === "all" || (type === "income" && x.in) || (type === "spending" && !x.in && !x.swap) ||
     (type === "transfers" && x.cat.startsWith("P2P")) || (type === "swaps" && x.swap)) &&
    (!q || x.m.toLowerCase().includes(q.toLowerCase()));
  const rows = D4.txs.filter(match);
  const days = [...new Set(rows.map((x) => x.day))];
  const dl = (kind) => app.toast(<>{kind === "pdf" ? "statement_jul-2026.pdf" : "activity_jul-2026.csv"}&nbsp;<span className="mono">{t("exported")}</span></>);

  return (
    <div className="scr" style={{ position: "relative" }}>
      <SH app={app} title={t("activity")} backTo="home"
        right={<button className="icbtn" onClick={() => setSearch(!search)} aria-label="Search"><Icon name={search ? "close" : "search"} size={16} /></button>} />
      {search && (
        <div className="searchbar" style={{ marginBottom: 14 }}>
          <Icon name="search" size={15} style={{ opacity: 0.4 }} />
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("search") + "…"} />
          {q && <button onClick={() => setQ("")}><Icon name="close" size={14} style={{ opacity: 0.5 }} /></button>}
        </div>
      )}

      <div className="card-blk">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <span className="k">{t("period")} · 1 – 5 Jul</span>
          <span className="mono up" style={{ fontSize: 15, fontWeight: 600 }}>+€2,986.36 <span className="mute" style={{ fontWeight: 400, fontSize: 11 }}>{t("net")}</span></span>
        </div>
        <div className="mono" style={{ display: "flex", gap: 16, fontSize: 11.5, margin: "6px 0 12px" }}>
          <span className="up">+€4,382.00 {t("in")}</span>
          <span className="mute">−€1,395.64 {t("out")}</span>
        </div>
        <Bars data={D4.analytics.months} h={44} active={6} />
        <div className="mono mute" style={{ display: "flex", justifyContent: "space-between", fontSize: 9, marginTop: 4 }}>
          {["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL"].map((m) => <span key={m}>{m}</span>)}
        </div>
      </div>

      <div style={{ display: "flex", gap: 8, margin: "12px 0" }}>
        <button className="chip" style={{ flex: 1, display: "flex", alignItems: "center", gap: 7, justifyContent: "center" }} onClick={() => setSheet(true)}>
          <Icon name="filter" size={14} /> 1 Jul → 5 Jul
          <span className="pill pill-mint mono" style={{ padding: "1px 7px" }}>{nFilters}</span>
        </button>
        <button className="chip" onClick={() => dl("pdf")} style={{ display: "flex", gap: 6, alignItems: "center" }}><Icon name="dl" size={14} /> PDF</button>
        <button className="chip" onClick={() => dl("csv")} style={{ display: "flex", gap: 6, alignItems: "center" }}><Icon name="dl" size={14} /> CSV</button>
      </div>

      <div className="chiprow">
        {[["all", t("all")], ["income", t("income")], ["spending", t("spending")], ["transfers", t("transfers")], ["swaps", t("swaps")]].map(([id, l]) => (
          <Chip key={id} on={type === id} onClick={() => setType(id)}>{l}</Chip>
        ))}
      </div>

      {rows.length === 0 ? (
        <div style={{ textAlign: "center", padding: "44px 0" }}>
          <div className="mute" style={{ fontSize: 13.5 }}>{t("noTx")}</div>
          <button style={{ color: "var(--m3-mint)", fontSize: 13, fontWeight: 600, marginTop: 10 }}
            onClick={() => { setType("all"); setQ(""); }}>{t("reset")}</button>
        </div>
      ) : days.map((d) => (
        <div key={d}>
          <div className="k" style={{ margin: "18px 2px 4px" }}>{d === "today" ? t("today") : d === "yesterday" ? "Yesterday" : d}</div>
          <div className="list">
            {rows.filter((x) => x.day === d).map((tx) => <TxRow key={tx.id} tx={tx} onClick={() => go("tx")} />)}
          </div>
        </div>
      ))}

      {sheet && (<>
        <div className="sheet-veil" onClick={() => setSheet(false)}></div>
        <FilterSheet app={app} close={() => setSheet(false)} n={rows.length}
          preset={preset} setPreset={setPreset} accs={accs} cats={cats} crd={crd}
          tglAcc={(v) => setAccs(flt(accs, v))} tglCat={(v) => setCats(flt(cats, v))} tglCrd={(v) => setCrd(flt(crd, v))}
          reset={() => { setAccs([]); setCats([]); setCrd([]); setPreset("7d"); }} />
      </>)}
    </div>
  );
}

function FilterSheet({ app, close, n, preset, setPreset, accs, cats, crd, tglAcc, tglCat, tglCrd, reset }) {
  const { t } = app;
  /* July 2026 — 1st falls on Wednesday */
  const cells = [29, 30, ...Array.from({ length: 31 }, (_, i) => i + 1), 1, 2];
  return (
    <div className="sheet">
      <div className="sheet-handle"></div>
      <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 14 }}>{t("filters")}</div>

      <div className="k" style={{ marginBottom: 8 }}>{t("presets")}</div>
      <div className="chiprow">
        {["7d", "30d", "3m", "YTD", t("custom")].map((p) => (
          <Chip key={p} on={preset === p} onClick={() => setPreset(p)}><span className="mono">{p}</span></Chip>
        ))}
      </div>

      <div style={{ display: "flex", gap: 10, margin: "14px 0" }}>
        {[[t("fromDate"), "1 Jul 2026"], [t("toDate"), "5 Jul 2026"]].map(([l, v]) => (
          <div key={l} className="card-blk" style={{ flex: 1, padding: "10px 13px", background: "var(--m3-elevated)" }}>
            <div className="k" style={{ fontSize: 9 }}>{l}</div>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600, marginTop: 3 }}>{v}</div>
          </div>
        ))}
      </div>

      <div className="cal">
        {["MO", "TU", "WE", "TH", "FR", "SA", "SU"].map((d) => <span className="dow" key={d}>{d}</span>)}
        {cells.map((d, i) => {
          const dim = i < 2 || i > 32;
          const edge = !dim && (d === 1 || d === 5);
          const inr = !dim && d > 1 && d < 5;
          return <span key={i} className={"cal-d" + (dim ? " dim" : "") + (edge ? " edge" : "") + (inr ? " inr" : "")}>{d}</span>;
        })}
      </div>

      <div className="k" style={{ margin: "16px 0 8px" }}>{t("accounts")}</div>
      <div className="chiprow">
        {["EUR", "USD", "GBP", "AED", "USDT", "USDC"].map((a) => (
          <Chip key={a} on={accs.includes(a)} onClick={() => tglAcc(a)}><span className="mono">{a}</span></Chip>
        ))}
      </div>
      <div className="k" style={{ margin: "14px 0 8px" }}>{t("categories")}</div>
      <div className="chiprow">
        {["Food & Drink", "Transport", "Groceries", "Travel", "Home", "Income"].map((c) => (
          <Chip key={c} on={cats.includes(c)} onClick={() => tglCat(c)}>{c}</Chip>
        ))}
      </div>
      <div className="k" style={{ margin: "14px 0 8px" }}>{t("cards")}</div>
      <div className="chiprow">
        {["Graphite ••4417", "Aurum ••8802", "Pulse ••3359"].map((c) => (
          <Chip key={c} on={crd.includes(c)} onClick={() => tglCrd(c)}><span className="mono">{c}</span></Chip>
        ))}
      </div>

      <div className="k" style={{ margin: "14px 0 8px" }}>{t("amount")}</div>
      <div style={{ display: "flex", gap: 10 }}>
        {[t("min"), t("max2")].map((l) => (
          <div key={l} className="searchbar" style={{ flex: 1, height: 42 }}>
            <span className="mute" style={{ fontSize: 12 }}>{l}</span>
            <input className="mono" placeholder="€0" style={{ textAlign: "end" }} />
          </div>
        ))}
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <button className="btn-ghost btn-sm" style={{ flex: 1 }} onClick={reset}>{t("resetAll")}</button>
        <button className="btn btn-sm" style={{ flex: 2 }} onClick={close}>{t("showResults")} ({n})</button>
      </div>
    </div>
  );
}

/* ============ 15 · Transaction detail ============ */
function ScrTx({ app }) {
  const { t, go } = app;
  const tx = D4.txs[0];
  const acts = [["dispute", t("dispute")], ["split", t("split")], ["repeat", t("recurring")],
    ["search", t("similar")], ["tag", t("editCat")], ["doc", t("addNote")]];
  return (
    <div className="scr">
      <SH app={app} title={t("txDetail")} backTo="activity"
        right={<button className="icbtn" aria-label="More"><Icon name="dots" size={17} /></button>} />
      <div style={{ textAlign: "center", padding: "4px 0 18px" }}>
        <span className="mavatar" style={{ width: 58, height: 58, fontSize: 17 }}>W</span>
        <div style={{ fontSize: 19, fontWeight: 700, marginTop: 10 }}>{tx.m}</div>
        <div className="mute" style={{ fontSize: 12.5, marginTop: 3 }}>{tx.cat} · {tx.city}</div>
        <div className="mono" style={{ fontSize: 36, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 12 }}>−€24.60</div>
        <div className="mono mute" style={{ fontSize: 11.5, marginTop: 4 }}>≈ $26.75 {t("atTime")}</div>
      </div>

      <div className="mapsnip">
        <svg viewBox="0 0 350 130" preserveAspectRatio="none" aria-hidden="true">
          <path d="M0 40 L350 24" stroke="#1d232b" strokeWidth="10" />
          <path d="M0 96 L350 84" stroke="#1d232b" strokeWidth="7" />
          <path d="M84 0 L104 130" stroke="#1d232b" strokeWidth="8" />
          <path d="M236 0 L222 130" stroke="#1d232b" strokeWidth="6" />
          <path d="M0 68 L350 58" stroke="#171c23" strokeWidth="3" />
          <circle cx="176" cy="56" r="12" fill="rgba(0,214,143,.18)" />
          <circle cx="176" cy="56" r="5" fill="#00D68F" />
        </svg>
        <span className="place">Telliskivi 60a, Tallinn</span>
      </div>

      <div className="card-blk" style={{ margin: "14px 0", padding: "2px 16px" }}>
        <div className="kv"><span className="kk">{t("paymentCard")}</span><span className="vv">Graphite •• 4417</span></div>
        <div className="kv"><span className="kk">{t("exchangeRate")}</span><span className="vv mono">1 EUR = 1.0874 USD</span></div>
        <div className="kv"><span className="kk">{t("midMarket")}</span><span className="vv mono">1.0874 · 0.0%</span></div>
        <div className="kv"><span className="kk">{t("fxFee")}</span><span className="vv mono" style={{ color: "var(--m3-mint)" }}>€0.00</span></div>
        <div className="kv"><span className="kk">{t("merchantId")}</span><span className="vv mono">{tx.mid}</span></div>
        <div className="kv"><span className="kk">{t("posted")}</span><span className="vv mono">{tx.posted}</span></div>
      </div>

      <button className="card-blk lrow" style={{ width: "100%", padding: "13px 16px", marginBottom: 14 }}
        onClick={() => app.toast(t("addReceipt"))}>
        <span className="lrow-ic"><Icon name="camera" size={17} /></span>
        <span className="lrow-main"><span className="lrow-label">{t("receipt")}</span><span className="lrow-sub">{t("addReceipt")}</span></span>
        <Icon name="plus" size={16} style={{ opacity: 0.4 }} />
      </button>

      <div className="agrid" style={{ marginBottom: 6 }}>
        {acts.map(([ic, l]) => (
          <button key={l} onClick={() => app.toast(l)}><Icon name={ic} size={18} />{l}</button>
        ))}
      </div>
    </div>
  );
}

/* ============ 16 · Earn ============ */
function ScrEarn({ app }) {
  const { t, go } = app;
  return (
    <div className="scr">
      <SH app={app} title={t("earnTitle")} backTo="home" />
      <div style={{ padding: "0 2px 4px" }}>
        <div className="k">{t("allTime")}</div>
        <div className="mono" style={{ fontSize: 34, fontWeight: 700, letterSpacing: "-0.02em", margin: "6px 0 4px" }}>€486.22</div>
        <div className="mono up" style={{ fontSize: 12.5 }}>+€0.54 {t("accrual")}</div>
      </div>
      <div className="card-blk" style={{ marginTop: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
          <span className="k">{t("apy12")}</span>
          <span className="mono" style={{ color: "var(--m3-mint)", fontSize: 14, fontWeight: 600 }}>3.2%</span>
        </div>
        <Area data={D4.earn.apyHistory} h={80} />
        <div className="mono mute" style={{ display: "flex", justifyContent: "space-between", fontSize: 9, marginTop: 4 }}>
          <span>AUG 25</span><span>JAN 26</span><span>JUL 26</span>
        </div>
      </div>

      <Sect title={t("products")} />
      <div className="list card-blk" style={{ padding: "2px 16px" }}>
        {D4.earn.products.map((p) => (
          <div className="lrow" key={p.asset}>
            <span className="flagchip" style={{ width: 38, height: 38, borderRadius: 12, fontSize: 9.5 }}>{p.asset}</span>
            <span className="lrow-main">
              <span className="lrow-label" style={{ display: "flex", gap: 7, alignItems: "center" }}>
                {p.name} <Pill tone="mint"><span className="mono">{p.apy}%</span></Pill>
              </span>
              <span className="lrow-sub">{p.note}</span>
            </span>
            {p.dep > 0
              ? <span className="lrow-r1 mono">{p.asset === "USDT" ? "₮" : "€"}{fmtNum(p.dep, 0)}</span>
              : <button className="wbtn" onClick={() => app.toast(t("deposit") + " · " + p.asset)}>{t("deposit")}</button>}
          </div>
        ))}
      </div>

      <Sect title={t("recentEarn")} />
      <div className="list card-blk" style={{ padding: "2px 16px" }}>
        {D4.earn.recent.map((r, i) => (
          <div className="lrow" key={i}>
            <span className="mavatar in"><Icon name="down" size={15} /></span>
            <span className="lrow-main">
              <span className="lrow-label">{r.m}</span>
              <span className="lrow-sub">{r.when}</span>
            </span>
            <span className="lrow-r1 mono up">{signed(r.amt)}</span>
          </div>
        ))}
      </div>
      <button className="btn" style={{ margin: "16px 0 6px" }} onClick={() => app.toast(t("deposit"))}>{t("deposit")}</button>
    </div>
  );
}

/* ============ 17 · Analytics ============ */
function ScrAnalytics({ app }) {
  const { t, go } = app;
  const A = D4.analytics;
  const total = A.cats.reduce((s, c) => s + c.amt, 0);
  return (
    <div className="scr">
      <SH app={app} title={t("analyticsTitle")} backTo="activity"
        right={<button className="icbtn" aria-label="Calendar"><Icon name="cal" size={16} /></button>} />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 2px" }}>
        <button className="icbtn" style={{ width: 32, height: 32 }}><span className="flipx" style={{ display: "flex" }}><Icon name="back" size={15} /></span></button>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 14.5, fontWeight: 600 }}>{A.month}</div>
          <div className="mono" style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 4 }}>€2,364.20</div>
          <div style={{ fontSize: 11.5, marginTop: 4 }}>
            <span className="mono up">−8.2%</span> <span className="mute">{t("vsLastMonth")}</span>
            <span className="mute mono"> · €3,180 {t("predicted")}</span>
          </div>
        </div>
        <button className="icbtn" style={{ width: 32, height: 32 }}><span className="flipx" style={{ display: "flex" }}><Icon name="chev" size={15} /></span></button>
      </div>

      <Sect title={t("byCategory")} />
      <div className="card-blk" style={{ display: "flex", gap: 18, alignItems: "center" }}>
        <Donut parts={A.cats} size={118} width={11} />
        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
          {A.cats.map((c) => (
            <div key={c.name} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: catColor(c.c), flexShrink: 0 }}></span>
              <span style={{ flex: 1 }}>{c.name}</span>
              <span className="mono mute">{eur(c.amt, 0)}</span>
            </div>
          ))}
        </div>
      </div>

      <Sect title={t("dailySpend")} />
      <div className="card-blk">
        <Bars data={A.daily} h={70} />
        <div className="mono mute" style={{ display: "flex", justifyContent: "space-between", fontSize: 9, marginTop: 5 }}>
          <span>1 JUL</span><span>7</span><span>14 JUL</span>
        </div>
      </div>

      <Sect title={t("topMerchants")} />
      <div className="list card-blk" style={{ padding: "2px 16px", marginBottom: 6 }}>
        {A.top.map((m) => (
          <button className="lrow" key={m.m} onClick={() => go("tx")}>
            <span className="mavatar">{m.m.slice(0, 2)}</span>
            <span className="lrow-main">
              <span className="lrow-label">{m.m}</span>
              <span className="lrow-sub">{m.n} {t("txCount")}</span>
            </span>
            <span className="lrow-r1 mono">{eur(m.amt)}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScrActivity, ScrTx, ScrEarn, ScrAnalytics });
