// Wealth screen — segmented Assets / Liabilities

const WEALTH_ROW_BUTTON_BG =
  "linear-gradient(155deg, rgb(246, 247, 249) 0%, rgb(255, 255, 255) 90%)";

function isMidnightWealthTheme(theme) {
  return theme?.label === "Midnight" && theme?.description === "slate + cyan";
}

function AssetsScreen({ theme, accent, onNav, onAddAsset, onAskHimma }) {
  const [view, setView] = React.useState("assets"); // 'assets' | 'liabilities'
  const openAddAsset = () => {
    if (onAddAsset) onAddAsset();
    else window.dispatchEvent(new CustomEvent("himma-add-asset"));
  };
  const openAddLiability = () =>
    window.dispatchEvent(new CustomEvent("himma-add-liability"));

  return (
    <Screen theme={theme}>
      <AppTopbar
        theme={theme}
        accent={accent}
        onNav={onNav}
        onAskHimma={onAskHimma}
      />

      <div style={{ padding: "6px 16px 14px" }}>
        <WealthSegmented
          value={view}
          onChange={setView}
          theme={theme}
          accent={accent}
        />
      </div>

      {view === "assets" ? (
        <AssetsBody
          theme={theme}
          accent={accent}
          onNav={onNav}
          onAddAsset={openAddAsset}
        />
      ) : (
        <LiabilitiesBody
          theme={theme}
          accent={accent}
          onNav={onNav}
          onAddLiability={openAddLiability}
        />
      )}

      <div style={{ height: 10 }} />
    </Screen>
  );
}

function WealthAddButton({ theme, label, onClick }) {
  const midnight = isMidnightWealthTheme(theme);
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: "100%",
        minHeight: 38,
        background: midnight ? theme.surface2 : WEALTH_ROW_BUTTON_BG,
        border: `0.5px solid ${theme.line2}`,
        borderRadius: 13,
        padding: "9px 10px",
        color: theme.text,
        fontFamily: FONTS.ui,
        fontSize: 12.5,
        fontWeight: 600,
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        gap: 6,
        whiteSpace: "nowrap",
      }}
    >
      <Ico.plus size={13} /> {label}
    </button>
  );
}

