// Investments — portfolio market intelligence and risk surface

const INVESTMENT_IMPACT_CARDS = [
  {
    tone: "negative",
    label: "High Negative Impact",
    headline:
      "Global supply chain disruptions impact defense and aerospace sectors",
    tickers: ["LMT", "RTX", "BA"],
  },
  {
    tone: "positive",
    label: "Medium Positive Impact",
    headline: "AI infrastructure spending lifts semiconductor outlook",
    tickers: ["NVDA", "AMD", "TSM"],
  },
  {
    tone: "negative",
    label: "Moderate Negative Impact",
    headline: "Crude price volatility pressures transport and utilities",
    tickers: ["DAL", "UPS", "DUK"],
  },
];

const PORTFOLIO_RISKS = [
  {
    label: "Asset class",
    value: "90% Equities",
    description:
      "Our system evaluates the proportion of the portfolio held in stocks. When this number exceeds a certain threshold, we flag it to indicate an increased vulnerability to stock market corrections, emphasizing the importance of balancing with fixed-income assets.",
    status: "warning",
  },
  {
    label: "Geography",
    value: "High US Concentration",
    description:
      "Identifies the regional footprint of the portfolio's assets. A high concentration warning is triggered when investments are too localized, illustrating a lack of global diversification that could otherwise protect against country-specific risks.",
  },
  {
    label: "Sector",
    value: "Heavy Energy Exposure",
    description:
      "By evaluating industry allocations, the system identifies if a portfolio is overly reliant on a single sector's performance. Highlighting this exposure helps identify sector-specific risks, encouraging a spread across non-correlated industries to smooth out returns.",
  },
  {
    label: "Liquidity",
    value: "Healthy",
    description:
      "This metric analyzes the trading volume and market accessibility of the held assets. We display a positive liquidity rating when the majority of the portfolio can be efficiently liquidated, meaning cash can be accessed quickly during market stress or emergencies.",
    status: "healthy",
  },
];

const PORTFOLIO_ALLOCATION_COLORS = {
  ETF: "#9DD6C8",
  Stocks: "#8CB7FF",
  Crypto: "#F2C36B",
  Cash: "#D9DDE5",
};

const INVESTMENT_CHART_FILTERS = ["1W", "1M", "3M", "6M", "YTD", "1Y"];

const INVESTMENT_CHART_TRENDS = {
  "1W": [34, 35, 33, 36, 37, 36, 39],
  "1M": [20, 23, 21, 26, 24, 31, 35, 32, 37, 41, 39, 46, 50, 54, 58],
  "3M": [32, 34, 31, 38, 36, 42, 40, 46, 45, 49, 53, 50, 57, 60, 64],
  "6M": [30, 28, 33, 36, 35, 40, 43, 39, 46, 48, 52, 51, 55, 59, 63],
  YTD: [29, 33, 35, 32, 39, 42, 45, 43, 48, 50, 54, 56, 59, 62, 66],
  "1Y": [24, 27, 25, 31, 34, 37, 35, 42, 45, 44, 51, 55, 58, 63, 69],
};

const STOCK_LOGOS = {
  AAPL: { initials: "A", bg: "#1D1D1F" },
  AMZN: { initials: "a", bg: "#FF9900" },
  "BRK.B": { initials: "B", bg: "#3A3A3A" },
  COIN: { initials: "C", bg: "#0052FF" },
  BTC: { initials: "B", bg: "#F7931A" },
  ETH: { initials: "E", bg: "#627EEA" },
  GOOGL: { initials: "G", bg: "#4285F4" },
  IEMG: { initials: "iS", bg: "#111827" },
  META: { initials: "M", bg: "#0668E1" },
  MSFT: { initials: "M", bg: "#00A4EF" },
  NVDA: { initials: "N", bg: "#76B900" },
  PLTR: { initials: "P", bg: "#111111" },
  QQQ: { initials: "Q", bg: "#7B3FF2" },
  SPY: { initials: "S", bg: "#1E5AA8" },
  TSLA: { initials: "T", bg: "#CC0000" },
  VWRL: { initials: "V", bg: "#B21F2D" },
};

const HOLDING_DAILY_TRENDS = {
  AAPL: [22, 23, 23, 22, 24, 24, 25],
  AMZN: [20, 21, 20, 22, 22, 23, 23],
  "BRK.B": [22, 22, 23, 22, 23, 23, 23],
  COIN: [29, 27, 28, 26, 25, 24, 23],
  GOOGL: [24, 23, 24, 24, 25, 24, 25],
  IEMG: [24, 23, 24, 23, 23, 22, 22],
  META: [29, 28, 28, 27, 26, 26, 25],
  MSFT: [20, 21, 22, 22, 23, 24, 25],
  NVDA: [19, 22, 21, 25, 27, 29, 32],
  PLTR: [21, 22, 21, 23, 24, 23, 25],
  QQQ: [28, 27, 28, 27, 26, 25, 25],
  SPY: [27, 27, 26, 26, 25, 25, 24],
  TSLA: [23, 22, 24, 23, 25, 26, 27],
  VWRL: [20, 21, 21, 22, 23, 23, 25],
};

const POPULAR_HOLDINGS = [
  { symbol: "AAPL", name: "Apple Inc.", price: 212.93 },
  { symbol: "NVDA", name: "NVIDIA Corp.", price: 924.79 },
  { symbol: "AMZN", name: "Amazon.com Inc.", price: 186.51 },
];

const POPULAR_CRYPTO_HOLDINGS = [
  { symbol: "BTC", name: "Bitcoin", price: 98420 },
  { symbol: "ETH", name: "Ethereum", price: 3420 },
];

const MANUAL_ACCOUNT_ID = "manual-tracking-account";
const MANUAL_ACCOUNT_NAME = "Manual tracking account";

