/* mSamex Card — screens 18–21: Notifications, Profile, Security center, Business */
const { Icon, Pill, Chip, Tgl, Bar, Sect, Avatar, Row, catColor, eur, money, signed, fmtNum } = window.CardKit;
const D5 = window.CARD_DATA;

/* ============ 18 · Notifications ============ */
function ScrNotifs({ app }) {
  const { t, go } = app;
  const [f, setF] = React.useState("all");
  const [read, setRead] = React.useState({});
  const kindIcon = { tx: "card", security: "shield", promo: "tag", account: "user" };
  const rows = D5.notifications.filter((n) => f === "all" ||
    (f === "tx" && n.kind === "tx") || (f === "security" && n.kind === "security") ||
    (f === "promo" && n.kind === "promo") || (f === "account" && n.kind === "account"));
  return (
    <div className="scr">
      <SH app={app} title={t("notifTitle")} backTo="home"
        right={<button style={{ fontSize: 12, color: "var(--m3-mint)", fontWeight: 600, whiteSpace: "nowrap" }}
          onClick={() => setRead({ n1: 1, n2: 1 })}>{t("markAll")}</button>} />
      <div className="chiprow" style={{ marginBottom: 14 }}>
        {[["all", t("all")], ["tx", t("transactions")], ["security", t("securityF")], ["promo", t("promos")], ["account", t("account")]].map(([id, l]) => (
          <Chip key={id} on={f === id} onClick={() => setF(id)}>{l}</Chip>
        ))}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {rows.map((n) => {
          const unread = n.unread && !read[n.id];
          return (
            <div key={n.id} className={"ncard" + (unread ? " unread" : "")}>
              <span className="nk"><Icon name={kindIcon[n.kind]} size={16} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1 }}>{n.title}</span>
                  <span className="mono mute" style={{ fontSize: 10 }}>{n.when}</span>
                  {unread && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--m3-mint)", flexShrink: 0 }}></span>}
                </div>
                <div className="mute" style={{ fontSize: 12, lineHeight: 1.5, marginTop: 4 }}>{n.body}</div>
                {n.kind === "tx" && (
                  <div className="nact">
                    <button className="hot" onClick={() => go("tx")}>{t("viewReceipt")}</button>
                    <button onClick={() => app.toast(t("dispute"))}>{t("dispute")}</button>
                  </div>
                )}
                {n.kind === "security" && (
                  <div className="nact">
                    <button className="hot" onClick={() => { setRead({ ...read, [n.id]: 1 }); app.toast(t("itWasMe")); }}>{t("itWasMe")}</button>
                    <button className="bad" onClick={() => go("security")}>{t("block")}</button>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ============ 19 · Profile ============ */
function ScrProfile({ app }) {
  const { t, go } = app;
  const G = ({ title, rows }) => (<>
    <Sect title={title} />
    <div className="list card-blk" style={{ padding: "2px 16px" }}>
      {rows.map((r) => (
        <button className="lrow" key={r.l} onClick={r.go ? () => go(r.go) : () => {}}>
          <span className="lrow-ic"><Icon name={r.ic} size={16} /></span>
          <span className="lrow-main">
            <span className="lrow-label">{r.l}</span>
            {r.s && <span className="lrow-sub">{r.s}</span>}
          </span>
          {r.pill && <Pill tone="mint">{r.pill}</Pill>}
          <Icon name="chev" size={15} style={{ opacity: 0.35, flexShrink: 0 }} />
        </button>
      ))}
    </div>
  </>);
  return (
    <div className="scr">
      <SH app={app} title={t("profile")} backTo="home"
        right={<button className="icbtn" aria-label="Settings"><Icon name="gear" size={17} /></button>} />

      <div className="card-blk" style={{ display: "flex", gap: 14, alignItems: "center" }}>
        <div style={{ position: "relative" }}>
          <Avatar name="Kertu Laanemets" size={56} tone="mint" />
          <span style={{ position: "absolute", bottom: -3, insetInlineEnd: -3, background: "var(--m3-mint)", color: "var(--m3-ink)", borderRadius: 999, fontSize: 8, fontWeight: 800, padding: "2px 5px", border: "2px solid var(--m3-surface)" }}>A</span>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 17, fontWeight: 700 }}>Kertu Laanemets</div>
          <div className="mono mute" style={{ fontSize: 12, margin: "3px 0 8px" }}>@kertu · {t("memberSince")}</div>
          <div style={{ display: "flex", gap: 6 }}>
            <Pill tone="mint">Aurum Reserve</Pill>
            <Pill tone="dim"><Icon name="check" size={9} /> {t("verifiedP")}</Pill>
          </div>
        </div>
      </div>

      <div className="seg" style={{ margin: "14px 0 4px" }}>
        <button className="on">{t("personal")}</button>
        <button onClick={() => go("business")}>{t("businessMode")}</button>
      </div>

      <G title={t("account")} rows={[
        { ic: "user", l: t("personalInfo"), s: "Kertu Laanemets · +372 5• •• ••7" },
        { ic: "check", l: t("kyc"), s: "ID + liveness · Feb 2026", pill: t("verifiedP") },
        { ic: "pin", l: t("address"), s: "Pikk 12-4, 10123 Tallinn" },
      ]} />
      <G title={t("money")} rows={[
        { ic: "bank", l: t("accounts"), s: "8 · €31,398.75", go: "accounts" },
        { ic: "card", l: t("cards"), s: "3 · 1 " + t("physical"), go: "cards" },
        { ic: "pulse", l: t("earnTitle"), s: "3.2–8.2% APY", go: "earn" },
        { ic: "doc", l: t("statementsExports"), s: "PDF · CSV", go: "activity" },
        { ic: "repeat", l: t("subscription"), s: "Aurum Reserve · €39.99" + t("perMonth") },
      ]} />
      <G title={t("securityF")} rows={[
        { ic: "shield", l: t("securityCenter"), s: t("faceId") + " · " + t("passkeys") + " · 2FA", go: "security" },
        { ic: "bell", l: t("notifTitle"), s: "2 " + t("in"), go: "notifs" },
      ]} />
      <G title={t("preferences")} rows={[
        { ic: "globe", l: t("languageRow"), s: t("language") },
        { ic: "moon", l: t("appearance"), s: t("dark") },
      ]} />
      <G title={t("support")} rows={[
        { ic: "search", l: t("help") },
        { ic: "contact", l: t("contact"), s: "24/7" },
        { ic: "doc", l: t("legalRow") },
      ]} />
      <button className="lrow danger" style={{ justifyContent: "center", padding: "18px 0 8px" }} onClick={() => go("splash")}>
        <span className="lrow-label">{t("signOut")}</span>
      </button>
    </div>
  );
}

/* ============ 20 · Security center ============ */
function ScrSecurity({ app }) {
  const { t, go } = app;
  const [m, setM] = React.useState({ face: true, passkey: true, tfa: false });
  const methods = [
    ["face", t("faceId"), "iPhone 17 Pro"],
    ["passkey", t("passkeys"), "MacBook Pro · iCloud Keychain"],
    ["tfa", t("twofa"), "—"],
  ];
  return (
    <div className="scr">
      <SH app={app} title={t("securityCenter")} backTo="profile" />
      <Sect title={t("signIn")} />
      <div className="card-blk" style={{ padding: "4px 16px" }}>
        {methods.map(([k, l, s]) => (
          <div className="kv" key={k}>
            <span>
              <span style={{ fontSize: 14, fontWeight: 500, display: "block" }}>{l}</span>
              <span className="mute" style={{ fontSize: 11.5 }}>{s}</span>
            </span>
            <Tgl on={m[k]} onChange={(v) => setM({ ...m, [k]: v })} />
          </div>
        ))}
      </div>

      <Sect title={t("trustedDevices")} />
      <div className="list card-blk" style={{ padding: "2px 16px" }}>
        {D5.security.devices.map((d) => (
          <div className="lrow" key={d.name}>
            <span className="lrow-ic"><Icon name={d.name.includes("Mac") ? "card" : "user"} size={16} /></span>
            <span className="lrow-main">
              <span className="lrow-label" style={{ display: "flex", gap: 7, alignItems: "center" }}>
                {d.name}{d.thisDevice && <Pill tone="mint">{t("thisDevice")}</Pill>}
              </span>
              <span className="lrow-sub">{t("addedRow")} {d.added} · {t("lastSeen")} {d.seen}</span>
            </span>
            <button className="icbtn" style={{ width: 30, height: 30 }}><Icon name="dots" size={14} /></button>
          </div>
        ))}
      </div>

      <Sect title={t("loginHistory")} />
      <div className="list card-blk" style={{ padding: "2px 16px" }}>
        {D5.security.logins.map((l, i) => (
          <div className="lrow" key={i}>
            <span className="lrow-main">
              <span className="lrow-label">{l.dev}</span>
              <span className="lrow-sub">{l.city} · {l.when}</span>
            </span>
            <Pill tone={l.ok ? "mint" : "coral"}>{l.ok ? t("success") : t("blocked")}</Pill>
          </div>
        ))}
      </div>

      <Sect title={t("approvalRules")} />
      <div className="card-blk" style={{ padding: "2px 16px", marginBottom: 6 }}>
        {D5.security.rules.map((r) => (
          <div className="kv" key={r.k}>
            <span className="kk">{r.k}</span><span className="vv mono">{r.v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============ 21 · Business mode ============ */
function ScrBusiness({ app }) {
  const { t, go } = app;
  const B = D5.business;
  const catTotal = B.cats.reduce((s, c) => s + c.amt, 0);
  return (
    <div className="scr">
      <SH app={app} title={t("businessMode")} backTo="profile" />
      <div className="seg" style={{ marginBottom: 16 }}>
        <button onClick={() => go("profile")}>{t("personal")}</button>
        <button className="on">{t("businessMode")}</button>
      </div>

      <div style={{ padding: "0 2px" }}>
        <div className="k">{B.company}</div>
        <div className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", margin: "6px 0 4px" }}>€48,210.77</div>
        <div className="mute" style={{ fontSize: 12 }}>{B.subs} {t("subAccounts")} · {B.people} {t("teamMembers")}</div>
      </div>

      <div className="qa-row" style={{ justifyContent: "flex-start", gap: 26 }}>
        <button className="qa" onClick={() => go("addmoney")}><span className="qa-ic"><Icon name="plus" size={20} /></span>{t("topUp")}</button>
        <button className="qa" onClick={() => go("send")}><span className="qa-ic"><Icon name="up" size={20} /></span>{t("pay")}</button>
        <button className="qa"><span className="qa-ic"><Icon name="contact" size={20} /></span>{t("team")}</button>
      </div>

      <Sect title={t("teamSpending")} />
      <div className="card-blk">
        <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
          <span className="mono" style={{ fontSize: 22, fontWeight: 600 }}>€6,842.10</span>
          <span className="mono" style={{ fontSize: 11.5, color: "var(--m3-warn)" }}>+4.6% {t("vsLastMonth")}</span>
        </div>
        <div style={{ display: "flex", height: 8, borderRadius: 99, overflow: "hidden", gap: 2, margin: "12px 0 12px" }}>
          {B.cats.map((c) => (
            <span key={c.name} style={{ width: (c.amt / catTotal) * 100 + "%", background: catColor(c.c) }}></span>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
          {B.cats.map((c) => (
            <span key={c.name} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 11.5 }}>
              <span style={{ width: 7, height: 7, borderRadius: 2, background: catColor(c.c) }}></span>
              <span className="mute" style={{ flex: 1 }}>{c.name}</span>
              <span className="mono">{eur(c.amt, 0)}</span>
            </span>
          ))}
        </div>
      </div>

      <Sect title={t("employeeCards")} action={"+ " + t("addCard")} onAction={() => go("order")} />
      <div className="list card-blk" style={{ padding: "2px 16px" }}>
        {B.employees.map((e) => (
          <div className="lrow" key={e.name}>
            <Avatar name={e.name} size={38} />
            <span className="lrow-main">
              <span className="lrow-label">{e.name} <span className="mono mute" style={{ fontSize: 10.5 }}>••{e.last4}</span></span>
              <span className="lrow-sub" style={{ marginTop: 4 }}>
                <Bar v={e.spent} max={e.limit} h={3.5} tone={e.spent / e.limit > 0.9 ? "warn" : "mint"} />
              </span>
              <span className="lrow-sub">{e.role}</span>
            </span>
            <span className="lrow-right">
              <span className="lrow-r1 mono" style={{ fontSize: 12.5 }}>{eur(e.spent)}</span>
              <span className="lrow-r2 mono">/ {eur(e.limit, 0)}</span>
            </span>
          </div>
        ))}
      </div>

      <Sect title={t("companyTx")} />
      <div className="list card-blk" style={{ padding: "2px 16px", marginBottom: 6 }}>
        {B.txs.map((x, i) => (
          <div className="lrow" key={i}>
            <span className={"mavatar" + (x.in ? " in" : "")}>{x.in ? <Icon name="down" size={15} /> : x.m.slice(0, 2)}</span>
            <span className="lrow-main">
              <span className="lrow-label">{x.m}</span>
              <span className="lrow-sub">{x.cat} · {x.when}{x.who ? " · " + x.who : ""}</span>
            </span>
            <span className={"lrow-r1 mono" + (x.in ? " up" : "")}>{signed(x.amt)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ScrNotifs, ScrProfile, ScrSecurity, ScrBusiness });