function WealthSegmented({ value, onChange, theme, accent }) {
  const opts = [
    { key: "assets", label: "Assets", total: ASSETS_TOTAL },
    { key: "liabilities", label: "Liabilities", total: LIABILITIES_TOTAL },
  ];
  return (
    <div
      style={{
        display: "flex",
        background: theme.surface2,
        border: `0.5px solid ${theme.line}`,
        borderRadius: 14,
        padding: 3,
      }}
    >
      {opts.map((o) => {
        const active = value === o.key;
        return (
          <button
            key={o.key}
            onClick={() => onChange(o.key)}
            style={{
              flex: 1,
              background: active ? theme.surface : "transparent",
              border: "none",
              borderRadius: 11,
              padding: "8px 12px",
              cursor: "pointer",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              gap: 2,
              boxShadow: active ? "0 1px 2px rgba(0,0,0,0.06)" : "none",
              transition: "background 140ms",
            }}
          >
            <span
              style={{
                fontFamily: FONTS.ui,
                fontSize: 12.5,
                fontWeight: 600,
                color: active ? theme.text : theme.textDim,
              }}
            >
              {o.label}
            </span>
            <span
              style={{
                fontFamily: FONTS.mono,
                fontSize: 10,
                fontVariantNumeric: "tabular-nums",
                color: active ? theme.textDim : theme.textMute,
              }}
            >
              {o.key === "liabilities" ? "−" : ""}
              <Dh /> {fmtAED(o.total, { compact: true })}
            </span>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// ASSETS BODY
// ─────────────────────────────────────────────────────────────
function AssetsBody({ theme, accent, onNav, onAddAsset }) {
  const [open, setOpen] = React.useState({
    banking: true,
    brokerages: false,
    crypto: false,
    realestate: false,
    other: false,
  });
  const [realEstateItems, setRealEstateItems] = React.useState(() =>
    REAL_ESTATE.map((r) => ({ ...r })),
  );
  const [otherAssetItems, setOtherAssetItems] = React.useState(() =>
    OTHER_ASSETS.map((o) => ({ ...o })),
  );
  const [assetEditor, setAssetEditor] = React.useState(null);
  const [deleteConfirm, setDeleteConfirm] = React.useState(null);

  const toggle = (k) => setOpen((o) => ({ ...o, [k]: !o[k] }));

  const banksUAE = BANK_ACCOUNTS.filter((b) => b.region === "UAE");
  const banksIntl = BANK_ACCOUNTS.filter((b) => b.region === "International");
  const bankTotal = BANK_ACCOUNTS.reduce((s, b) => s + b.balance, 0);
  const banksUAETotal = banksUAE.reduce((s, b) => s + b.balance, 0);
  const banksIntlTotal = banksIntl.reduce((s, b) => s + b.balance, 0);
  const brokTotal = BROKERAGES.reduce((s, b) => s + b.portfolio, 0);
  const cryptoAccounts =
    typeof CRYPTO_ACCOUNTS !== "undefined" ? CRYPTO_ACCOUNTS : [];
  const cryptoTotal = cryptoAccounts.length
    ? cryptoAccounts.reduce(
        (s, a) => s + a.holdings.reduce((sum, h) => sum + h.value, 0),
        0,
      )
    : CRYPTO.reduce((s, c) => s + c.value, 0);
  const reTotal = realEstateItems.reduce((s, r) => s + r.value, 0);
  const otherTotal = otherAssetItems.reduce((s, o) => s + o.value, 0);
  const total = bankTotal + brokTotal + cryptoTotal + reTotal + otherTotal;

  const saveAssetEdit = (updated) => {
    if (!assetEditor) return;
    if (assetEditor.kind === "realestate") {
      setRealEstateItems((items) =>
        items.map((item) => (item.id === updated.id ? updated : item)),
      );
    } else {
      setOtherAssetItems((items) =>
        items.map((item) => (item.id === updated.id ? updated : item)),
      );
    }
    setAssetEditor(null);
  };

  const deleteRealEstate = (id) =>
    setRealEstateItems((items) => items.filter((item) => item.id !== id));
  const deleteOtherAsset = (id) =>
    setOtherAssetItems((items) => items.filter((item) => item.id !== id));
  const requestAssetDelete = (kind, item) => setDeleteConfirm({ kind, item });
  const confirmAssetDelete = () => {
    if (!deleteConfirm) return;
    if (deleteConfirm.kind === "realestate") {
      deleteRealEstate(deleteConfirm.item.id);
    } else {
      deleteOtherAsset(deleteConfirm.item.id);
    }
    setAssetEditor(null);
    setDeleteConfirm(null);
  };

  return (
    <>
      {/* Total + 12-month trend */}
      <div>
        <Card theme={theme} style={{ padding: 18, border: "none" }}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "flex-end",
            }}
          >
            <div>
              <SectionLabel theme={theme}>Total assets</SectionLabel>
              <BigNumber
                value={total}
                theme={theme}
                accent={theme.text}
                size={30}
              />
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <Spark
              data={ASSETS_TREND}
              width={300}
              height={48}
              color={accent}
              responsive
            />
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                fontFamily: FONTS.mono,
                fontSize: 9,
                color: theme.textMute,
                marginTop: 4,
                letterSpacing: 0.5,
              }}
            >
              <span>MAY '25</span>
              <span>APR '26</span>
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <WealthAddButton
              theme={theme}
              label="Add assets"
              onClick={onAddAsset}
            />
          </div>
        </Card>
      </div>

      {/* Bank accounts */}
      <AssetSection
        title="Bank accounts"
        total={bankTotal}
        parentTotal={total}
        open={open.banking}
        onToggle={() => toggle("banking")}
        theme={theme}
        accent={accent}
      >
        <SubRegion
          theme={theme}
          accent={accent}
          label="UAE"
          total={banksUAETotal}
          count={banksUAE.length}
        >
          {banksUAE.map((b) => (
            <BankRow key={b.id} b={b} theme={theme} accent={accent} />
          ))}
        </SubRegion>
        <SubRegion
          theme={theme}
          accent={accent}
          label="International"
          total={banksIntlTotal}
          count={banksIntl.length}
        >
          {banksIntl.map((b) => (
            <BankRow key={b.id} b={b} theme={theme} accent={accent} />
          ))}
        </SubRegion>
      </AssetSection>

      {/* Brokerage accounts */}
      <AssetSection
        title="Trading accounts"
        total={brokTotal}
        parentTotal={total}
        open={open.brokerages}
        onToggle={() => toggle("brokerages")}
        theme={theme}
        accent={accent}
      >
        {BROKERAGES.map((b, i) => (
          <Row
            key={b.id}
            theme={theme}
            onClick={() =>
              onNav && onNav("brokerage_detail", { brokerageId: b.id })
            }
            chevron
            last={i === BROKERAGES.length - 1}
            left={<BrandLogo name={b.name} size={36} />}
            title={b.name}
            subtitle={`${b.holdings.length} holdings`}
            rightTop={
              <span
                style={{
                  fontFamily: FONTS.mono,
                  fontSize: 14,
                  color: theme.text,
                }}
              >
                <Dh /> {fmtAED(b.portfolio)}
              </span>
            }
            rightBottom={
              <Delta value={b.pnlDay} pct={b.pnlPct} theme={theme} size={11} />
            }
          />
        ))}
      </AssetSection>

      {/* Crypto */}
      <AssetSection
        title="Crypto"
        total={cryptoTotal}
        parentTotal={total}
        open={open.crypto}
        onToggle={() => toggle("crypto")}
        theme={theme}
        accent={accent}
      >
        {(cryptoAccounts.length
          ? cryptoAccounts
          : [
              {
                id: "crypto-direct",
                name: "Crypto holdings",
                kind: "Ungrouped",
                holdings: CRYPTO,
              },
            ]
        ).map((account, i, arr) => (
          <CryptoAccountGroup
            key={account.id}
            account={account}
            theme={theme}
            accent={accent}
            onOpen={() =>
              onNav && onNav("crypto_detail", { cryptoAccountId: account.id })
            }
            last={i === arr.length - 1}
          />
        ))}
      </AssetSection>

      {/* Real estate — collapsible cards, one per property */}
      <AssetSection
        title="Real Estate"
        total={reTotal}
        parentTotal={total}
        open={open.realestate}
        onToggle={() => toggle("realestate")}
        theme={theme}
        accent={accent}
      >
        <div
          style={{
            padding: 14,
            display: "flex",
            flexDirection: "column",
            gap: 10,
          }}
        >
          {realEstateItems.map((r) => (
            <PropertyCard
              key={r.id}
              r={r}
              theme={theme}
              accent={accent}
              onEdit={() => setAssetEditor({ kind: "realestate", item: r })}
              onDelete={() => requestAssetDelete("realestate", r)}
            />
          ))}
          {!realEstateItems.length && (
            <EmptyManualState theme={theme} label="No real estate added." />
          )}
        </div>
      </AssetSection>

      {/* Other valuables */}
      <AssetSection
        title="Other Valuables"
        total={otherTotal}
        parentTotal={total}
        open={open.other}
        onToggle={() => toggle("other")}
        theme={theme}
        accent={accent}
      >
        {otherAssetItems.map((o, i) => (
          <EditableOtherAssetRow
            key={o.id}
            o={o}
            theme={theme}
            accent={accent}
            last={i === otherAssetItems.length - 1}
            onEdit={() => setAssetEditor({ kind: "other", item: o })}
            onDelete={() => requestAssetDelete("other", o)}
          />
        ))}
        {!otherAssetItems.length && (
          <EmptyManualState theme={theme} label="No valuables added." />
        )}
      </AssetSection>
      {assetEditor && (
        <EditAssetSheet
          editor={assetEditor}
          theme={theme}
          accent={accent}
          onClose={() => setAssetEditor(null)}
          onSave={saveAssetEdit}
          onDelete={() =>
            requestAssetDelete(assetEditor.kind, assetEditor.item)
          }
        />
      )}
      {deleteConfirm && (
        <DeleteManualAssetConfirmSheet
          request={deleteConfirm}
          theme={theme}
          onCancel={() => setDeleteConfirm(null)}
          onConfirm={confirmAssetDelete}
        />
      )}
    </>
  );
}

// One real-estate property as its own collapsible card.
function PropertyCard({ r, theme, accent, onEdit, onDelete }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div
      style={{
        background: theme.surface,
        border: `0.5px solid ${theme.line}`,
        borderRadius: 14,
        overflow: "hidden",
      }}
    >
      <button
        onClick={() => setOpen((o) => !o)}
        style={{
          width: "100%",
          background: "transparent",
          border: "none",
          padding: "14px 14px",
          display: "flex",
          alignItems: "center",
          gap: 12,
          cursor: "pointer",
          textAlign: "left",
          color: theme.text,
        }}
      >
        <div
          style={{
            width: 36,
            height: 36,
            borderRadius: 10,
            background: theme.surface2,
            color: accent,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            border: `0.5px solid ${theme.line}`,
            flexShrink: 0,
          }}
        >
          <Ico.home size={16} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontSize: 13.5,
              color: theme.text,
              fontWeight: 500,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {r.name}
          </div>
          <div
            style={{
              fontSize: 11,
              color: theme.textMute,
              fontFamily: FONTS.mono,
              marginTop: 2,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {r.location}
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div
            style={{
              fontFamily: FONTS.mono,
              fontSize: 14,
              color: theme.text,
              whiteSpace: "nowrap",
            }}
          >
            <Dh /> {fmtAED(r.value, { compact: true })}
          </div>
          <div
            style={{
              fontFamily: FONTS.mono,
              fontSize: 10,
              color: theme.text,
              marginTop: 2,
            }}
          >
            Market value
          </div>
        </div>
        <div
          style={{
            marginLeft: 6,
            color: theme.textDim,
            transform: open ? "rotate(90deg)" : "",
            transition: "transform 160ms",
          }}
        >
          <Ico.chevR size={13} />
        </div>
      </button>
      {open && (
        <div
          style={{
            padding: "4px 14px 14px",
            borderTop: `0.5px solid ${theme.line}`,
          }}
        >
          <div
            style={{
              marginTop: 10,
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 10,
              fontFamily: FONTS.mono,
              fontSize: 10.5,
            }}
          >
            <AssetStat
              label="Purchase value"
              value={`${fmtAED(r.purchase, { compact: true })}`}
              theme={theme}
            />
            <AssetStat
              label="Market value"
              value={`${fmtAED(r.value, { compact: true })}`}
              theme={theme}
            />
          </div>
          {(r.propertyType || r.sizeSqft || r.rooms) && (
            <div
              style={{
                marginTop: 12,
                fontFamily: FONTS.mono,
                fontSize: 10.5,
                color: theme.textDim,
                letterSpacing: 0.3,
              }}
            >
              {[
                r.propertyType,
                r.sizeSqft
                  ? `${r.sizeSqft.toLocaleString("en-AE")} sqft`
                  : null,
                r.rooms ? `${r.rooms} room${r.rooms === 1 ? "" : "s"}` : null,
              ]
                .filter(Boolean)
                .join(" · ")}
            </div>
          )}
          {r.address && (
            <div
              style={{
                marginTop: 6,
                fontSize: 11,
                color: theme.textMute,
                fontFamily: FONTS.ui,
              }}
            >
              {r.address}
            </div>
          )}
          <ManualItemActions
            theme={theme}
            onEdit={onEdit}
            onDelete={onDelete}
            style={{ marginTop: 12 }}
          />
        </div>
      )}
    </div>
  );
}

function EditableOtherAssetRow({ o, theme, accent, last, onEdit, onDelete }) {
  const iconName =
    o.category === "Vehicle"
      ? "car"
      : o.category === "Jewellery"
        ? "gem"
        : "briefcase";
  const IcC = Ico[iconName];
  return (
    <Row
      theme={theme}
      last={last}
      left={
        <div
          style={{
            width: 36,
            height: 36,
            borderRadius: 10,
            background: theme.surface2,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: accent,
            border: `0.5px solid ${theme.line}`,
          }}
        >
          <IcC size={16} />
        </div>
      }
      title={o.name}
      subtitle={o.category}
      rightTop={
        <span
          style={{
            fontFamily: FONTS.mono,
            fontSize: 14,
            color: theme.text,
          }}
        >
          <Dh /> {fmtAED(o.value)}
        </span>
      }
      rightBottom={
        <ManualItemActions theme={theme} onEdit={onEdit} onDelete={onDelete} />
      }
    />
  );
}

function ManualItemActions({ theme, onEdit, onDelete, style = {} }) {
  return (
    <div
      onClick={(e) => e.stopPropagation()}
      style={{ display: "inline-flex", alignItems: "center", gap: 6, ...style }}
    >
      <IconActionButton
        label="Edit"
        icon="compose"
        theme={theme}
        onClick={onEdit}
      />
      <IconActionButton
        label="Delete"
        icon="trash"
        theme={theme}
        tone={theme.negative}
        onClick={onDelete}
      />
    </div>
  );
}

function IconActionButton({ label, icon, theme, tone, onClick }) {
  const Icon = Ico[icon];
  return (
    <button
      type="button"
      aria-label={label}
      title={label}
      onClick={onClick}
      style={{
        width: 28,
        height: 28,
        borderRadius: 14,
        background: theme.surface2,
        border: `0.5px solid ${theme.line2}`,
        color: tone || theme.textDim,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        cursor: "pointer",
        padding: 0,
      }}
    >
      <Icon size={13} />
    </button>
  );
}

function EmptyManualState({ theme, label }) {
  return (
    <div
      style={{
        padding: "16px 18px",
        color: theme.textMute,
        fontFamily: FONTS.mono,
        fontSize: 10.5,
        letterSpacing: 0.2,
      }}
    >
      {label}
    </div>
  );
}

function EditAssetSheet({ editor, theme, accent, onClose, onSave, onDelete }) {
  const [form, setForm] = React.useState(() => ({ ...editor.item }));

  React.useEffect(() => {
    setForm({ ...editor.item });
  }, [editor]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const cleanMoney = (v) => String(v).replace(/[^0-9]/g, "");
  const isRealEstate = editor.kind === "realestate";
  const title = isRealEstate ? "Edit real estate" : "Edit valuable";
  const canSave = form.name && Number(form.value) > 0;

  const save = () => {
    const updated = {
      ...editor.item,
      ...form,
      value: Number(form.value) || 0,
    };
    if (isRealEstate) {
      updated.purchase = Number(form.purchase) || 0;
      updated.sizeSqft = Number(form.sizeSqft) || 0;
      updated.rooms = Number(form.rooms) || 0;
    }
    onSave(updated);
  };

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 80,
        display: "flex",
        alignItems: "flex-end",
        background: "rgba(0,0,0,0.45)",
      }}
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          maxHeight: "82%",
          overflowY: "auto",
          background: theme.surface,
          borderRadius: "24px 24px 0 0",
          borderTop: `0.5px solid ${theme.line2}`,
          padding: "10px 20px 34px",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 12,
          }}
        >
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 22,
              color: theme.text,
              letterSpacing: -0.4,
            }}
          >
            {title}
          </div>
          <IconActionButton
            label="Delete"
            icon="trash"
            theme={theme}
            tone={theme.negative}
            onClick={() => onDelete(editor.item.id)}
          />
        </div>

        <div style={{ marginTop: 16 }}>
          <EditField
            theme={theme}
            label={isRealEstate ? "Property name" : "Name"}
          >
            <input
              value={form.name || ""}
              onChange={(e) => set("name", e.target.value)}
              placeholder={isRealEstate ? "JVC Studio" : "2022 Mazda CX-5"}
              style={editInputStyle(theme)}
            />
          </EditField>

          {isRealEstate ? (
            <>
              <EditField theme={theme} label="Location">
                <input
                  value={form.location || ""}
                  onChange={(e) => set("location", e.target.value)}
                  placeholder="Jumeirah Village Circle, Dubai"
                  style={editInputStyle(theme)}
                />
              </EditField>
              <EditField theme={theme} label="Address">
                <textarea
                  value={form.address || ""}
                  onChange={(e) => set("address", e.target.value)}
                  rows={2}
                  placeholder="Tower B · Apt 1204"
                  style={editInputStyle(theme)}
                />
              </EditField>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 12,
                }}
              >
                <EditField theme={theme} label="Purchase (AED)">
                  <input
                    value={form.purchase || ""}
                    onChange={(e) =>
                      set("purchase", cleanMoney(e.target.value))
                    }
                    inputMode="numeric"
                    placeholder="540000"
                    style={editInputStyle(theme)}
                  />
                </EditField>
                <EditField theme={theme} label="Market value (AED)">
                  <input
                    value={form.value || ""}
                    onChange={(e) => set("value", cleanMoney(e.target.value))}
                    inputMode="numeric"
                    placeholder="620000"
                    style={editInputStyle(theme)}
                  />
                </EditField>
              </div>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 12,
                }}
              >
                <EditField theme={theme} label="Size (sqft)">
                  <input
                    value={form.sizeSqft || ""}
                    onChange={(e) =>
                      set("sizeSqft", cleanMoney(e.target.value))
                    }
                    inputMode="numeric"
                    placeholder="612"
                    style={editInputStyle(theme)}
                  />
                </EditField>
                <EditField theme={theme} label="Rooms">
                  <input
                    value={form.rooms || ""}
                    onChange={(e) => set("rooms", cleanMoney(e.target.value))}
                    inputMode="numeric"
                    placeholder="1"
                    style={editInputStyle(theme)}
                  />
                </EditField>
              </div>
            </>
          ) : (
            <>
              <EditField theme={theme} label="Category">
                <input
                  value={form.category || ""}
                  onChange={(e) => set("category", e.target.value)}
                  placeholder="Vehicle"
                  style={editInputStyle(theme)}
                />
              </EditField>
              <EditField theme={theme} label="Estimated value (AED)">
                <input
                  value={form.value || ""}
                  onChange={(e) => set("value", cleanMoney(e.target.value))}
                  inputMode="numeric"
                  placeholder="82000"
                  style={editInputStyle(theme)}
                />
              </EditField>
            </>
          )}
        </div>

        <button
          type="button"
          onClick={save}
          disabled={!canSave}
          style={{
            marginTop: 22,
            width: "100%",
            background: canSave ? accent : theme.surface3,
            color: canSave ? theme.bg : theme.textMute,
            border: "none",
            borderRadius: 14,
            padding: "14px",
            fontFamily: FONTS.ui,
            fontSize: 14,
            fontWeight: 600,
            cursor: canSave ? "pointer" : "not-allowed",
          }}
        >
          Save changes
        </button>
      </div>
    </div>
  );
}