function fmtUSD(value) {
  return `$${Number(value).toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
}

function themeRadius(theme, key, fallback) {
  return theme.radius?.[key] ?? fallback;
}

function cardSurfaceStyle(theme, overrides = {}) {
  const card = theme.components?.compactCard || theme.components?.card || {};
  return {
    borderRadius: card.radius ?? themeRadius(theme, "lg", 18),
    border: `0.5px solid ${card.border || theme.line}`,
    background: card.bg || theme.surface,
    ...overrides,
  };
}

function translucentSurface(theme, color, opacity) {
  return alpha(color, opacity);
}

function getToneColor(theme, tone) {
  if (tone === "positive" || tone === "healthy") return theme.positive;
  if (tone === "negative") return theme.negative;
  if (tone === "warning") return theme.warning;
  return theme.textDim;
}

function textActionStyle(theme, overrides = {}) {
  return {
    border: "none",
    background: "transparent",
    color: theme.text,
    fontFamily: FONTS.ui,
    fontSize: 12.5,
    fontWeight: 500,
    cursor: "pointer",
    ...overrides,
  };
}

function secondaryButtonStyle(theme, overrides = {}) {
  const button = theme.components?.secondaryButton || {};
  return {
    borderRadius: button.radius || themeRadius(theme, "md", 14),
    border: `0.5px solid ${button.border || theme.line2}`,
    background: button.bg || "transparent",
    color: button.color || theme.text,
    fontFamily: FONTS.ui,
    cursor: "pointer",
    ...overrides,
  };
}

function getSeedManualHolding() {
  return {
    sym: "AAPL",
    name: "Apple Inc.",
    value: 212.93,
    pnlPct: 0,
    quantity: 1,
    price: 212.93,
    currency: "USD",
  };
}

function getPortfolioAllocation() {
  const buckets = new Map();

  const add = (key, label, value) => {
    if (!value) return;
    const prev = buckets.get(key) || {
      key,
      label,
      value: 0,
      color: PORTFOLIO_ALLOCATION_COLORS[key],
    };
    prev.value += value;
    buckets.set(key, prev);
  };

  BROKERAGES.forEach((brokerage) => {
    brokerage.holdings.forEach((holding) => {
      if (holding.sym === "CASH") {
        add("Cash", "Cash", holding.value);
      } else if (
        /ETF|Trust|All-World|Emerging Markets|S&P 500|QQQ/i.test(holding.name)
      ) {
        add("ETF", "ETFs", holding.value);
      } else {
        add("Stocks", "Stocks", holding.value);
      }
    });
  });

  CRYPTO_ACCOUNTS.forEach((account) => {
    account.holdings.forEach((holding) => {
      add("Crypto", "Crypto", holding.value);
    });
  });

  return Array.from(buckets.values()).sort((a, b) => b.value - a.value);
}

function getAggregatedHoldings() {
  const holdings = new Map();

  BROKERAGES.forEach((brokerage) => {
    brokerage.holdings.forEach((holding) => {
      if (holding.sym === "CASH") return;

      const existing = holdings.get(holding.sym) || {
        sym: holding.sym,
        name: holding.name,
        value: 0,
        weightedPnl: 0,
      };

      existing.value += holding.value;
      existing.weightedPnl += holding.value * holding.pnlPct;
      holdings.set(holding.sym, existing);
    });
  });

  return Array.from(holdings.values()).map((holding) => ({
    ...holding,
    pnlPct: holding.value ? holding.weightedPnl / holding.value : 0,
  }));
}

function getHoldingCards() {
  const holdings = getAggregatedHoldings();
  const portfolioTotal = BROKERAGES.reduce(
    (sum, brokerage) => sum + brokerage.portfolio,
    0,
  );
  const withPortfolioMetric = (holding) => ({
    ...holding,
    metric: `${((holding.value / portfolioTotal) * 100).toFixed(1)}%`,
  });
  const withPerformanceMetric = (holding) => ({
    ...holding,
    metric: `${holding.pnlPct >= 0 ? "+" : ""}${holding.pnlPct.toFixed(1)}%`,
  });

  return [
    {
      title: "Top holdings",
      holdings: [...holdings]
        .sort((a, b) => b.value - a.value)
        .slice(0, 3)
        .map(withPortfolioMetric),
    },
    {
      title: "Top performers",
      holdings: [...holdings]
        .sort((a, b) => b.pnlPct - a.pnlPct)
        .slice(0, 3)
        .map(withPerformanceMetric),
    },
    {
      title: "Worst performers",
      holdings: [...holdings]
        .sort((a, b) => a.pnlPct - b.pnlPct)
        .slice(0, 3)
        .map(withPerformanceMetric),
    },
  ];
}

function InvestmentsScreen({ theme, accent, onNav, onAskHimma }) {
  return (
    <Screen theme={theme}>
      <AppTopbar
        theme={theme}
        accent={accent}
        onNav={onNav}
        onAskHimma={onAskHimma}
      />

      <InvestmentHero theme={theme} accent={accent} onNav={onNav} />
      <MarketImpactSection theme={theme} />
      <PortfolioRisksSection theme={theme} />
      <ProfessionalHelpCard theme={theme} accent={accent} />
    </Screen>
  );
}

function InvestmentHero({ theme, accent, onNav }) {
  const [activeRange, setActiveRange] = React.useState("1M");
  const trend =
    INVESTMENT_CHART_TRENDS[activeRange] || INVESTMENT_CHART_TRENDS["1M"];

  return (
    <section style={{ padding: "12px 16px 8px" }}>
      <div
        style={{
          padding: "10px 4px 0",
        }}
      >
        <SectionLabel theme={theme}>Portfolio</SectionLabel>
        <div
          style={{
            marginTop: 9,
            fontFamily: FONTS.ui,
            fontSize: 30,
            lineHeight: 1.12,
            fontWeight: 400,
            letterSpacing: -1,
            color: theme.text,
            fontVariantNumeric: "tabular-nums",
          }}
        >
          $142,500.00
        </div>
        <div
          style={{
            marginTop: 9,
            display: "flex",
            alignItems: "center",
            gap: 10,
          }}
        >
          <Delta value={1420.5} pct={1.01} theme={theme} size={13} />
          <span
            style={{
              fontFamily: FONTS.ui,
              fontSize: 12,
              color: theme.textDim,
              fontVariantNumeric: "tabular-nums",
            }}
          >
            +${fmtAED(1420.5, { decimals: 2 })} today
          </span>
        </div>
      </div>

      <div style={{ marginTop: 18 }}>
        <Card theme={theme}>
          <InvestmentSparkline
            color={accent}
            data={trend}
            label={`${activeRange} investment trend`}
          />
          <div
            style={{
              marginTop: 13,
              display: "grid",
              gridTemplateColumns: "repeat(6, 1fr)",
              gap: 6,
            }}
          >
            {INVESTMENT_CHART_FILTERS.map((range) => {
              const active = range === activeRange;
              return (
                <button
                  key={range}
                  type="button"
                  onClick={() => setActiveRange(range)}
                  style={{
                    minHeight: 30,
                    borderRadius: themeRadius(theme, "sm", 10),
                    border: 0,
                    background: active ? theme.text : theme.surface2,
                    color: active ? theme.bg : theme.textDim,
                    fontFamily: FONTS.ui,
                    fontSize: 10,
                    fontWeight: 500,
                    letterSpacing: 0,
                    cursor: "pointer",
                    padding: "0 4px",
                  }}
                >
                  {range}
                </button>
              );
            })}
          </div>
        </Card>
      </div>

      <HoldingsCarousel theme={theme} onNav={onNav} />
      <PortfolioAllocation theme={theme} />
    </section>
  );
}

function PortfolioAllocation({ theme }) {
  const allocation = getPortfolioAllocation();
  const total = allocation.reduce((sum, item) => sum + item.value, 0);

  return (
    <div style={{ marginTop: 18 }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 12,
          marginBottom: 10,
        }}
      >
        <SectionLabel theme={theme}>Current Allocation</SectionLabel>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 11.5,
            fontWeight: 600,
            color: theme.textDim,
          }}
        >
          By asset class
        </div>
      </div>

      <div
        style={{
          height: 9,
          display: "flex",
          overflow: "hidden",
          borderRadius: themeRadius(theme, "xs", 3),
          background: theme.line2,
        }}
      >
        {allocation.map((item) => (
          <div
            key={item.key}
            style={{
              width: `${(item.value / total) * 100}%`,
              background: item.color,
            }}
          />
        ))}
      </div>

      <div
        style={{
          marginTop: 12,
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 10,
        }}
      >
        {allocation.map((item) => {
          const pct = (item.value / total) * 100;
          return (
            <div
              key={item.key}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                minWidth: 0,
              }}
            >
              <span
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: themeRadius(theme, "xs", 3),
                  background: item.color,
                  flexShrink: 0,
                }}
              />
              <span
                style={{
                  flex: 1,
                  minWidth: 0,
                  fontFamily: FONTS.ui,
                  fontSize: 12.5,
                  fontWeight: 600,
                  color: theme.text,
                }}
              >
                {item.label}
              </span>
              <span
                style={{
                  fontFamily: FONTS.mono,
                  fontSize: 11,
                  fontWeight: 650,
                  color: theme.textDim,
                  fontVariantNumeric: "tabular-nums",
                }}
              >
                {pct.toFixed(0)}%
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function InvestmentSparkline({ color, data, label }) {
  const width = 340;
  const height = 70;
  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = max - min || 1;
  const points = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / range) * (height - 8) - 4;
    return [x, y];
  });
  const path = "M " + points.map((p) => p.join(" ")).join(" L ");
  const area = `${path} L ${width} ${height} L 0 ${height} Z`;

  return (
    <svg
      width="100%"
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      preserveAspectRatio="none"
      style={{ display: "block", overflow: "visible" }}
      aria-label={label || "Investment trend"}
    >
      <path
        d={area}
        fill={color}
        opacity={0.12}
        vectorEffect="non-scaling-stroke"
      />
      <path
        d={path}
        fill="none"
        stroke={color}
        strokeWidth={1.6}
        strokeLinecap="butt"
        strokeLinejoin="miter"
        vectorEffect="non-scaling-stroke"
      />
    </svg>
  );
}

function HoldingsCarousel({ theme, onNav }) {
  const cards = getHoldingCards();
  const openHoldings = () => onNav && onNav("investment_holdings");

  return (
    <div style={{ marginTop: 18 }}>
      <div style={{ padding: "0 4px 10px" }}>
        <SectionLabel theme={theme}>Holdings</SectionLabel>
      </div>
      <div
        style={{
          display: "flex",
          gap: 12,
          overflowX: "auto",
          padding: "0 4px 2px",
          scrollSnapType: "x mandatory",
        }}
      >
        {cards.map((card) => (
          <HoldingSummaryCard
            key={card.title}
            card={card}
            theme={theme}
            onSeeAll={openHoldings}
          />
        ))}
      </div>
    </div>
  );
}

function HoldingSummaryCard({ card, theme, onSeeAll }) {
  return (
    <article
      style={{
        minWidth: 314,
        maxWidth: 314,
        padding: "15px 14px 13px",
        scrollSnapAlign: "start",
        ...cardSurfaceStyle(theme),
      }}
    >
      <div
        style={{
          fontFamily: FONTS.ui,
          fontSize: 15,
          lineHeight: 1.2,
          fontWeight: 500,
          color: theme.text,
          marginBottom: 10,
        }}
      >
        {card.title}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {card.holdings.map((holding) => (
          <HoldingSummaryRow
            key={`${card.title}-${holding.sym}`}
            holding={holding}
            theme={theme}
          />
        ))}
      </div>
      <SeeAllHoldingsButton theme={theme} onClick={onSeeAll} />
    </article>
  );
}

function HoldingSummaryRow({ holding, theme }) {
  const positive = holding.pnlPct >= 0;
  const trend = HOLDING_DAILY_TRENDS[holding.sym] || [
    20, 21, 20, 22, 23, 22, 24,
  ];

  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "34px minmax(0, 1fr) 62px 48px",
        alignItems: "center",
        gap: 9,
        minHeight: 38,
      }}
    >
      <StockLogo symbol={holding.sym} />
      <div style={{ minWidth: 0 }}>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 13,
            fontWeight: 500,
            color: theme.text,
            lineHeight: 1.15,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {holding.sym}
        </div>
        <div
          style={{
            marginTop: 2,
            fontFamily: FONTS.ui,
            fontSize: 10.5,
            color: theme.textMute,
            lineHeight: 1.15,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {holding.name}
        </div>
      </div>
      <Spark
        data={trend}
        width={62}
        height={22}
        color={positive ? theme.positive : theme.negative}
        fill={false}
        dot={false}
      />
      <div
        style={{
          fontFamily: FONTS.ui,
          fontSize: 11.5,
          fontWeight: 550,
          color: theme.textMute,
          textAlign: "right",
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {holding.metric}
      </div>
    </div>
  );
}

function StockLogo({ symbol }) {
  const logo = STOCK_LOGOS[symbol] || {
    initials: symbol.slice(0, 2),
    bg: "#6B7280",
  };

  return (
    <div
      style={{
        width: 34,
        height: 34,
        borderRadius: 10,
        background: logo.bg,
        color: "#FFFFFF",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: FONTS.ui,
        fontSize: logo.initials.length > 1 ? 12 : 15,
        fontWeight: 750,
        letterSpacing: 0,
        flexShrink: 0,
      }}
    >
      {logo.initials}
    </div>
  );
}

function SeeAllHoldingsButton({ theme, onClick }) {
  const button = theme.components?.secondaryButton || {};
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        marginTop: 13,
        width: "100%",
        background: button.bg || "transparent",
        border: `0.5px dashed ${button.border || theme.line2}`,
        borderRadius: button.radius || themeRadius(theme, "md", 14),
        padding: "12px",
        color: button.color || theme.text,
        cursor: "pointer",
        fontFamily: FONTS.ui,
        fontSize: 12.5,
        fontWeight: 500,
      }}
    >
      See all holdings
    </button>
  );
}

function getAccountOptions(manualAccounts = []) {
  return [
    ...BROKERAGES.map((brokerage) => ({
      id: brokerage.id,
      name: brokerage.name,
      holdings: brokerage.holdings,
    })),
    ...manualAccounts,
  ];
}

function getFilteredHoldingRows(accountIds, manualAccounts = []) {
  const selectedIds = new Set(accountIds);
  const useAllAccounts = selectedIds.size === 0;
  const selectedAccounts = getAccountOptions(manualAccounts).filter(
    (account) => useAllAccounts || selectedIds.has(account.id),
  );
  const holdings = new Map();

  selectedAccounts.forEach((account) => {
    account.holdings.forEach((holding) => {
      if (holding.sym === "CASH") return;

      const existing = holdings.get(holding.sym) || {
        sym: holding.sym,
        name: holding.name,
        value: 0,
        weightedPnl: 0,
        accounts: new Set(),
        quantity: null,
        price: holding.price,
        currency: holding.currency,
      };

      existing.value += holding.value;
      existing.weightedPnl += holding.value * (holding.pnlPct || 0);
      existing.accounts.add(account.name);
      if (holding.quantity != null) {
        existing.quantity =
          (existing.quantity || 0) + Number(holding.quantity || 0);
      }
      holdings.set(holding.sym, existing);
    });
  });

  return Array.from(holdings.values())
    .map((holding) => ({
      ...holding,
      pnlPct: holding.value ? holding.weightedPnl / holding.value : 0,
      accountLabel: Array.from(holding.accounts).join(", "),
    }))
    .sort((a, b) => b.value - a.value);
}

function InvestmentHoldingsScreen({ theme, accent, onBack }) {
  const [selectedAccounts, setSelectedAccounts] = React.useState([]);
  const [manualAccounts, setManualAccounts] = React.useState([]);
  const [optionsOpen, setOptionsOpen] = React.useState(false);
  const [addStep, setAddStep] = React.useState(null);
  const [selectedAsset, setSelectedAsset] = React.useState(null);
  const [shareQty, setShareQty] = React.useState("");
  const [shareFocused, setShareFocused] = React.useState(false);
  const [drafts, setDrafts] = React.useState([]);
  const [selectedDraftAccount, setSelectedDraftAccount] = React.useState(null);
  const [createAccountOpen, setCreateAccountOpen] = React.useState(false);
  const [manualAccountName, setManualAccountName] =
    React.useState(MANUAL_ACCOUNT_NAME);
  const [accountToast, setAccountToast] = React.useState(false);
  const [successToast, setSuccessToast] = React.useState(false);
  const [editOpen, setEditOpen] = React.useState(false);
  const [editHoldings, setEditHoldings] = React.useState([]);
  const [editedEmpty, setEditedEmpty] = React.useState(false);
  const [editToast, setEditToast] = React.useState(false);
  const holdings = getFilteredHoldingRows(selectedAccounts, manualAccounts);
  const accountOptions = getAccountOptions(manualAccounts);
  const total = holdings.reduce((sum, holding) => sum + holding.value, 0);
  const weightedPnl = total
    ? holdings.reduce(
        (sum, holding) => sum + holding.value * holding.pnlPct,
        0,
      ) / total
    : 0;
  const filterLabel =
    selectedAccounts.length === 0
      ? "All accounts"
      : selectedAccounts.length === 1
        ? accountOptions.find((account) => account.id === selectedAccounts[0])
            ?.name || "1 account"
        : `${selectedAccounts.length} accounts`;

  const closeAddFlow = () => {
    setAddStep(null);
    setSelectedAsset(null);
    setShareQty("");
    setShareFocused(false);
    setDrafts([]);
    setSelectedDraftAccount(null);
    setAccountToast(false);
  };
  const openAddFlow = () => {
    setOptionsOpen(false);
    setSelectedAsset(null);
    setShareQty("");
    setDrafts([]);
    setSelectedDraftAccount(manualAccounts[0]?.id || null);
    setAccountToast(false);
    setAddStep("search");
  };
  const openEditFlow = () => {
    const manualAccount = manualAccounts.find(
      (account) => account.id === MANUAL_ACCOUNT_ID,
    );
    const holdingsToEdit = manualAccount
      ? manualAccount.holdings
      : [getSeedManualHolding()];

    setOptionsOpen(false);
    setSuccessToast(false);
    setEditToast(false);
    setEditHoldings(holdingsToEdit.map((holding) => ({ ...holding })));
    setEditOpen(true);
  };
  const selectAsset = (asset) => {
    setSelectedAsset(asset);
    setShareQty("");
    setShareFocused(false);
    setAddStep("quantity");
  };
  const goAccountStep = () => {
    if (!selectedAsset || !shareQty) return;
    const quantity = Number(shareQty) || 0;
    const draft = {
      id: `${selectedAsset.symbol}-${drafts.length}`,
      asset: selectedAsset,
      quantity,
      value: quantity * selectedAsset.price,
    };
    setDrafts((items) => [...items, draft]);
    setSelectedDraftAccount(manualAccounts[0]?.id || null);
    setAddStep("account");
  };
  const saveManualAccount = () => {
    const name = manualAccountName.trim() || MANUAL_ACCOUNT_NAME;
    const id = MANUAL_ACCOUNT_ID;
    setManualAccounts((accounts) => {
      if (accounts.some((account) => account.id === id)) {
        return accounts.map((account) =>
          account.id === id ? { ...account, name } : account,
        );
      }
      return [...accounts, { id, name, holdings: [] }];
    });
    setSelectedDraftAccount(id);
    setCreateAccountOpen(false);
    setAccountToast(true);
  };
  const saveDraftHoldings = () => {
    if (!selectedDraftAccount || drafts.length === 0) return;
    setManualAccounts((accounts) =>
      accounts.map((account) =>
        account.id === selectedDraftAccount
          ? {
              ...account,
              holdings: [
                ...account.holdings,
                ...drafts.map((draft) => ({
                  sym: draft.asset.symbol,
                  name: draft.asset.name,
                  value: draft.value,
                  pnlPct: 0,
                  quantity: draft.quantity,
                  price: draft.asset.price,
                  currency: "USD",
                })),
              ],
            }
          : account,
      ),
    );
    setSelectedAccounts([selectedDraftAccount]);
    closeAddFlow();
    setEditedEmpty(false);
    setSuccessToast(true);
  };
  const saveEditedHoldings = () => {
    setManualAccounts((accounts) => {
      const nextAccount = {
        id: MANUAL_ACCOUNT_ID,
        name: MANUAL_ACCOUNT_NAME,
        holdings: editHoldings,
      };

      if (accounts.some((account) => account.id === MANUAL_ACCOUNT_ID)) {
        return accounts.map((account) =>
          account.id === MANUAL_ACCOUNT_ID
            ? { ...account, holdings: editHoldings }
            : account,
        );
      }

      return [...accounts, nextAccount];
    });
    setSelectedAccounts([MANUAL_ACCOUNT_ID]);
    setEditOpen(false);
    setEditedEmpty(editHoldings.length === 0);
    setEditToast(true);
  };

  return (
    <Screen theme={theme} padBottom={40} style={{ position: "relative" }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "18px 20px 12px",
        }}
      >
        <button onClick={onBack} style={iconButtonStyle(theme)}>
          <Ico.chevL size={14} />
        </button>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            letterSpacing: 1.5,
            textTransform: "uppercase",
            color: theme.textMute,
          }}
        >
          Trading accounts
        </div>
        <button
          type="button"
          onClick={() => setOptionsOpen(true)}
          style={iconButtonStyle(theme)}
          aria-label="Open holdings options"
        >
          <Ico.dots size={16} />
        </button>
      </div>

      <div style={{ padding: "0 22px 14px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div
            style={{
              width: 42,
              height: 42,
              borderRadius: themeRadius(theme, "md", 14),
              background: theme.surface3,
              border: `0.5px solid ${theme.line}`,
              color: accent,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
            }}
          >
            <Ico.lineChart size={20} sw={1.7} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 24,
                color: theme.text,
                letterSpacing: -0.5,
                lineHeight: 1.1,
              }}
            >
              Holdings
            </div>
            <div
              style={{
                marginTop: 3,
                fontFamily: FONTS.ui,
                fontSize: 12,
                color: theme.textMute,
              }}
            >
              {filterLabel}
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: "0 16px 12px" }}>
        {!editedEmpty && (
          <AccountMultiSelect
            theme={theme}
            selected={selectedAccounts}
            accounts={accountOptions}
            onChange={setSelectedAccounts}
          />
        )}
      </div>

      {editedEmpty ? (
        <MainHoldingsEmptyState theme={theme} />
      ) : (
        <>
          <div style={{ padding: "0 16px 14px" }}>
            <Card
              theme={theme}
              style={{
                padding: 20,
                background:
                  theme.components?.promoCard?.bg ||
                  `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}>Holdings 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",
                    }}
                  >
                    Today
                  </div>
                  <Delta
                    value={weightedPnl}
                    pct={weightedPnl}
                    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, index) => (
                <InvestmentHoldingRow
                  key={holding.sym}
                  holding={holding}
                  total={total}
                  theme={theme}
                  last={index === holdings.length - 1}
                />
              ))}
            </Card>
          </div>
        </>
      )}

      {optionsOpen && (
        <HoldingOptionsSheet
          theme={theme}
          onClose={() => setOptionsOpen(false)}
          onAdd={openAddFlow}
          onEdit={openEditFlow}
        />
      )}
      {addStep && (
        <AddHoldingFlow
          theme={theme}
          accent={accent}
          step={addStep}
          selectedAsset={selectedAsset}
          shareQty={shareQty}
          shareFocused={shareFocused}
          drafts={drafts}
          manualAccounts={manualAccounts}
          selectedDraftAccount={selectedDraftAccount}
          accountToast={accountToast}
          onClose={closeAddFlow}
          onBack={() => {
            if (addStep === "quantity") setAddStep("search");
            else if (addStep === "account") setAddStep("quantity");
            else closeAddFlow();
          }}
          onSelectAsset={selectAsset}
          onShareQty={setShareQty}
          onShareFocus={setShareFocused}
          onNext={goAccountStep}
          onCreateAccount={() => setCreateAccountOpen(true)}
          onSelectAccount={setSelectedDraftAccount}
          onAddAnother={() => {
            setSelectedAsset(null);
            setShareQty("");
            setShareFocused(false);
            setAddStep("search");
          }}
          onSave={saveDraftHoldings}
          onDismissAccountToast={() => setAccountToast(false)}
        />
      )}
      {createAccountOpen && (
        <CreateInvestmentAccountModal
          theme={theme}
          accountName={manualAccountName}
          onNameChange={setManualAccountName}
          onClose={() => setCreateAccountOpen(false)}
          onSave={saveManualAccount}
        />
      )}
      {successToast && (
        <SuccessBanner
          theme={theme}
          title="New Holding Added!"
          body="You've successfully added a new holding to your portfolio."
          onClose={() => setSuccessToast(false)}
        />
      )}
      {editOpen && (
        <EditHoldingsView
          theme={theme}
          holdings={editHoldings}
          onHoldingsChange={setEditHoldings}
          onCancel={() => setEditOpen(false)}
          onSave={saveEditedHoldings}
        />
      )}
      {editToast && (
        <EditedHoldingsToast
          theme={theme}
          onClose={() => setEditToast(false)}
        />
      )}
    </Screen>
  );
}