function EditField({ theme, label, children }) {
  return (
    <div style={{ marginTop: 14 }}>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 10,
          color: theme.textMute,
          textTransform: "uppercase",
          letterSpacing: 1,
          marginBottom: 6,
        }}
      >
        {label}
      </div>
      {children}
    </div>
  );
}

function editInputStyle(theme) {
  return {
    width: "100%",
    background: theme.surface2,
    border: `0.5px solid ${theme.line2}`,
    borderRadius: 12,
    padding: "12px 14px",
    color: theme.text,
    fontSize: 13.5,
    fontFamily: FONTS.ui,
    outline: "none",
    resize: "vertical",
  };
}

function BrokerageDetailScreen({ theme, accent, brokerageId, onBack }) {
  const brokerage =
    BROKERAGES.find((b) => b.id === brokerageId) || BROKERAGES[0];
  const holdings = brokerage.holdings || [];

  return (
    <Screen theme={theme} padBottom={40}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "18px 20px 12px",
        }}
      >
        <button
          onClick={onBack}
          style={{
            width: 36,
            height: 36,
            borderRadius: 18,
            background: "transparent",
            border: `0.5px solid ${theme.line2}`,
            color: theme.text,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Ico.chevL size={14} />
        </button>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            letterSpacing: 1.5,
            textTransform: "uppercase",
            color: theme.textMute,
          }}
        >
          Trading account
        </div>
        <div style={{ width: 36 }} />
      </div>

      <div style={{ padding: "0 22px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <BrandLogo name={brokerage.name} size={42} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 24,
                color: theme.text,
                letterSpacing: -0.5,
                lineHeight: 1.1,
              }}
            >
              {brokerage.name}
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: "0 16px 14px" }}>
        <Card
          theme={theme}
          style={{
            padding: 20,
            background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 90%)`,
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "flex-start",
              gap: 12,
            }}
          >
            <div>
              <SectionLabel theme={theme}>Portfolio value</SectionLabel>
              <BigNumber
                value={brokerage.portfolio}
                theme={theme}
                accent={accent}
                size={32}
              />
            </div>
            <div style={{ textAlign: "right", paddingTop: 2 }}>
              <div
                style={{
                  fontFamily: FONTS.mono,
                  fontSize: 10,
                  color: theme.textMute,
                  letterSpacing: 1,
                  textTransform: "uppercase",
                }}
              >
                Today
              </div>
              <Delta
                value={brokerage.pnlDay}
                pct={brokerage.pnlPct}
                theme={theme}
                size={12}
              />
            </div>
          </div>
        </Card>
      </div>

      <div style={{ padding: "0 22px 10px" }}>
        <SectionLabel theme={theme}>Holdings</SectionLabel>
      </div>
      <div style={{ padding: "0 16px 18px" }}>
        <Card theme={theme} padded={false} style={{ overflow: "hidden" }}>
          {holdings.map((holding, i) => (
            <BrokerageHoldingRow
              key={holding.sym + i}
              holding={holding}
              portfolio={brokerage.portfolio}
              theme={theme}
              last={i === holdings.length - 1}
            />
          ))}
        </Card>
      </div>
    </Screen>
  );
}

function CryptoDetailScreen({ theme, accent, cryptoAccountId, onBack }) {
  const cryptoAccounts =
    typeof CRYPTO_ACCOUNTS !== "undefined" ? CRYPTO_ACCOUNTS : [];
  const fallbackAccount = {
    id: "crypto-direct",
    name: "Crypto holdings",
    kind: "Ungrouped",
    holdings: CRYPTO,
  };
  const account =
    cryptoAccounts.find((a) => a.id === cryptoAccountId) ||
    cryptoAccounts[0] ||
    fallbackAccount;
  const holdings = account.holdings || [];
  const total = holdings.reduce((s, h) => s + h.value, 0);
  const weighted24h = total
    ? holdings.reduce((s, h) => s + h.value * (h.pnl24 || 0), 0) / total
    : 0;
  const isWallet = account.name.startsWith("0x");

  return (
    <Screen theme={theme} padBottom={40}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "18px 20px 12px",
        }}
      >
        <button
          onClick={onBack}
          style={{
            width: 36,
            height: 36,
            borderRadius: 18,
            background: "transparent",
            border: `0.5px solid ${theme.line2}`,
            color: theme.text,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Ico.chevL size={14} />
        </button>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            letterSpacing: 1.5,
            textTransform: "uppercase",
            color: theme.textMute,
          }}
        >
          {isWallet ? "Crypto wallet" : "Crypto account"}
        </div>
        <div style={{ width: 36 }} />
      </div>

      <div style={{ padding: "0 22px 16px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <CryptoAccountIcon
            account={account}
            theme={theme}
            accent={accent}
            size={42}
          />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 24,
                color: theme.text,
                letterSpacing: -0.5,
                lineHeight: 1.1,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {account.name}
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: "0 16px 14px" }}>
        <Card
          theme={theme}
          style={{
            padding: 20,
            background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 90%)`,
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "flex-start",
              gap: 12,
            }}
          >
            <div>
              <SectionLabel theme={theme}>Total value</SectionLabel>
              <BigNumber
                value={total}
                theme={theme}
                accent={accent}
                size={32}
              />
            </div>
            <div style={{ textAlign: "right", paddingTop: 2 }}>
              <div
                style={{
                  fontFamily: FONTS.mono,
                  fontSize: 10,
                  color: theme.textMute,
                  letterSpacing: 1,
                  textTransform: "uppercase",
                }}
              >
                24h
              </div>
              <Delta
                value={weighted24h}
                pct={weighted24h}
                theme={theme}
                size={12}
              />
            </div>
          </div>
        </Card>
      </div>

      <div style={{ padding: "0 22px 10px" }}>
        <SectionLabel theme={theme}>Holdings</SectionLabel>
      </div>
      <div style={{ padding: "0 16px 18px" }}>
        <Card theme={theme} padded={false} style={{ overflow: "hidden" }}>
          {holdings.map((holding, i) => (
            <CryptoDetailHoldingRow
              key={holding.id || holding.symbol + i}
              holding={holding}
              total={total}
              theme={theme}
              last={i === holdings.length - 1}
            />
          ))}
        </Card>
      </div>
    </Screen>
  );
}