function iconButtonStyle(theme) {
  const button = theme.components?.iconButton || {};
  return {
    width: button.size || 36,
    height: button.size || 36,
    borderRadius: button.radius || 18,
    background: button.bg || "transparent",
    border: `0.5px solid ${button.border || theme.line2}`,
    color: button.color || theme.text,
    cursor: "pointer",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
  };
}

function bareIconButtonStyle(theme, size = 30, overrides = {}) {
  return {
    width: size,
    height: size,
    borderRadius: themeRadius(theme, "pill", 999),
    border: "none",
    background: "transparent",
    color: theme.textMute,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    cursor: "pointer",
    flexShrink: 0,
    ...overrides,
  };
}

function sheetPanelStyle(theme) {
  const sheet = theme.components?.sheet || {};
  const radius = sheet.radius ?? themeRadius(theme, "sheet", 28);
  return {
    position: "absolute",
    left: 0,
    right: 0,
    bottom: 0,
    background: sheet.bg || theme.surface,
    borderTopLeftRadius: radius,
    borderTopRightRadius: radius,
    border: `0.5px solid ${sheet.border || theme.line}`,
    padding: sheet.padding || "18px 18px 30px",
    boxShadow: sheet.shadow || theme.shadow?.sheet,
  };
}

function HoldingOptionsSheet({ theme, onClose, onAdd, onEdit }) {
  return (
    <div style={overlayStyle(theme)}>
      <button
        type="button"
        onClick={onClose}
        style={{
          position: "absolute",
          inset: 0,
          border: "none",
          background: "transparent",
        }}
        aria-label="Close options"
      />
      <div style={sheetPanelStyle(theme)}>
        <SheetHeader title="OPTIONS" theme={theme} onClose={onClose} />
        <div style={{ display: "grid", gap: 12, marginTop: 16 }}>
          <OptionLargeButton
            theme={theme}
            icon={<Ico.plus size={18} />}
            label="Add holding"
            onClick={onAdd}
          />
          <OptionLargeButton
            theme={theme}
            icon={<Ico.compose size={18} />}
            label="Edit holdings"
            onClick={onEdit}
          />
        </div>
      </div>
    </div>
  );
}