function BrokerageHoldingRow({ holding, portfolio, theme, last }) {
  const share = portfolio ? (holding.value / portfolio) * 100 : 0;
  return (
    <Row
      theme={theme}
      last={last}
      left={<TickerBadge symbol={holding.sym} theme={theme} />}
      title={holding.sym}
      subtitle={holding.name}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}
        >
          <Dh /> {fmtAED(holding.value)}
        </span>
      }
      rightBottom={
        <span
          style={{
            fontFamily: FONTS.mono,
            fontSize: 11,
            color: theme.textMute,
          }}
        >
          {share.toFixed(1)}%
        </span>
      }
    />
  );
}

function CryptoDetailHoldingRow({ holding, total, theme, last }) {
  const share = total ? (holding.value / total) * 100 : 0;
  return (
    <Row
      theme={theme}
      last={last}
      left={<CoinBadge symbol={holding.symbol} theme={theme} />}
      title={holding.symbol}
      subtitle={`${holding.name} · ${holding.qty} ${holding.symbol}`}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}
        >
          <Dh /> {fmtAED(holding.value)}
        </span>
      }
      rightBottom={
        <span
          style={{
            fontFamily: FONTS.mono,
            fontSize: 11,
            color: theme.textMute,
          }}
        >
          {share.toFixed(1)}%
        </span>
      }
    />
  );
}

function TickerBadge({ symbol, theme }) {
  const isCash = symbol === "CASH";
  return (
    <div
      style={{
        width: 36,
        height: 36,
        borderRadius: 10,
        background: isCash ? theme.surface2 : theme.surface3,
        border: `0.5px solid ${theme.line}`,
        color: isCash ? theme.textDim : theme.text,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: FONTS.mono,
        fontSize: symbol.length > 4 ? 8.5 : 10,
        fontWeight: 700,
        letterSpacing: 0.2,
        flexShrink: 0,
      }}
    >
      {symbol}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LIABILITIES BODY
// ─────────────────────────────────────────────────────────────
function LiabilitiesBody({ theme, accent, onNav, onAddLiability }) {
  const [open, setOpen] = React.useState({
    mortgages: LIABILITIES.mortgages.length > 0,
    loans: LIABILITIES.mortgages.length === 0 && LIABILITIES.loans.length > 0,
    cards:
      LIABILITIES.mortgages.length === 0 &&
      LIABILITIES.loans.length === 0 &&
      LIABILITIES.credit_cards.length > 0,
  });
  const [mortgageItems, setMortgageItems] = React.useState(() =>
    LIABILITIES.mortgages.map((m) => ({ ...m })),
  );
  const [loanItems, setLoanItems] = React.useState(() =>
    LIABILITIES.loans.map((l) => ({ ...l })),
  );
  const [liabilityEditor, setLiabilityEditor] = React.useState(null);
  const toggle = (k) => setOpen((o) => ({ ...o, [k]: !o[k] }));
  const goDetail = (kind, id, item) =>
    onNav &&
    onNav("liability_detail", {
      liabilityKind: kind,
      liabilityId: id,
      liabilityItem: item,
    });
  const mortgageTotal = mortgageItems.reduce((s, m) => s + m.balance, 0);
  const loanTotal = loanItems.reduce((s, l) => s + l.balance, 0);
  const cardTotal = LIABILITIES.credit_cards.reduce((s, c) => s + c.balance, 0);
  const liabilitiesTotal = mortgageTotal + loanTotal + cardTotal;

  const saveLiabilityEdit = (updated) => {
    if (!liabilityEditor) return;
    if (liabilityEditor.kind === "mortgage") {
      setMortgageItems((items) =>
        items.map((item) => (item.id === updated.id ? updated : item)),
      );
    } else {
      setLoanItems((items) =>
        items.map((item) => (item.id === updated.id ? updated : item)),
      );
    }
    setLiabilityEditor(null);
  };
  const deleteMortgage = (id) =>
    setMortgageItems((items) => items.filter((item) => item.id !== id));
  const deleteLoan = (id) =>
    setLoanItems((items) => items.filter((item) => item.id !== id));

  return (
    <>
      {/* Total owed card with paydown trend */}
      <div style={{ padding: "0 16px 16px" }}>
        <Card theme={theme} style={{ padding: 18, border: "none" }}>
          <SectionLabel theme={theme}>Total owed</SectionLabel>
          <BigNumber
            value={liabilitiesTotal}
            theme={theme}
            accent={theme.text}
            size={30}
          />
          <div style={{ marginTop: 14 }}>
            <Spark
              data={LIABILITIES_TREND}
              width={300}
              height={48}
              color={accent}
              responsive
            />
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                fontFamily: FONTS.mono,
                fontSize: 9,
                color: theme.textMute,
                marginTop: 4,
                letterSpacing: 0.5,
              }}
            >
              <span>MAY '25</span>
              <span>APR '26</span>
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <WealthAddButton
              theme={theme}
              label="Add liabilities"
              onClick={onAddLiability}
            />
          </div>
        </Card>
      </div>

      {/* Mortgages */}
      <AssetSection
        title="Mortgages"
        total={mortgageTotal}
        parentTotal={liabilitiesTotal}
        open={open.mortgages}
        onToggle={() => toggle("mortgages")}
        theme={theme}
      >
        <LiabilitySectionList theme={theme}>
          {mortgageItems.map((m) => {
            const property = REAL_ESTATE.find((r) => r.id === m.propertyId);
            return (
              <DebtCard
                key={m.id}
                theme={theme}
                accent={accent}
                onSeeDetails={() => goDetail("mortgage", m.id, m)}
                title={m.lender}
                subtitle={`${property ? property.name : "Property"} · ${m.term}`}
                balance={m.balance}
                balanceCompact
                apr={m.apr}
                originalAmount={m.originalAmount}
                monthlyPayment={m.monthlyPayment}
              />
            );
          })}
          {!mortgageItems.length && (
            <EmptyManualState theme={theme} label="No mortgages added." />
          )}
        </LiabilitySectionList>
      </AssetSection>

      {/* Loans */}
      <AssetSection
        title="Loans"
        total={loanTotal}
        parentTotal={liabilitiesTotal}
        open={open.loans}
        onToggle={() => toggle("loans")}
        theme={theme}
      >
        <LiabilitySectionList theme={theme}>
          {loanItems.map((l) => (
            <DebtCard
              key={l.id}
              theme={theme}
              accent={accent}
              onSeeDetails={() => goDetail("loan", l.id, l)}
              onEdit={() => setLiabilityEditor({ kind: "loan", item: l })}
              onDelete={() => deleteLoan(l.id)}
              title={l.lender}
              subtitle={`${LOAN_KIND_LABELS[l.kind] || ""} · ${l.term}`}
              balance={l.balance}
              apr={l.apr}
              originalAmount={l.originalAmount}
              monthlyPayment={l.monthlyPayment}
            />
          ))}
          {!loanItems.length && (
            <EmptyManualState theme={theme} label="No loans added." />
          )}
        </LiabilitySectionList>
      </AssetSection>

      {/* Credit cards */}
      <AssetSection
        title="Credit cards"
        total={cardTotal}
        parentTotal={liabilitiesTotal}
        open={open.cards}
        onToggle={() => toggle("cards")}
        theme={theme}
      >
        <LiabilitySectionList theme={theme}>
          {LIABILITIES.credit_cards.map((c) => (
            <CreditCardItem
              key={c.id}
              c={c}
              theme={theme}
              accent={accent}
              onSeeDetails={() => goDetail("card", c.id, c)}
            />
          ))}
        </LiabilitySectionList>
      </AssetSection>
      <AecbFakeDoorCTA
        theme={theme}
        accent={accent}
        onClick={() => onNav && onNav("chat")}
      />
      {liabilityEditor && (
        <EditLiabilitySheet
          editor={liabilityEditor}
          theme={theme}
          accent={accent}
          onClose={() => setLiabilityEditor(null)}
          onSave={saveLiabilityEdit}
          onDelete={(id) => {
            if (liabilityEditor.kind === "mortgage") deleteMortgage(id);
            else deleteLoan(id);
            setLiabilityEditor(null);
          }}
        />
      )}
    </>
  );
}