function MainHoldingsEmptyState({ theme }) {
  return (
    <div
      style={{
        minHeight: 520,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        textAlign: "center",
        padding: "0 34px 40px",
      }}
    >
      <div
        style={{
          fontFamily: FONTS.ui,
          fontSize: 20,
          lineHeight: 1.2,
          fontWeight: 750,
          color: theme.text,
        }}
      >
        No holdings found
      </div>
      <div
        style={{
          marginTop: 8,
          fontFamily: FONTS.ui,
          fontSize: 13,
          lineHeight: 1.4,
          color: theme.textMute,
        }}
      >
        We couldn't find any holdings for this account.
      </div>
    </div>
  );
}

function EditHoldingsView({
  theme,
  holdings,
  onHoldingsChange,
  onCancel,
  onSave,
}) {
  const [deleteCandidate, setDeleteCandidate] = React.useState(null);

  const updateQuantity = (sym, value) => {
    const cleanValue = value.replace(/[^\d.]/g, "");
    onHoldingsChange((items) =>
      items.map((holding) => {
        if (holding.sym !== sym) return holding;
        const quantity = Number(cleanValue) || 0;
        return {
          ...holding,
          quantity: cleanValue,
          value: quantity * (holding.price || 0),
        };
      }),
    );
  };
  const deleteHolding = () => {
    if (!deleteCandidate) return;
    onHoldingsChange((items) =>
      items.filter((holding) => holding.sym !== deleteCandidate.sym),
    );
    setDeleteCandidate(null);
  };

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 65,
        background: theme.bg,
        color: theme.text,
        overflow: "hidden",
      }}
    >
      <div
        style={{
          position: "sticky",
          top: 0,
          zIndex: 5,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "18px 20px 14px",
          background: theme.bg,
        }}
      >
        <button type="button" onClick={onCancel} style={iconButtonStyle(theme)}>
          <Ico.chevL size={14} />
        </button>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            letterSpacing: 1.5,
            textTransform: "uppercase",
            color: theme.textMute,
          }}
        >
          EDIT HOLDINGS
        </div>
        <div style={{ width: 36 }} />
      </div>

      <div
        style={{ height: "100%", overflowY: "auto", padding: "0 16px 118px" }}
      >
        <Card theme={theme} padded={false} style={{ overflow: "hidden" }}>
          <div
            style={{
              padding: "14px 15px",
              display: "flex",
              alignItems: "center",
              gap: 11,
            }}
          >
            <div
              style={{
                width: 34,
                height: 34,
                borderRadius: themeRadius(theme, "pill", 999),
                background: theme.surface3,
                color: theme.textDim,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontFamily: FONTS.ui,
                fontSize: 14,
                fontWeight: 750,
                flexShrink: 0,
              }}
            >
              M
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div
                style={{
                  fontFamily: FONTS.ui,
                  fontSize: 14,
                  fontWeight: 750,
                  color: theme.text,
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {MANUAL_ACCOUNT_NAME}
              </div>
              <div
                style={{
                  marginTop: 2,
                  fontFamily: FONTS.ui,
                  fontSize: 11.5,
                  color: theme.textMute,
                }}
              >
                {holdings.length} holdings
              </div>
            </div>
            <Ico.chevU size={15} stroke={theme.textMute} />
          </div>

          {holdings.length > 0 && (
            <div style={{ borderTop: `0.5px solid ${theme.line}` }}>
              {holdings.map((holding, index) => (
                <EditHoldingRow
                  key={holding.sym}
                  holding={holding}
                  theme={theme}
                  last={index === holdings.length - 1}
                  onQuantityChange={(value) =>
                    updateQuantity(holding.sym, value)
                  }
                  onDelete={() => setDeleteCandidate(holding)}
                />
              ))}
            </div>
          )}
        </Card>
      </div>

      <EditHoldingsFooter theme={theme} onCancel={onCancel} onSave={onSave} />

      {deleteCandidate && (
        <DeleteHoldingSheet
          theme={theme}
          onCancel={() => setDeleteCandidate(null)}
          onDelete={deleteHolding}
        />
      )}
    </div>
  );
}

function EditHoldingRow({ holding, theme, last, onQuantityChange, onDelete }) {
  return (
    <div
      style={{
        minHeight: 66,
        display: "grid",
        gridTemplateColumns: "34px minmax(0, 1fr) 112px 30px",
        gap: 10,
        alignItems: "center",
        padding: "12px 14px",
        borderBottom: last ? "none" : `0.5px solid ${theme.line}`,
      }}
    >
      <EditHoldingLogo symbol={holding.sym} />
      <div style={{ minWidth: 0 }}>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 13.5,
            fontWeight: 500,
            color: theme.text,
          }}
        >
          {holding.sym}
        </div>
        <div
          style={{
            marginTop: 2,
            fontFamily: FONTS.ui,
            fontSize: 11,
            color: theme.textMute,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {holding.name}
        </div>
      </div>
      <EditQuantityField
        theme={theme}
        value={String(holding.quantity ?? "")}
        onChange={onQuantityChange}
      />
      <button
        type="button"
        onClick={onDelete}
        style={bareIconButtonStyle(theme)}
      >
        <Ico.trash size={16} />
      </button>
    </div>
  );
}

function EditHoldingLogo({ symbol }) {
  return <StockLogo symbol={symbol} />;
}

function EditQuantityField({ theme, value, onChange }) {
  const input = theme.components?.input || {};
  return (
    <div
      style={{
        height: 43,
        borderRadius: themeRadius(theme, "md", input.radius || 14),
        border: `0.5px solid ${input.border || theme.line2}`,
        background: input.bg || theme.bg,
        padding: "6px 9px 5px",
      }}
    >
      <div
        style={{
          fontFamily: FONTS.ui,
          fontSize: 9.5,
          lineHeight: 1,
          color: theme.textMute,
          whiteSpace: "nowrap",
        }}
      >
        Number of shares
      </div>
      <input
        value={value}
        onChange={(event) => onChange(event.target.value)}
        inputMode="decimal"
        style={{
          width: "100%",
          border: "none",
          outline: "none",
          background: "transparent",
          padding: "4px 0 0",
          color: theme.text,
          fontFamily: FONTS.ui,
          fontSize: 14,
          fontWeight: 600,
        }}
      />
    </div>
  );
}

function EditHoldingsFooter({ theme, onCancel, onSave }) {
  return (
    <div
      style={{
        position: "absolute",
        left: 0,
        right: 0,
        bottom: 0,
        padding: "10px 18px 24px",
        background: `linear-gradient(to top, ${theme.bg} 82%, ${theme.bg}00)`,
      }}
    >
      <button
        type="button"
        onClick={onCancel}
        style={textActionStyle(theme, {
          width: "100%",
          textDecoration: "underline",
          padding: "9px 0 12px",
        })}
      >
        CANCEL
      </button>
      <button type="button" onClick={onSave} style={primaryPillStyle(theme)}>
        SAVE
      </button>
    </div>
  );
}

function DeleteHoldingSheet({ theme, onCancel, onDelete }) {
  return (
    <div style={overlayStyle(theme, 85)}>
      <button
        type="button"
        onClick={onCancel}
        style={{
          position: "absolute",
          inset: 0,
          border: "none",
          background: "transparent",
        }}
        aria-label="Close delete holding"
      />
      <div style={sheetPanelStyle(theme)}>
        <SheetHeader title="DELETE HOLDING" theme={theme} onClose={onCancel} />
        <div style={{ textAlign: "center", padding: "28px 14px 24px" }}>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 21,
              lineHeight: 1.15,
              fontWeight: 750,
              color: theme.text,
            }}
          >
            Are you sure you want to delete this holding?
          </div>
          <div
            style={{
              marginTop: 10,
              fontFamily: FONTS.ui,
              fontSize: 13,
              lineHeight: 1.45,
              color: theme.textMute,
            }}
          >
            Deleting will remove all history of this holding.
          </div>
        </div>
        <button
          type="button"
          onClick={onCancel}
          style={textActionStyle(theme, {
            width: "100%",
            textDecoration: "underline",
            padding: "0 0 14px",
          })}
        >
          CANCEL
        </button>
        <button type="button" onClick={onDelete} style={dangerPillStyle(theme)}>
          YES, DELETE
        </button>
      </div>
    </div>
  );
}

function OptionLargeButton({ theme, icon, label, onClick }) {
  const button = theme.components?.secondaryButton || {};
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: "100%",
        minHeight: 64,
        borderRadius: themeRadius(theme, "lg", 18),
        border: `0.5px solid ${button.border || theme.line2}`,
        background: theme.surface,
        color: button.color || theme.text,
        fontFamily: FONTS.ui,
        fontSize: 15,
        fontWeight: 500,
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        gap: 12,
        padding: "0 16px",
      }}
    >
      <span
        style={{
          width: 34,
          height: 34,
          borderRadius: themeRadius(theme, "md", 14),
          background: theme.surface2,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        {icon}
      </span>
      {label}
    </button>
  );
}

function AddHoldingFlow({
  theme,
  accent,
  step,
  selectedAsset,
  shareQty,
  shareFocused,
  drafts,
  manualAccounts,
  selectedDraftAccount,
  accountToast,
  onClose,
  onBack,
  onSelectAsset,
  onShareQty,
  onShareFocus,
  onNext,
  onCreateAccount,
  onSelectAccount,
  onAddAnother,
  onSave,
  onDismissAccountToast,
}) {
  const showFooter = step === "quantity" || step === "account";

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 60,
        background: theme.bg,
        color: theme.text,
        overflowY: "auto",
        paddingBottom: showFooter ? 92 : 22,
      }}
    >
      {accountToast && (
        <SuccessBanner
          theme={theme}
          title="Success"
          body="Your asset was created."
          onClose={onDismissAccountToast}
        />
      )}
      <FlowHeader
        theme={theme}
        title="ADD HOLDING"
        onBack={onBack}
        onClose={onClose}
      />

      {step === "search" && (
        <AddHoldingSearch theme={theme} onSelectAsset={onSelectAsset} />
      )}
      {step === "quantity" && selectedAsset && (
        <ShareQuantityStep
          theme={theme}
          asset={selectedAsset}
          shareQty={shareQty}
          focused={shareFocused}
          onShareQty={onShareQty}
          onFocus={onShareFocus}
        />
      )}
      {step === "account" && (
        <AccountSelectionStep
          theme={theme}
          drafts={drafts}
          manualAccounts={manualAccounts}
          selectedDraftAccount={selectedDraftAccount}
          onCreateAccount={onCreateAccount}
          onSelectAccount={onSelectAccount}
          onAddAnother={onAddAnother}
        />
      )}

      {showFooter && (
        <div style={flowFooterStyle(theme)}>
          <button
            type="button"
            onClick={step === "quantity" ? onNext : onSave}
            style={primaryPillStyle(theme)}
          >
            {step === "quantity" ? "NEXT ->" : "SAVE"}
          </button>
        </div>
      )}
    </div>
  );
}