function LiabilitySectionList({ theme, children }) {
  return (
    <div
      style={{
        padding: 14,
        display: "flex",
        flexDirection: "column",
        gap: 10,
        background: theme.surface2,
      }}
    >
      {children}
    </div>
  );
}

// Shared "See details" link used in the top-right of every liability card.
function SeeDetailsLink({ onClick, theme }) {
  return (
    <button
      onClick={onClick}
      style={{
        background: "transparent",
        border: "none",
        padding: 0,
        cursor: "pointer",
        fontFamily: FONTS.ui,
        fontSize: 11.5,
        color: theme.textDim,
        display: "flex",
        alignItems: "center",
        gap: 2,
        whiteSpace: "nowrap",
      }}
    >
      See details <Ico.chevR size={11} />
    </button>
  );
}

// Mortgage / loan card — shared layout (header, 3-column stats, paid-down bar).
function DebtCard({
  theme,
  accent,
  onSeeDetails,
  onEdit,
  onDelete,
  title,
  subtitle,
  balance,
  balanceCompact = false,
  apr,
  originalAmount,
  monthlyPayment,
}) {
  const paid = originalAmount - balance;
  const paidPct = Math.max(0, Math.min(100, (paid / originalAmount) * 100));
  return (
    <Card theme={theme} style={{ padding: 16 }}>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-start",
          gap: 12,
        }}
      >
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, color: theme.text, fontWeight: 500 }}>
            {title}
          </div>
          <div
            style={{
              fontSize: 11,
              color: theme.textMute,
              fontFamily: FONTS.mono,
              marginTop: 2,
            }}
          >
            {subtitle}
          </div>
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            flexShrink: 0,
          }}
        >
          <SeeDetailsLink onClick={onSeeDetails} theme={theme} />
          {onEdit && onDelete && (
            <ManualItemActions
              theme={theme}
              onEdit={onEdit}
              onDelete={onDelete}
            />
          )}
        </div>
      </div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "flex-end",
          marginTop: 10,
        }}
      >
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 18,
            color: theme.text,
            fontVariantNumeric: "tabular-nums",
          }}
        >
          <Dh />{" "}
          {fmtAED(balance, balanceCompact ? { compact: true } : undefined)}
        </div>
        <div
          style={{ fontSize: 11, fontFamily: FONTS.mono, color: theme.textDim }}
        >
          {apr.toFixed(2)}% APR
        </div>
      </div>
      <div
        style={{
          marginTop: 12,
          display: "grid",
          gridTemplateColumns: "1fr 1fr 1fr",
          gap: 10,
          fontFamily: FONTS.mono,
          fontSize: 10.5,
        }}
      >
        <AssetStat
          label="Original"
          value={`${fmtAED(originalAmount, { compact: true })}`}
          theme={theme}
        />
        <AssetStat
          label="Paid down"
          value={`${fmtAED(paid, { compact: true })}`}
          theme={theme}
          accent={theme.positive}
        />
        <AssetStat
          label="Monthly"
          value={`${fmtAED(monthlyPayment)}`}
          theme={theme}
        />
      </div>
      <div
        style={{
          marginTop: 10,
          height: 4,
          borderRadius: 2,
          background: theme.surface2,
          overflow: "hidden",
        }}
      >
        <div
          style={{
            height: "100%",
            width: `${paidPct}%`,
            background: theme.positive,
          }}
        />
      </div>
    </Card>
  );
}

function AecbFakeDoorCTA({ theme, accent, onClick }) {
  return (
    <div style={{ padding: "0 16px 14px" }}>
      <button
        type="button"
        onClick={onClick}
        style={{
          width: "100%",
          background: `${accent}10`,
          border: `0.5px solid ${accent}45`,
          borderRadius: 18,
          padding: "15px 16px",
          color: theme.text,
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          gap: 12,
          textAlign: "left",
        }}
      >
        <div
          style={{
            width: 34,
            height: 34,
            borderRadius: 17,
            background: `${accent}18`,
            color: accent,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
          }}
        >
          <Ico.shield size={16} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 13.5,
              fontWeight: 600,
              color: theme.text,
            }}
          >
            Learn your AECB credit score now
          </div>
        </div>
        <Ico.chevR size={14} stroke={theme.textMute} />
      </button>
    </div>
  );
}