function FlowHeader({ theme, title, onBack, onClose }) {
  return (
    <div
      style={{
        position: "sticky",
        top: 0,
        zIndex: 5,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        padding: "18px 20px 14px",
        background: `linear-gradient(to bottom, ${theme.bg} 82%, ${theme.bg}00)`,
      }}
    >
      <button type="button" onClick={onBack} style={iconButtonStyle(theme)}>
        <Ico.chevL size={14} />
      </button>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 10,
          letterSpacing: 1.5,
          textTransform: "uppercase",
          color: theme.textMute,
        }}
      >
        {title}
      </div>
      <button type="button" onClick={onClose} style={iconButtonStyle(theme)}>
        <Ico.close size={14} />
      </button>
    </div>
  );
}

function SheetHeader({ title, theme, onClose }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
      }}
    >
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 10,
          letterSpacing: 1.5,
          textTransform: "uppercase",
          color: theme.textMute,
        }}
      >
        {title}
      </div>
      <button type="button" onClick={onClose} style={iconButtonStyle(theme)}>
        <Ico.close size={14} />
      </button>
    </div>
  );
}

function AddHoldingSearch({ theme, onSelectAsset }) {
  const input = theme.components?.input || {};
  return (
    <div style={{ padding: "0 16px 18px" }}>
      <div
        style={{
          minHeight: 56,
          borderRadius: themeRadius(theme, "lg", 18),
          border: `0.5px solid ${input.border || theme.line2}`,
          background: theme.surface,
          padding: "0 16px",
          display: "flex",
          alignItems: "center",
          gap: 10,
          color: theme.textMute,
          fontFamily: FONTS.ui,
          fontSize: 15,
        }}
      >
        <Ico.search size={17} />
        <span>Search</span>
      </div>

      <AssetPickSection
        theme={theme}
        title="POPULAR HOLDINGS"
        assets={POPULAR_HOLDINGS}
        onSelectAsset={onSelectAsset}
      />
      <AssetPickSection
        theme={theme}
        title="POPULAR CRYPTO"
        assets={POPULAR_CRYPTO_HOLDINGS}
        onSelectAsset={onSelectAsset}
      />
    </div>
  );
}

function AssetPickSection({ theme, title, assets, onSelectAsset }) {
  return (
    <div style={{ marginTop: 22 }}>
      <SectionLabel theme={theme}>{title}</SectionLabel>
      <Card
        theme={theme}
        padded={false}
        style={{ marginTop: 10, overflow: "hidden" }}
      >
        {assets.map((asset, index) => (
          <AssetPickRow
            key={asset.symbol}
            asset={asset}
            theme={theme}
            last={index === assets.length - 1}
            onClick={() => onSelectAsset(asset)}
          />
        ))}
      </Card>
    </div>
  );
}

function AssetPickRow({ asset, theme, last, onClick }) {
  return (
    <Row
      theme={theme}
      onClick={onClick}
      chevron
      last={last}
      left={<StockLogo symbol={asset.symbol} />}
      title={asset.symbol}
      subtitle={asset.name}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 13, color: theme.text }}
        >
          {fmtUSD(asset.price)}
        </span>
      }
    />
  );
}

function ShareQuantityStep({
  theme,
  asset,
  shareQty,
  focused,
  onShareQty,
  onFocus,
}) {
  return (
    <div style={{ padding: "0 16px 20px" }}>
      <Card theme={theme} style={{ padding: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <StockLogo symbol={asset.symbol} />
          <div style={{ minWidth: 0 }}>
            <div
              style={{ fontFamily: FONTS.ui, fontSize: 15, fontWeight: 500 }}
            >
              {asset.symbol}
            </div>
            <div
              style={{
                marginTop: 2,
                fontFamily: FONTS.ui,
                fontSize: 12,
                color: theme.textMute,
              }}
            >
              {asset.name}
            </div>
          </div>
        </div>
        <div
          style={{
            height: 1,
            background: theme.line,
            margin: "15px 0 13px",
          }}
        />
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 12.5,
            color: theme.textDim,
          }}
        >
          Latest closing share price: {fmtUSD(asset.price)}
        </div>
      </Card>

      <FloatingTextInput
        theme={theme}
        label="Number of shares"
        value={shareQty}
        onChange={onShareQty}
        focused={focused}
        onFocus={() => onFocus(true)}
        onBlur={() => onFocus(false)}
      />
    </div>
  );
}

function FloatingTextInput({
  theme,
  label,
  value,
  onChange,
  focused,
  onFocus,
  onBlur,
}) {
  const floating = focused || value;
  const input = theme.components?.input || {};
  return (
    <div style={{ position: "relative", marginTop: 20 }}>
      <label
        style={{
          position: "absolute",
          left: 15,
          top: floating ? -8 : 17,
          padding: "0 6px",
          background: theme.bg,
          color: floating ? theme.textDim : theme.textMute,
          fontFamily: FONTS.ui,
          fontSize: floating ? 11 : 14,
          transition: "all 140ms",
          pointerEvents: "none",
        }}
      >
        {label}
      </label>
      <input
        value={value}
        onChange={(event) =>
          onChange(event.target.value.replace(/[^\d.]/g, ""))
        }
        onFocus={onFocus}
        onBlur={onBlur}
        inputMode="decimal"
        style={{
          width: "100%",
          height: 58,
          borderRadius: input.radius || themeRadius(theme, "lg", 16),
          border: `1px solid ${focused ? theme.text : input.border || theme.line2}`,
          background: input.bg || theme.bg,
          color: theme.text,
          fontFamily: FONTS.ui,
          fontSize: 17,
          padding: "16px 18px 8px",
          outline: "none",
        }}
      />
    </div>
  );
}

function AccountSelectionStep({
  theme,
  drafts,
  manualAccounts,
  selectedDraftAccount,
  onCreateAccount,
  onSelectAccount,
  onAddAnother,
}) {
  const account = manualAccounts.find(
    (item) => item.id === selectedDraftAccount,
  );

  return (
    <div style={{ padding: "0 16px 20px" }}>
      <div
        style={{
          fontFamily: FONTS.ui,
          fontSize: 18,
          lineHeight: 1.25,
          fontWeight: 500,
          color: theme.text,
          marginBottom: 14,
        }}
      >
        Select an account to add your holdings.
      </div>

      {account ? (
        <ManualAccountDropdown
          theme={theme}
          account={account}
          onSelect={() => onSelectAccount(account.id)}
        />
      ) : (
        <Card theme={theme} style={{ padding: 18 }}>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 15,
              fontWeight: 500,
              color: theme.text,
            }}
          >
            No manual account found
          </div>
          <div
            style={{
              marginTop: 5,
              fontFamily: FONTS.ui,
              fontSize: 12.5,
              color: theme.textMute,
            }}
          >
            Create a new one to continue
          </div>
          <button
            type="button"
            onClick={onCreateAccount}
            style={secondaryButtonStyle(theme, {
              marginTop: 14,
              width: "100%",
              minHeight: 42,
              fontSize: 12.5,
              fontWeight: 500,
            })}
          >
            ADD ACCOUNT
          </button>
        </Card>
      )}

      <div style={{ marginTop: 22 }}>
        <SectionLabel theme={theme}>Holdings to be added</SectionLabel>
        <Card
          theme={theme}
          padded={false}
          style={{ marginTop: 10, overflow: "hidden" }}
        >
          {drafts.map((draft, index) => (
            <DraftHoldingRow
              key={draft.id}
              draft={draft}
              theme={theme}
              last={index === drafts.length - 1}
            />
          ))}
        </Card>
        <button
          type="button"
          onClick={onAddAnother}
          style={secondaryButtonStyle(theme, {
            marginTop: 12,
            width: "100%",
            minHeight: 42,
            fontSize: 12.5,
            fontWeight: 500,
          })}
        >
          ADD A HOLDING
        </button>
      </div>
    </div>
  );
}

function ManualAccountDropdown({ theme, account, onSelect }) {
  return (
    <button
      type="button"
      onClick={onSelect}
      style={secondaryButtonStyle(theme, {
        width: "100%",
        minHeight: 46,
        background: theme.surface,
        padding: "11px 13px",
        fontSize: 13,
        fontWeight: 600,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
      })}
    >
      <span>{account.name}</span>
      <Ico.chevD size={14} />
    </button>
  );
}

function DraftHoldingRow({ draft, theme, last }) {
  return (
    <Row
      theme={theme}
      last={last}
      left={<StockLogo symbol={draft.asset.symbol} />}
      title={draft.asset.symbol}
      subtitle={`${draft.quantity} share${draft.quantity === 1 ? "" : "s"}`}
      rightTop={
        <span
          style={{ fontFamily: FONTS.mono, fontSize: 13, color: theme.text }}
        >
          {fmtUSD(draft.value)}
        </span>
      }
    />
  );
}

function CreateInvestmentAccountModal({
  theme,
  accountName,
  onNameChange,
  onClose,
  onSave,
}) {
  return (
    <div style={overlayStyle(theme, 90, true)}>
      <div
        style={{
          position: "absolute",
          left: 16,
          right: 16,
          top: 88,
          bottom: 24,
          background: theme.bg,
          borderRadius: themeRadius(theme, "modal", 24),
          border: `0.5px solid ${theme.line}`,
          overflow: "hidden",
          boxShadow: theme.shadow?.modal,
        }}
      >
        <div
          style={{
            padding: "18px 18px 88px",
            height: "100%",
            overflowY: "auto",
          }}
        >
          <SheetHeader title="INVESTMENTS" theme={theme} onClose={onClose} />
          <div
            style={{
              marginTop: 18,
              fontFamily: FONTS.display,
              fontSize: 24,
              color: theme.text,
              letterSpacing: -0.4,
            }}
          >
            Complete your information
          </div>
          <WireframeField
            theme={theme}
            label="Account type"
            value="MANUAL"
            disabled
          />
          <WireframeField
            theme={theme}
            label="Account name"
            value={accountName}
            onChange={onNameChange}
          />
        </div>
        <div style={flowFooterStyle(theme)}>
          <button
            type="button"
            onClick={onSave}
            style={primaryPillStyle(theme)}
          >
            SAVE
          </button>
        </div>
      </div>
    </div>
  );
}

function WireframeField({ theme, label, value, onChange, disabled }) {
  const input = theme.components?.input || {};
  return (
    <div style={{ position: "relative", marginTop: 22 }}>
      <label
        style={{
          position: "absolute",
          top: -8,
          left: 14,
          background: theme.bg,
          padding: "0 6px",
          fontFamily: FONTS.ui,
          fontSize: 11,
          color: theme.textDim,
        }}
      >
        {label}
      </label>
      <input
        value={value}
        disabled={disabled}
        onChange={(event) => onChange && onChange(event.target.value)}
        style={{
          width: "100%",
          height: 56,
          borderRadius: input.radius || themeRadius(theme, "lg", 16),
          border: `1px solid ${input.border || theme.line2}`,
          background: disabled ? theme.surface2 : theme.bg,
          color: theme.text,
          fontFamily: FONTS.ui,
          fontSize: 14,
          padding: "14px 18px",
          outline: "none",
        }}
      />
    </div>
  );
}

function SuccessBanner({ theme, title, body, onClose }) {
  const toast = theme.components?.toast || {};
  return (
    <div
      style={{
        position: "absolute",
        top: 12,
        left: 16,
        right: 16,
        zIndex: 100,
        borderRadius: toast.radius || themeRadius(theme, "lg", 16),
        border: `0.5px solid ${toast.border || theme.line}`,
        background: toast.bg || theme.surface,
        boxShadow: toast.shadow || theme.shadow?.toast,
        padding: "13px 12px",
        display: "flex",
        alignItems: "flex-start",
        gap: 10,
      }}
    >
      <span
        style={{
          width: 28,
          height: 28,
          borderRadius: themeRadius(theme, "pill", 999),
          background:
            toast.iconBg || translucentSurface(theme, theme.positive, 0.1),
          color: theme.positive,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
        }}
      >
        <Ico.check size={15} sw={2.2} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: FONTS.ui, fontSize: 13.5, fontWeight: 700 }}>
          {title}
        </div>
        <div
          style={{
            marginTop: 2,
            fontFamily: FONTS.ui,
            fontSize: 12,
            color: theme.textDim,
            lineHeight: 1.35,
          }}
        >
          {body}
        </div>
      </div>
      <button
        type="button"
        onClick={onClose}
        style={bareIconButtonStyle(theme, 26)}
      >
        <Ico.close size={13} />
      </button>
    </div>
  );
}

function EditedHoldingsToast({ theme, onClose }) {
  const toast = theme.components?.toast || {};
  return (
    <div
      style={{
        position: "absolute",
        top: 12,
        left: 20,
        right: 20,
        zIndex: 100,
        minHeight: 48,
        borderRadius: themeRadius(theme, "pill", 999),
        border: `0.5px solid ${toast.border || theme.line}`,
        background: toast.bg || theme.surface,
        boxShadow: theme.shadow?.pillToast,
        padding: "8px 10px",
        display: "flex",
        alignItems: "center",
        gap: 10,
      }}
    >
      <span
        style={{
          width: 30,
          height: 30,
          borderRadius: themeRadius(theme, "pill", 999),
          background: theme.positive,
          color: theme.bg,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
        }}
      >
        <Ico.check size={15} sw={2.3} />
      </span>
      <div
        style={{
          flex: 1,
          minWidth: 0,
          textAlign: "center",
          fontFamily: FONTS.ui,
          fontSize: 13.5,
          fontWeight: 700,
          color: theme.text,
        }}
      >
        Holdings was edited!
      </div>
      <button
        type="button"
        onClick={onClose}
        style={bareIconButtonStyle(theme)}
      >
        <Ico.close size={13} />
      </button>
    </div>
  );
}