function EditLiabilitySheet({
  editor,
  theme,
  accent,
  onClose,
  onSave,
  onDelete,
}) {
  const [form, setForm] = React.useState(() => ({ ...editor.item }));

  React.useEffect(() => {
    setForm({ ...editor.item });
  }, [editor]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const cleanMoney = (v) => String(v).replace(/[^0-9]/g, "");
  const cleanRate = (v) => String(v).replace(/[^0-9.]/g, "");
  const title = editor.kind === "mortgage" ? "Edit mortgage" : "Edit loan";
  const canSave = form.lender && Number(form.balance) > 0;

  const save = () => {
    onSave({
      ...editor.item,
      ...form,
      balance: Number(form.balance) || 0,
      originalAmount: Number(form.originalAmount) || 0,
      apr: Number(form.apr) || 0,
      monthlyPayment: Number(form.monthlyPayment) || 0,
    });
  };

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 80,
        display: "flex",
        alignItems: "flex-end",
        background: "rgba(0,0,0,0.45)",
      }}
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          maxHeight: "82%",
          overflowY: "auto",
          background: theme.surface,
          borderRadius: "24px 24px 0 0",
          borderTop: `0.5px solid ${theme.line2}`,
          padding: "10px 20px 34px",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 12,
          }}
        >
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 22,
              color: theme.text,
              letterSpacing: -0.4,
            }}
          >
            {title}
          </div>
          <IconActionButton
            label="Delete"
            icon="trash"
            theme={theme}
            tone={theme.negative}
            onClick={() => onDelete(editor.item.id)}
          />
        </div>

        <div style={{ marginTop: 16 }}>
          <EditField theme={theme} label="Lender">
            <input
              value={form.lender || ""}
              onChange={(e) => set("lender", e.target.value)}
              placeholder="Mashreq"
              style={editInputStyle(theme)}
            />
          </EditField>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            <EditField theme={theme} label="Outstanding (AED)">
              <input
                value={form.balance || ""}
                onChange={(e) => set("balance", cleanMoney(e.target.value))}
                inputMode="numeric"
                placeholder="460000"
                style={editInputStyle(theme)}
              />
            </EditField>
            <EditField theme={theme} label="Original (AED)">
              <input
                value={form.originalAmount || ""}
                onChange={(e) =>
                  set("originalAmount", cleanMoney(e.target.value))
                }
                inputMode="numeric"
                placeholder="480000"
                style={editInputStyle(theme)}
              />
            </EditField>
          </div>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            <EditField theme={theme} label="APR %">
              <input
                value={form.apr || ""}
                onChange={(e) => set("apr", cleanRate(e.target.value))}
                inputMode="decimal"
                placeholder="4.50"
                style={editInputStyle(theme)}
              />
            </EditField>
            <EditField theme={theme} label="Monthly (AED)">
              <input
                value={form.monthlyPayment || ""}
                onChange={(e) =>
                  set("monthlyPayment", cleanMoney(e.target.value))
                }
                inputMode="numeric"
                placeholder="2840"
                style={editInputStyle(theme)}
              />
            </EditField>
          </div>
          <div
            style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}
          >
            <EditField theme={theme} label="Term">
              <input
                value={form.term || ""}
                onChange={(e) => set("term", e.target.value)}
                placeholder={
                  editor.kind === "mortgage" ? "25 years" : "4 years"
                }
                style={editInputStyle(theme)}
              />
            </EditField>
            <EditField theme={theme} label="Started">
              <input
                value={form.originationDate || ""}
                onChange={(e) => set("originationDate", e.target.value)}
                placeholder="May 2024"
                style={editInputStyle(theme)}
              />
            </EditField>
          </div>
        </div>

        <button
          type="button"
          onClick={save}
          disabled={!canSave}
          style={{
            marginTop: 22,
            width: "100%",
            background: canSave ? accent : theme.surface3,
            color: canSave ? theme.bg : theme.textMute,
            border: "none",
            borderRadius: 14,
            padding: "14px",
            fontFamily: FONTS.ui,
            fontSize: 14,
            fontWeight: 600,
            cursor: canSave ? "pointer" : "not-allowed",
          }}
        >
          Save changes
        </button>
      </div>
    </div>
  );
}

function DeleteManualAssetConfirmSheet({
  request,
  theme,
  onCancel,
  onConfirm,
}) {
  const item = request.item || {};
  const isRealEstate = request.kind === "realestate";
  return (
    <div
      onClick={onCancel}
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 120,
        background: "rgba(0,0,0,0.6)",
        display: "flex",
        alignItems: "flex-end",
        animation: "himma-fade 200ms",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          background: theme.surface,
          borderRadius: "24px 24px 0 0",
          borderTop: `0.5px solid ${theme.line2}`,
          padding: "10px 20px 28px",
          animation: "himma-slide 260ms cubic-bezier(.2,.8,.25,1)",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>

        <div
          style={{
            width: 48,
            height: 48,
            borderRadius: 24,
            margin: "4px auto 14px",
            background: `${theme.negative}18`,
            color: theme.negative,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Ico.trash size={21} />
        </div>

        <div
          style={{
            fontFamily: FONTS.display,
            fontSize: 20,
            color: theme.text,
            letterSpacing: -0.3,
            textAlign: "center",
          }}
        >
          Delete this {isRealEstate ? "property" : "valuable"}?
        </div>
        <div
          style={{
            fontSize: 13,
            color: theme.textDim,
            marginTop: 10,
            lineHeight: 1.5,
            textAlign: "center",
            padding: "0 6px",
          }}
        >
          <b style={{ color: theme.text }}>{item.name}</b> will be removed from
          your manual assets and total wealth.
        </div>

        <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
          <button
            type="button"
            onClick={onCancel}
            style={{
              flex: 1,
              background: "transparent",
              border: `0.5px solid ${theme.line2}`,
              borderRadius: 14,
              padding: "13px",
              color: theme.text,
              fontFamily: FONTS.ui,
              fontSize: 13.5,
              fontWeight: 500,
              cursor: "pointer",
            }}
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={onConfirm}
            style={{
              flex: 1,
              background: theme.negative,
              border: "none",
              borderRadius: 14,
              padding: "13px",
              color: "#fff",
              fontFamily: FONTS.ui,
              fontSize: 13.5,
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  );
}

// Credit card item — summary only; details live on the detail page.
function CreditCardItem({ c, theme, accent, onSeeDetails }) {
  return (
    <Card theme={theme} style={{ padding: 14 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <BrandLogo name={c.issuer} size={36} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 8,
            }}
          >
            <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500 }}>
              {c.issuer}
            </div>
            <SeeDetailsLink onClick={onSeeDetails} theme={theme} />
          </div>
          <div
            style={{
              fontSize: 11,
              color: theme.textMute,
              fontFamily: FONTS.mono,
              marginTop: 2,
            }}
          >
            {c.last}
          </div>
        </div>
      </div>
    </Card>
  );
}

function AssetSection({
  title,
  total,
  open,
  onToggle,
  theme,
  children,
  parentTotal,
}) {
  const denom = parentTotal || NET_WORTH || 1;
  return (
    <div style={{ padding: "0 16px 12px" }}>
      <button
        onClick={onToggle}
        style={{
          width: "100%",
          background: theme.surface,
          border: `0.5px solid ${theme.line}`,
          borderRadius: open ? "18px 18px 0 0" : 18,
          padding: "14px 16px",
          display: "flex",
          alignItems: "center",
          gap: 12,
          cursor: "pointer",
          color: theme.text,
          textAlign: "left",
        }}
      >
        <div
          style={{
            flex: 1,
            display: "flex",
            flexDirection: "column",
            gap: 2,
            minWidth: 0,
          }}
        >
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 14,
              fontWeight: 500,
              color: theme.text,
            }}
          >
            {title}
          </div>
        </div>
        <div style={{ textAlign: "right", flexShrink: 0, marginLeft: 12 }}>
          <div
            style={{
              fontFamily: FONTS.mono,
              fontSize: 14,
              color: theme.text,
              whiteSpace: "nowrap",
            }}
          >
            <Dh /> {fmtAED(total, { compact: total > 10000 })}
          </div>
          <div
            style={{
              fontFamily: FONTS.mono,
              fontSize: 10,
              color: theme.textMute,
              marginTop: 2,
            }}
          >
            {((total / denom) * 100).toFixed(1)}%
          </div>
        </div>
        <div
          style={{
            marginLeft: 8,
            color: theme.textDim,
            transform: open ? "rotate(90deg)" : "",
            transition: "transform 160ms",
          }}
        >
          <Ico.chevR size={14} />
        </div>
      </button>
      {open && (
        <div
          style={{
            background: theme.surface,
            borderLeft: `0.5px solid ${theme.line}`,
            borderRight: `0.5px solid ${theme.line}`,
            borderBottom: `0.5px solid ${theme.line}`,
            borderRadius: "0 0 18px 18px",
            overflow: "hidden",
          }}
        >
          {children}
        </div>
      )}
    </div>
  );
}