function AccountMultiSelect({ theme, selected, accounts, onChange }) {
  const [open, setOpen] = React.useState(false);
  const selectedSet = new Set(selected);
  const label =
    selected.length === 0
      ? "All accounts"
      : selected.length === 1
        ? accounts.find((account) => account.id === selected[0])?.name ||
          "1 account"
        : `${selected.length} accounts`;

  const toggleAccount = (id) => {
    const next = selectedSet.has(id)
      ? selected.filter((accountId) => accountId !== id)
      : [...selected, id];
    onChange(next);
  };

  return (
    <div style={{ position: "relative" }}>
      <button
        type="button"
        onClick={() => setOpen((value) => !value)}
        style={secondaryButtonStyle(theme, {
          width: "100%",
          minHeight: 42,
          background: theme.surface,
          padding: "10px 13px",
          fontSize: 13,
          fontWeight: 600,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 10,
        })}
      >
        <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Ico.filter size={14} sw={1.7} />
          {label}
        </span>
        {open ? <Ico.chevU size={14} /> : <Ico.chevD size={14} />}
      </button>

      {open && (
        <div
          style={{
            position: "absolute",
            top: "calc(100% + 8px)",
            left: 0,
            right: 0,
            zIndex: 20,
            background: theme.surface,
            border: `0.5px solid ${theme.line}`,
            borderRadius: themeRadius(theme, "lg", 16),
            padding: 8,
            boxShadow: theme.shadow?.popover,
          }}
        >
          <AccountFilterOption
            theme={theme}
            label="All accounts"
            checked={selected.length === 0}
            onClick={() => {
              onChange([]);
              setOpen(false);
            }}
          />
          {accounts.map((account) => (
            <AccountFilterOption
              key={account.id}
              theme={theme}
              label={account.name}
              checked={selectedSet.has(account.id)}
              onClick={() => toggleAccount(account.id)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function AccountFilterOption({ theme, label, checked, onClick }) {
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: "100%",
        minHeight: 38,
        border: "none",
        borderRadius: themeRadius(theme, "sm", 10),
        background: checked ? theme.surface2 : "transparent",
        color: theme.text,
        fontFamily: FONTS.ui,
        fontSize: 12.5,
        fontWeight: 550,
        cursor: "pointer",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        padding: "9px 10px",
        textAlign: "left",
      }}
    >
      <span>{label}</span>
      <span
        style={{
          width: 18,
          height: 18,
          borderRadius: themeRadius(theme, "xs", 6),
          border: `0.5px solid ${checked ? theme.text : theme.line2}`,
          background: checked ? theme.text : "transparent",
          color: theme.bg,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
        }}
      >
        {checked && <Ico.check size={11} sw={2.1} />}
      </span>
    </button>
  );
}

function InvestmentHoldingRow({ holding, total, theme, last }) {
  const share = total ? (holding.value / total) * 100 : 0;
  const quantity =
    holding.quantity == null
      ? "--"
      : Number(holding.quantity).toLocaleString("en-US", {
          maximumFractionDigits: 6,
        });

  return (
    <Row
      theme={theme}
      last={last}
      left={<StockLogo symbol={holding.sym} />}
      title={holding.name}
      subtitle={`Quantity: ${quantity}`}
      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 overlayStyle(theme, zIndex = 70, modal = false) {
  const overlay = theme.components?.overlay || {};
  return {
    position: "absolute",
    inset: 0,
    zIndex,
    background: modal ? overlay.modalScrim : overlay.scrim,
  };
}

function flowFooterStyle(theme) {
  return {
    position: "absolute",
    left: 0,
    right: 0,
    bottom: 0,
    padding: "12px 18px 24px",
    background: `linear-gradient(to top, ${theme.bg} 76%, ${theme.bg}00)`,
  };
}

function primaryPillStyle(theme) {
  const button = theme.components?.primaryButton || {};
  return {
    width: "100%",
    minHeight: 50,
    borderRadius: button.radius || 25,
    border: "none",
    background: button.bg || theme.text,
    color: button.color || theme.bg,
    fontFamily: FONTS.ui,
    fontSize: 14,
    fontWeight: 750,
    cursor: "pointer",
  };
}

function dangerPillStyle(theme) {
  const button = theme.components?.dangerButton || {};
  return {
    width: "100%",
    minHeight: 48,
    borderRadius: button.radius || 25,
    border: "none",
    background: button.bg || theme.negative,
    color: button.color || theme.bg,
    fontFamily: FONTS.ui,
    fontSize: 13,
    fontWeight: 750,
    cursor: "pointer",
  };
}

function MarketImpactSection({ theme }) {
  return (
    <section style={{ padding: "20px 16px 8px" }}>
      <div style={{ padding: "0 20px 10px" }}>
        <SectionLabel theme={theme}>Market Impact</SectionLabel>
      </div>
      <div
        style={{
          display: "flex",
          gap: 12,
          overflowX: "auto",
          padding: "0 16px 2px",
          scrollSnapType: "x mandatory",
        }}
      >
        {INVESTMENT_IMPACT_CARDS.map((card) => (
          <ImpactCard key={card.headline} card={card} theme={theme} />
        ))}
      </div>
    </section>
  );
}

function ImpactCard({ card, theme }) {
  const positive = card.tone === "positive";
  const tone = positive ? theme.positive : theme.negative;
  const Icon = positive ? Ico.arrowUR : Ico.arrowDR;
  const promo = theme.components?.promoCard || {};

  return (
    <article
      style={{
        minWidth: 286,
        maxWidth: 286,
        minHeight: 178,
        background: promo.bg || theme.surface,
        border: `0.5px solid ${promo.border || theme.line}`,
        borderRadius: themeRadius(theme, "lg", 18),
        padding: 16,
        color: theme.text,
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        scrollSnapAlign: "start",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 8,
          fontFamily: FONTS.mono,
          fontSize: 10,
          fontWeight: 600,
          letterSpacing: 0.8,
          textTransform: "uppercase",
          color: tone,
        }}
      >
        <span
          style={{
            width: 22,
            height: 22,
            borderRadius: themeRadius(theme, "pill", 999),
            background: translucentSurface(theme, tone, 0.1),
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
          }}
        >
          <Icon size={13} sw={2} />
        </span>
        <span>{card.label}</span>
      </div>

      <div
        style={{
          marginTop: 18,
          fontFamily: FONTS.ui,
          fontSize: 17,
          lineHeight: 1.25,
          fontWeight: 500,
          letterSpacing: 0,
          color: theme.text,
        }}
      >
        {card.headline}
      </div>

      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 7,
          flexWrap: "wrap",
          marginTop: 18,
        }}
      >
        <span
          style={{
            color: theme.textMute,
            fontFamily: FONTS.ui,
            fontSize: 12,
            fontWeight: 500,
          }}
        >
          Affects:
        </span>
        {card.tickers.map((ticker) => (
          <span
            key={ticker}
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              minHeight: 22,
              padding: "3px 8px",
              borderRadius: themeRadius(theme, "pill", 999),
              background: theme.surface2,
              border: `0.5px solid ${theme.line2}`,
              color: theme.textDim,
              fontFamily: FONTS.mono,
              fontSize: 10,
              fontWeight: 600,
              letterSpacing: 0.4,
            }}
          >
            [{ticker}]
          </span>
        ))}
      </div>
    </article>
  );
}

function PortfolioRisksSection({ theme }) {
  const [openRisks, setOpenRisks] = React.useState({});

  const toggleRisk = (label) => {
    setOpenRisks((current) => ({
      ...current,
      [label]: !current[label],
    }));
  };

  return (
    <section style={{ padding: "28px 16px 0" }}>
      <div style={{ padding: "0 4px 10px" }}>
        <SectionLabel theme={theme}>Portfolio Health</SectionLabel>
      </div>
      <Card
        theme={theme}
        padded={false}
        style={{ borderRadius: themeRadius(theme, "lg", 18) }}
      >
        {PORTFOLIO_RISKS.map((risk, index) => (
          <RiskItem
            key={risk.label}
            risk={risk}
            theme={theme}
            open={!!openRisks[risk.label]}
            onToggle={() => toggleRisk(risk.label)}
            last={index === PORTFOLIO_RISKS.length - 1}
          />
        ))}
      </Card>
    </section>
  );
}

function RiskItem({ risk, theme, open, onToggle, last }) {
  const isWarning = risk.status === "warning";
  const isHealthy = risk.status === "healthy";
  const Icon = isWarning ? Ico.alert : isHealthy ? Ico.check : null;
  const iconColor = isWarning
    ? theme.warning
    : isHealthy
      ? theme.positive
      : theme.textMute;

  return (
    <button
      type="button"
      onClick={onToggle}
      aria-expanded={open}
      style={{
        width: "100%",
        padding: "15px 16px",
        borderBottom: last ? "none" : `0.5px solid ${theme.line}`,
        borderTop: "none",
        borderLeft: "none",
        borderRight: "none",
        background: "transparent",
        appearance: "none",
        textAlign: "left",
        cursor: "pointer",
        display: "block",
        color: "inherit",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 14,
        }}
      >
        <div style={{ minWidth: 0 }}>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 13,
              fontWeight: 500,
              color: theme.text,
              letterSpacing: 0,
            }}
          >
            {risk.label}
          </div>
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-end",
            gap: 6,
            color: iconColor,
            flexShrink: 0,
            maxWidth: 170,
            textAlign: "right",
          }}
        >
          <span
            style={{
              fontFamily: FONTS.ui,
              fontSize: 13,
              fontWeight: 500,
              color: isWarning || isHealthy ? iconColor : theme.textDim,
            }}
          >
            {risk.value}
          </span>
          {Icon && <Icon size={15} sw={1.9} />}
          {open ? (
            <Ico.chevU size={13} stroke={theme.textMute} />
          ) : (
            <Ico.chevD size={13} stroke={theme.textMute} />
          )}
        </div>
      </div>
      {open && (
        <div
          style={{
            marginTop: 10,
            fontFamily: FONTS.ui,
            fontSize: 11.5,
            lineHeight: 1.45,
            fontWeight: 400,
            color: theme.textMute,
          }}
        >
          {risk.description}
        </div>
      )}
    </button>
  );
}

function ProfessionalHelpCard({ theme, accent }) {
  const promo = theme.components?.promoCard || {};
  return (
    <section style={{ padding: "28px 16px 20px" }}>
      <div
        style={{
          width: "100%",
          borderRadius:
            theme.components?.card?.radius || themeRadius(theme, "xl", 20),
          padding: 20,
          background: promo.bg || theme.surface,
          border: `0.5px solid ${promo.border || theme.line}`,
          color: theme.text,
        }}
      >
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 20,
            lineHeight: 1.1,
            fontWeight: 500,
            letterSpacing: 0,
            color: theme.text,
          }}
        >
          Consult an expert
        </div>
        <div
          style={{
            marginTop: 8,
            maxWidth: 285,
            fontFamily: FONTS.ui,
            fontSize: 12,
            lineHeight: 1.45,
            color: theme.textDim,
          }}
        >
          Discuss a professional wealth plan with a licensed advisor.
        </div>
        <button
          type="button"
          style={{
            ...primaryPillStyle(theme),
            marginTop: 18,
            width: "100%",
            minHeight: 46,
          }}
        >
          Book Free Session
        </button>
      </div>
    </section>
  );
}

Object.assign(window, { InvestmentsScreen, InvestmentHoldingsScreen });