// Sub-region (UAE / International) inside Bank accounts.
function SubRegion({ theme, label, total, count, children }) {
  return (
    <div style={{ borderTop: `0.5px solid ${theme.line}` }}>
      <div
        style={{
          width: "100%",
          background: theme.surface2,
          padding: "10px 18px",
          display: "flex",
          alignItems: "center",
          gap: 8,
          color: theme.text,
          textAlign: "left",
        }}
      >
        <div
          style={{
            flex: 1,
            fontFamily: FONTS.mono,
            fontSize: 9.5,
            letterSpacing: 1.2,
            textTransform: "uppercase",
            color: theme.textMute,
          }}
        >
          {label} · {count}
        </div>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 11.5,
            color: theme.textDim,
            whiteSpace: "nowrap",
          }}
        >
          <Dh /> {fmtAED(total, { compact: total > 10000 })}
        </div>
      </div>
      <div>{children}</div>
    </div>
  );
}

function BankRow({ b, theme, accent }) {
  return (
    <Row
      theme={theme}
      left={<BrandLogo name={b.bank} size={36} />}
      title={b.bank}
      subtitle={`${b.type} · ${b.last}`}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}
        >
          <Dh /> {fmtAED(b.balance)}
        </span>
      }
    />
  );
}

function CryptoAccountGroup({ account, theme, accent, onOpen, last }) {
  const total = account.holdings.reduce((s, h) => s + h.value, 0);

  return (
    <Row
      theme={theme}
      onClick={onOpen}
      chevron
      last={last}
      left={
        <CryptoAccountIcon account={account} theme={theme} accent={accent} />
      }
      title={account.name}
      subtitle={`${account.kind} · ${account.holdings.length} holdings`}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}
        >
          <Dh /> {fmtAED(total, { compact: total > 10000 })}
        </span>
      }
      rightBottom={
        <span
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            color: theme.textMute,
          }}
        >
          {((total / Math.max(1, ASSETS_TOTAL)) * 100).toFixed(1)}% assets
        </span>
      }
    />
  );
}

function CryptoAccountIcon({ account, theme, accent, size = 36 }) {
  const isWallet = account.name.startsWith("0x");
  if (!isWallet) return <BrandLogo name={account.name} size={size} />;

  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: Math.max(10, Math.round(size * 0.28)),
        background: theme.surface2,
        color: accent,
        border: `0.5px solid ${theme.line}`,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexShrink: 0,
      }}
    >
      <Ico.wallet size={Math.round(size * 0.44)} />
    </div>
  );
}

function CryptoHoldingRow({ holding, theme, last }) {
  return (
    <Row
      theme={theme}
      last={last}
      left={<CoinBadge symbol={holding.symbol} theme={theme} />}
      title={holding.name}
      subtitle={`${holding.qty} ${holding.symbol}`}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 14, color: theme.text }}
        >
          <Dh /> {fmtAED(holding.value)}
        </span>
      }
      rightBottom={
        holding.pnl24 === 0 ? (
          <span
            style={{
              fontFamily: FONTS.mono,
              fontSize: 11,
              color: theme.textMute,
            }}
          >
            flat 24h
          </span>
        ) : (
          <Delta
            pct={holding.pnl24}
            value={holding.pnl24}
            theme={theme}
            size={11}
          />
        )
      }
    />
  );
}

function Row({
  left,
  title,
  subtitle,
  rightTop,
  rightBottom,
  theme,
  onClick,
  chevron,
  last,
}) {
  const Tag = onClick ? "button" : "div";
  return (
    <Tag
      onClick={onClick}
      style={{
        width: "100%",
        background: "transparent",
        border: "none",
        textAlign: "left",
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "12px 16px",
        borderBottom: last ? "none" : `0.5px solid ${theme.line}`,
        cursor: onClick ? "pointer" : "default",
        color: theme.text,
      }}
    >
      {left}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{
            fontSize: 13.5,
            color: theme.text,
            fontWeight: 500,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {title}
        </div>
        <div
          style={{
            fontSize: 11,
            color: theme.textMute,
            fontFamily: FONTS.mono,
            marginTop: 2,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {subtitle}
        </div>
      </div>
      <div
        style={{
          textAlign: "right",
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-end",
          gap: 3,
          flexShrink: 0,
          minWidth: 90,
        }}
      >
        <div style={{ whiteSpace: "nowrap" }}>{rightTop}</div>
        {rightBottom && (
          <div style={{ whiteSpace: "nowrap" }}>{rightBottom}</div>
        )}
      </div>
      {chevron && <Ico.chevR size={13} stroke={theme.textMute} />}
    </Tag>
  );
}

function CoinBadge({ symbol, theme }) {
  const colors = {
    BTC: "#F7931A",
    ETH: "#627EEA",
    SOL: "#9945FF",
    USDC: "#2775CA",
  };
  const color = colors[symbol] || "#6B7280";
  return (
    <div
      style={{
        width: 36,
        height: 36,
        borderRadius: 18,
        background: color + "25",
        border: `0.5px solid ${color + "55"}`,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: FONTS.mono,
        fontSize: 10,
        color,
        fontWeight: 600,
        flexShrink: 0,
        letterSpacing: 0.2,
      }}
    >
      {symbol}
    </div>
  );
}

function AssetStat({ label, value, theme, accent }) {
  return (
    <div>
      <div
        style={{
          fontSize: 9.5,
          color: theme.textMute,
          textTransform: "uppercase",
          letterSpacing: 1,
        }}
      >
        {label}
      </div>
      <div
        style={{
          fontSize: 12,
          color: accent || theme.text,
          marginTop: 2,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        <Dh /> {value}
      </div>
    </div>
  );
}

Object.assign(window, {
  AssetsScreen,
  BrokerageDetailScreen,
  CryptoDetailScreen,
});
