sproutfolio source

App.tsx

import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { StatusBar, useWindowDimensions } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { ChartThemeProvider } from '@plocks/charts';
import { Block, Icon, PlocksProvider, SafeArea, ScrollArea, Tabs, Text, useTheme } from '@plocks/ui';
import type { Side } from './components/TradePanel';
import { findAsset, START_CASH, START_POSITIONS, START_WATCHLIST, type Position } from './data';
import { AssetScreen } from './screens/AssetScreen';
import { AccountScreen, HomeScreen, SearchScreen, WatchlistScreen, type Activity } from './screens/TabScreens';
import { C } from './theme';

type Tab = 'home' | 'search' | 'watchlist' | 'account';
const TABS: Tab[] = ['home', 'search', 'watchlist', 'account'];
const TAB_ICONS: Record<Tab, string> = { home: 'home', search: 'search', watchlist: 'bookmark', account: 'avatar' };
const STORAGE = 'plocks-sproutfolio-example:v2';

function SproutfolioScreen() {
  const { width } = useWindowDimensions();
  const wide = width >= 860;
  const [tab, setTab] = useState<Tab>('home');
  const [positions, setPositions] = useState<Record<string, Position>>(START_POSITIONS);
  const [cash, setCash] = useState(START_CASH);
  const [watchlist, setWatchlist] = useState<string[]>(START_WATCHLIST);
  const [activity, setActivity] = useState<Activity[]>([]);
  const [selected, setSelected] = useState<string | null>(null);
  const [query, setQuery] = useState('');
  const [ready, setReady] = useState(false);
  const asset = selected ? findAsset(selected) : undefined;
  const equity = Object.entries(positions).reduce(
    (sum, [ticker, position]) => sum + position.qty * (findAsset(ticker)?.price ?? 0),
    0,
  );

  useEffect(() => {
    AsyncStorage.getItem(STORAGE)
      .then((raw) => {
        if (!raw) return;
        const data = JSON.parse(raw) as {
          positions?: Record<string, Position>;
          cash?: number;
          watchlist?: string[];
          activity?: Activity[];
        };
        if (data.positions && typeof data.positions === 'object') setPositions(data.positions);
        if (typeof data.cash === 'number') setCash(data.cash);
        if (Array.isArray(data.watchlist)) setWatchlist(data.watchlist);
        if (Array.isArray(data.activity)) setActivity(data.activity);
      })
      .catch(() => {})
      .finally(() => setReady(true));
  }, []);
  useEffect(() => {
    if (ready) AsyncStorage.setItem(STORAGE, JSON.stringify({ positions, cash, watchlist, activity })).catch(() => {});
  }, [positions, cash, watchlist, activity, ready]);

  function trade(side: Side, qty: number) {
    if (!asset) return;
    const total = qty * asset.price;
    setPositions((old) => {
      const current = old[asset.ticker] ?? { qty: 0, avgCost: 0 };
      const nextQty = Math.round((current.qty + (side === 'Buy' ? qty : -qty)) * 1e8) / 1e8;
      const avgCost = side === 'Buy' ? (current.qty * current.avgCost + total) / nextQty : current.avgCost;
      const next = { ...old };
      if (nextQty > 0) next[asset.ticker] = { qty: nextQty, avgCost };
      else delete next[asset.ticker];
      return next;
    });
    setCash((old) => old + (side === 'Buy' ? -total : total));
    setActivity((old) => [{ id: `trade-${Date.now()}`, side, ticker: asset.ticker, qty, total }, ...old]);
  }

  const open = (ticker: string) => setSelected(ticker);
  const nav = (
    <Tabs
      navigationOnly
      orientation={wide ? 'vertical' : 'horizontal'}
      variant={wide ? 'chip' : 'line'}
      color={C.darkGreen}
      value={tab}
      onChange={(item) => {
        setTab(item as Tab);
        setSelected(null);
      }}
      items={TABS.map((item) => ({
        key: item,
        label: item[0].toUpperCase() + item.slice(1),
        icon: (
          <Icon
            name={TAB_ICONS[item]}
            color={tab === item && wide ? C.white : tab === item ? C.darkGreen : C.muted}
            size={wide ? 21 : 20}
          />
        ),
        content: null,
      }))}
    />
  );

  return (
    <SafeArea gap={0} flex={1} bg={C.white}>
      <StatusBar barStyle="dark-content" />
      <Block gap={0} flex={1} direction={wide ? 'row' : 'column'} maw={1280} w="100%" alignSelf="center">
        {wide && (
          <Block w={218} p={18} borderRightWidth={1} borderRightColor={C.line} gap={26}>
            <Text c={C.green} fw="bold" size={28}>
              sprout ↗
            </Text>
            {nav}
            <Block gap={0} flex={1} />
            <Text c={C.muted} size={11}>
              Simulated prices and trades
            </Text>
          </Block>
        )}
        <Block gap={0} flex={1}>
          {asset ? (
            <AssetScreen
              key={asset.ticker}
              asset={asset}
              position={positions[asset.ticker]}
              cash={cash}
              portfolioValue={cash + equity}
              watched={watchlist.includes(asset.ticker)}
              wide={wide}
              onBack={() => setSelected(null)}
              onToggleWatch={() =>
                setWatchlist((old) =>
                  old.includes(asset.ticker) ? old.filter((id) => id !== asset.ticker) : [...old, asset.ticker],
                )
              }
              onOpen={open}
              onOpenList={(list) => {
                setQuery(list);
                setTab('search');
                setSelected(null);
              }}
              onTrade={trade}
            />
          ) : (
            <>
              {!wide && (
                <Block
                  gap={0}
                  h={60}
                  px={18}
                  direction="row"
                  justify="space-between"
                  align="center"
                  borderBottomWidth={1}
                  borderBottomColor={C.line}
                >
                  <Text c={C.green} fw="bold" size={25}>
                    sprout ↗
                  </Text>
                  <Text c={C.muted} size={12}>
                    Demo portfolio
                  </Text>
                </Block>
              )}
              <ScrollArea key={tab} flex={1} contentProps={{ align: 'center', px: 20, pb: 35 }}>
                <Block gap={0} w="100%" maw={820}>
                  {tab === 'home' && (
                    <HomeScreen positions={positions} cash={cash} watchlist={watchlist} onOpen={open} wide={wide} />
                  )}
                  {tab === 'search' && <SearchScreen query={query} setQuery={setQuery} onOpen={open} wide={wide} />}
                  {tab === 'watchlist' && <WatchlistScreen watchlist={watchlist} onOpen={open} />}
                  {tab === 'account' && (
                    <AccountScreen positions={positions} cash={cash} activity={activity} onOpen={open} />
                  )}
                </Block>
              </ScrollArea>
            </>
          )}
          {!wide && !asset && (
            <Block gap={0} borderTopWidth={1} borderTopColor={C.line} bg={C.white}>
              {nav}
            </Block>
          )}
        </Block>
      </Block>
    </SafeArea>
  );
}

/** Chart labels inherit the app font and ink; without it SVG text falls back to the browser serif on web. */
function ChartTheme({ children }: { children: ReactNode }) {
  const theme = useTheme();
  const bridge = useMemo(
    () => ({
      textPrimary: C.ink,
      textSecondary: C.muted,
      background: C.white,
      grid: C.line,
      fontFamily: theme.fontFamily,
    }),
    [theme.fontFamily],
  );
  return <ChartThemeProvider hostThemeBridge={bridge}>{children}</ChartThemeProvider>;
}

export default function App() {
  return (
    <SafeAreaProvider>
      <PlocksProvider theme={{ colorScheme: 'light' }}>
        <ChartTheme>
          <SproutfolioScreen />
        </ChartTheme>
      </PlocksProvider>
    </SafeAreaProvider>
  );
}

components/AssetLogo.tsx

import { BrandIcon } from '@plocks/brands';
import { Block, Text } from '@plocks/ui';
import type { Asset } from '../data';
import { C } from '../theme';

/**
 * Company logo from @plocks/brands on a neutral disc. Coins have no registry
 * logo, so they get their own color with the currency glyph instead.
 */
export function AssetLogo({ asset, size = 42 }: { asset: Asset; size?: number }) {
  if (asset.brand) {
    return (
      <Block
        gap={0}
        w={size}
        h={size}
        radius={size / 2}
        bg={C.white}
        borderWidth={1}
        borderColor={C.line}
        align="center"
        justify="center"
      >
        <BrandIcon brand={asset.brand} size={Math.round(size * 0.56)} />
      </Block>
    );
  }
  return (
    <Block gap={0} w={size} h={size} radius={size / 2} bg={asset.color} align="center" justify="center">
      <Text c={C.white} fw="bold" size={Math.round(size * 0.5)} lh={Math.round(size * 0.6)}>
        {asset.glyph ?? asset.ticker[0]}
      </Text>
    </Block>
  );
}

components/common.tsx

import type { ReactNode } from 'react';
import { SparklineChart } from '@plocks/charts';
import { Block, Text } from '@plocks/ui';
import { sparkline, type Asset } from '../data';
import { C, pct, price, trend } from '../theme';
import { AssetLogo } from './AssetLogo';

export function SectionTitle({ children, action }: { children: ReactNode; action?: ReactNode }) {
  return (
    <Block gap={0} direction="row" justify="space-between" align="center" mt={34} mb={10}>
      <Text c={C.ink} fw="bold" size={21}>
        {children}
      </Text>
      {action}
    </Block>
  );
}

export interface Stat {
  label: string;
  value: string;
}

/** Label-over-value pairs, two per row on phones and four on wide screens. */
export function StatGrid({ stats, columns = 2 }: { stats: Stat[]; columns?: number }) {
  return (
    <Block gap={0} direction="row" wrap>
      {stats.map((stat) => (
        <Block
          key={stat.label}
          gap={2}
          w={`${100 / columns}%`}
          py={11}
          pr={12}
          borderBottomWidth={1}
          borderBottomColor={C.line}
        >
          <Text c={C.muted} size={12}>
            {stat.label}
          </Text>
          <Text c={C.ink} fw="semibold" size={15} numberOfLines={1}>
            {stat.value}
          </Text>
        </Block>
      ))}
    </Block>
  );
}

export function ChangeText({ value, size = 12 }: { value: number; size?: number }) {
  return (
    <Text c={trend(value)} fw="semibold" size={size}>
      {value >= 0 ? '▲' : '▼'} {pct(Math.abs(value)).replace('+', '')}
    </Text>
  );
}

/** A list row: logo, ticker, intraday sparkline, price and change. */
export function AssetRow({ asset, detail, onPress }: { asset: Asset; detail?: string; onPress: () => void }) {
  return (
    <Block
      onPress={onPress}
      accessibilityRole="button"
      accessibilityLabel={`View ${asset.name}`}
      direction="row"
      align="center"
      gap={12}
      py={12}
      borderBottomWidth={1}
      borderBottomColor={C.line}
    >
      <AssetLogo asset={asset} />
      <Block gap={0} flex={1}>
        <Text c={C.ink} fw="bold" size={15}>
          {asset.ticker}
        </Text>
        <Text c={C.muted} size={12} numberOfLines={1}>
          {detail ?? asset.name}
        </Text>
      </Block>
      <Block gap={0} w={76} h={34}>
        <SparklineChart
          data={sparkline(asset)}
          w={76}
          h={34}
          color={trend(asset.change)}
          strokeWidth={1.6}
          animation={{ enabled: false }}
          accessibilityLabel={`${asset.ticker} intraday trend`}
        />
      </Block>
      <Block gap={0} align="flex-end" miw={86}>
        <Text c={C.ink} fw="semibold" size={14}>
          {price(asset.price)}
        </Text>
        <ChangeText value={asset.change} />
      </Block>
    </Block>
  );
}

/** Compact card for horizontal strips such as movers and "people also own". */
export function AssetCard({ asset, onPress }: { asset: Asset; onPress: () => void }) {
  return (
    <Block
      onPress={onPress}
      accessibilityRole="button"
      accessibilityLabel={`View ${asset.name}`}
      w={148}
      p={14}
      gap={8}
      radius={16}
      borderWidth={1}
      borderColor={C.line}
      bg={C.white}
    >
      <Block gap={0} direction="row" justify="space-between" align="center">
        <AssetLogo asset={asset} size={34} />
        <ChangeText value={asset.change} />
      </Block>
      <Block gap={0}>
        <Text c={C.ink} fw="bold" size={15}>
          {asset.ticker}
        </Text>
        <Text c={C.muted} size={12} numberOfLines={1}>
          {asset.name}
        </Text>
      </Block>
      <SparklineChart
        data={sparkline(asset)}
        w={118}
        h={30}
        color={trend(asset.change)}
        fill
        fillOpacity={0.12}
        strokeWidth={1.5}
        animation={{ enabled: false }}
        accessibilityLabel={`${asset.ticker} intraday trend`}
      />
      <Text c={C.ink} fw="semibold" size={14}>
        {price(asset.price)}
      </Text>
    </Block>
  );
}

components/PriceChart.tsx

import { AreaChart, CandlestickChart, LineChart } from '@plocks/charts';
import { Block } from '@plocks/ui';
import type { History, Range } from '../data';
import { C, money, price } from '../theme';

export type ChartMode = 'line' | 'candles';

/**
 * The stock-page price chart: a scrubbable line by default, OHLC candles on
 * request. Green or red follows the move over the selected range, and the
 * dashed baseline marks where the range opened (yesterday's close on 1D).
 */
export function PriceChart({
  history,
  range,
  mode,
  height = 240,
  label,
}: {
  history: History;
  range: Range;
  mode: ChartMode;
  height?: number;
  label: string;
}) {
  const up = history.end >= history.start;
  const color = up ? C.green : C.red;
  const baseline = { y: history.start, color: C.muted, dashed: true };
  return (
    <Block gap={0} w="100%" h={height}>
      {mode === 'line' ? (
        <LineChart
          key={`line-${range}`}
          data={history.points}
          h={height}
          lineColor={color}
          lineThickness={2.5}
          showPoints={false}
          xAxis={{ show: false }}
          yAxis={{ show: false }}
          grid={{ show: false }}
          referenceLines={[baseline]}
          enableCrosshair
          liveTooltip
          tooltip={{
            show: true,
            formatter: (point) => `${price(point.y)} · ${point.label ?? ''}`,
          }}
          accessibilityLabel={`${label} price over ${range}`}
        />
      ) : (
        <CandlestickChart
          key={`candles-${range}`}
          h={height}
          series={[
            {
              id: 'price',
              name: label,
              data: history.candles,
              colorBull: C.green,
              colorBear: C.red,
              wickColor: C.muted,
            },
          ]}
          xAxis={{ show: false }}
          yAxis={{ show: true, labelFormatter: (value) => money(value, value >= 1000 ? 0 : 2), labelColor: C.muted }}
          grid={{ show: true, color: C.line }}
          enableCrosshair
          liveTooltip
          tooltip={{
            show: true,
            formatter: (candle) =>
              `O ${price(candle.open)}  H ${price(candle.high)}  L ${price(candle.low)}  C ${price(candle.close)}`,
          }}
          accessibilityLabel={`${label} candlestick chart over ${range}`}
        />
      )}
    </Block>
  );
}

/** Portfolio value over time, as a filled area. */
export function PortfolioChart({
  values,
  labels,
  height = 200,
}: {
  values: number[];
  labels: string[];
  height?: number;
}) {
  const up = values[values.length - 1] >= values[0];
  const color = up ? C.green : C.red;
  return (
    <Block gap={0} w="100%" h={height}>
      <AreaChart
        data={values.map((y, x) => ({ x, y, label: labels[x] }))}
        h={height}
        lineColor={color}
        lineThickness={2.5}
        fillColor={color}
        fillOpacity={0.24}
        showPoints={false}
        xAxis={{ show: false }}
        yAxis={{ show: false }}
        grid={{ show: false }}
        referenceLines={[{ y: values[0], color: C.muted, dashed: true }]}
        enableCrosshair
        liveTooltip
        tooltip={{ show: true, formatter: (point) => `${money(point.y)} · ${point.label ?? ''}` }}
        accessibilityLabel="Portfolio value chart"
      />
    </Block>
  );
}

components/TradePanel.tsx

import { useState } from 'react';
import { Block, Button, Input, SegmentedControl, Text } from '@plocks/ui';
import type { Asset, Position } from '../data';
import { C, money, quantity } from '../theme';

export type Side = 'Buy' | 'Sell';

/**
 * Order ticket. Stocks trade in whole shares; coins in fractional amounts. Used
 * inline beside the stock page on wide screens and in a bottom sheet on phones.
 */
export function TradePanel({
  asset,
  position,
  cash,
  initialSide = 'Buy',
  onSubmit,
  onCancel,
}: {
  asset: Asset;
  position?: Position;
  cash: number;
  initialSide?: Side;
  onSubmit: (side: Side, qty: number) => void;
  onCancel?: () => void;
}) {
  const [side, setSide] = useState<Side>(initialSide);
  const [amount, setAmount] = useState(asset.kind === 'crypto' ? '0.01' : '1');
  const crypto = asset.kind === 'crypto';
  const owned = position?.qty ?? 0;
  const qty = Number(amount);
  const total = qty * asset.price;
  const unit = crypto ? asset.ticker : qty === 1 ? 'share' : 'shares';
  const validAmount = Number.isFinite(qty) && qty > 0 && (crypto || Number.isInteger(qty));
  const valid = validAmount && (side === 'Buy' ? total <= cash : qty <= owned + 1e-9);
  return (
    <Block gap={12}>
      <SegmentedControl
        data={[
          { value: 'Buy', label: 'Buy' },
          { value: 'Sell', label: 'Sell', disabled: !owned },
        ]}
        value={side}
        onChange={(value) => setSide(value as Side)}
        color={side === 'Buy' ? C.green : C.red}
        fullWidth
        size="sm"
        accessibilityLabel="Order side"
      />
      <Text c={C.ink} fw="bold" size={18}>
        {side} {asset.ticker}
      </Text>
      <Block gap={0} direction="row" justify="space-between">
        <Text c={C.muted} size={13}>
          Market price
        </Text>
        <Text c={C.ink} fw="semibold" size={13}>
          {money(asset.price)}
        </Text>
      </Block>
      <Input
        variant="outline"
        label={crypto ? `Amount (${asset.ticker})` : 'Shares'}
        value={amount}
        onChangeText={setAmount}
        keyboardType={crypto ? 'decimal-pad' : 'number-pad'}
        placeholder={crypto ? '0.00' : 'Number of shares'}
        mb={0}
        radius={10}
        inputColor={C.ink}
      />
      <Block gap={0} direction="row" justify="space-between">
        <Text c={C.muted} size={13}>
          Estimated {side === 'Buy' ? 'cost' : 'credit'}
        </Text>
        <Text c={C.ink} fw="bold" size={13}>
          {validAmount ? money(total) : '—'}
        </Text>
      </Block>
      <Text c={C.muted} size={12}>
        {side === 'Buy'
          ? `${money(cash)} buying power available`
          : `${quantity(owned)} ${crypto ? asset.ticker : 'shares'} available`}
      </Text>
      <Button
        title={valid ? `Review ${side.toLowerCase()} · ${quantity(qty)} ${unit}` : `${side} ${asset.ticker}`}
        color={side === 'Buy' ? C.green : C.red}
        disabled={!valid}
        fullWidth
        onPress={() => {
          onSubmit(side, qty);
          setAmount(crypto ? '0.01' : '1');
        }}
      />
      {onCancel && <Button title="Cancel" variant="subtle" color={C.ink} fullWidth onPress={onCancel} />}
      <Text c={C.muted} size={11}>
        Simulated order with sample prices. No real trade is placed.
      </Text>
    </Block>
  );
}

data.ts

import type { BrandName } from '@plocks/brands';

/**
 * Every number in this file is fictional sample data, generated locally from a
 * seeded random walk so the app renders the same charts on every launch. Company
 * names and logos identify real businesses; their prices and statistics do not.
 */

export type AssetKind = 'stock' | 'crypto';
export type Range = '1D' | '1W' | '1M' | '3M' | '1Y' | '5Y';
export const RANGES: Range[] = ['1D', '1W', '1M', '3M', '1Y', '5Y'];

export interface Asset {
  ticker: string;
  name: string;
  kind: AssetKind;
  price: number;
  /** Percent change today (24h for crypto). */
  change: number;
  sector: string;
  color: string;
  brand?: BrandName;
  /** Fallback mark for assets without a registry logo. */
  glyph?: string;
  about: string;
  lists: string[];
  // Stocks
  ceo?: string;
  employees?: number;
  hq?: string;
  founded?: number;
  /** Shares outstanding, billions. */
  sharesOut?: number;
  pe?: number;
  dividendYield?: number;
  // Crypto
  circulating?: number;
  maxSupply?: number | null;
  launched?: number;
  consensus?: string;
}

export const ASSETS: Asset[] = [
  {
    ticker: 'AAPL',
    name: 'Apple',
    kind: 'stock',
    price: 231.48,
    change: 1.24,
    sector: 'Technology',
    color: '#111111',
    brand: 'apple',
    about:
      'Apple designs consumer electronics, software, and services, including the iPhone, Mac, iPad, Apple Watch, and a growing subscription business spanning music, cloud storage, and payments.',
    lists: ['Big Tech', 'Hardware'],
    ceo: 'Tim Cook',
    employees: 164000,
    hq: 'Cupertino, CA',
    founded: 1976,
    sharesOut: 15.1,
    pe: 34.2,
    dividendYield: 0.44,
  },
  {
    ticker: 'MSFT',
    name: 'Microsoft',
    kind: 'stock',
    price: 428.16,
    change: 0.62,
    sector: 'Technology',
    color: '#00A4EF',
    brand: 'microsoft',
    about:
      'Microsoft builds productivity software, the Windows platform, Azure cloud infrastructure, gaming hardware and content, and AI tooling for businesses and developers.',
    lists: ['Big Tech', 'Cloud'],
    ceo: 'Satya Nadella',
    employees: 228000,
    hq: 'Redmond, WA',
    founded: 1975,
    sharesOut: 7.43,
    pe: 36.8,
    dividendYield: 0.72,
  },
  {
    ticker: 'AMZN',
    name: 'Amazon',
    kind: 'stock',
    price: 189.72,
    change: -0.85,
    sector: 'Consumer',
    color: '#FF9900',
    brand: 'amazon',
    about:
      'Amazon runs a global online marketplace and logistics network, the AWS cloud platform, streaming media, devices, and a fast-growing advertising business.',
    lists: ['Big Tech', 'Cloud', 'E-commerce'],
    ceo: 'Andy Jassy',
    employees: 1550000,
    hq: 'Seattle, WA',
    founded: 1994,
    sharesOut: 10.5,
    pe: 41.5,
  },
  {
    ticker: 'GOOGL',
    name: 'Alphabet',
    kind: 'stock',
    price: 172.35,
    change: 2.11,
    sector: 'Communication',
    color: '#4285F4',
    brand: 'google',
    about:
      'Alphabet is the parent of Google, operating Search, YouTube, Android, Chrome, and Google Cloud, along with longer-term bets in autonomous driving and life sciences.',
    lists: ['Big Tech', 'Cloud', 'Advertising'],
    ceo: 'Sundar Pichai',
    employees: 183000,
    hq: 'Mountain View, CA',
    founded: 1998,
    sharesOut: 12.3,
    pe: 24.9,
    dividendYield: 0.46,
  },
  {
    ticker: 'META',
    name: 'Meta Platforms',
    kind: 'stock',
    price: 562.9,
    change: -1.47,
    sector: 'Communication',
    color: '#0866FF',
    brand: 'meta',
    about:
      'Meta operates Facebook, Instagram, WhatsApp, Messenger, and Threads, and invests heavily in AI models and mixed-reality hardware through Reality Labs.',
    lists: ['Big Tech', 'Social Media', 'Advertising'],
    ceo: 'Mark Zuckerberg',
    employees: 72000,
    hq: 'Menlo Park, CA',
    founded: 2004,
    sharesOut: 2.53,
    pe: 27.3,
    dividendYield: 0.36,
  },
  {
    ticker: 'SPOT',
    name: 'Spotify',
    kind: 'stock',
    price: 412.55,
    change: 3.38,
    sector: 'Communication',
    color: '#1DB954',
    brand: 'spotify',
    about:
      'Spotify is an audio streaming service offering music, podcasts, and audiobooks through free ad-supported and premium subscription tiers in more than 180 markets.',
    lists: ['Streaming', 'Subscriptions'],
    ceo: 'Alex Norström & Gustav Söderström',
    employees: 7300,
    hq: 'Stockholm, Sweden',
    founded: 2006,
    sharesOut: 0.204,
    pe: 68.4,
  },
  {
    ticker: 'RDDT',
    name: 'Reddit',
    kind: 'stock',
    price: 128.4,
    change: 4.92,
    sector: 'Communication',
    color: '#FF4500',
    brand: 'reddit',
    about:
      'Reddit hosts thousands of interest-based communities where people post, discuss, and vote on content, and earns revenue from advertising and data licensing.',
    lists: ['Social Media', 'Advertising'],
    ceo: 'Steve Huffman',
    employees: 2200,
    hq: 'San Francisco, CA',
    founded: 2005,
    sharesOut: 0.18,
    pe: 92.1,
  },
  {
    ticker: 'PYPL',
    name: 'PayPal',
    kind: 'stock',
    price: 71.26,
    change: -0.38,
    sector: 'Financials',
    color: '#003087',
    brand: 'paypal',
    about:
      'PayPal runs digital payment platforms for consumers and merchants, including PayPal checkout, Venmo, Braintree, and Xoom cross-border transfers.',
    lists: ['Payments', 'Fintech'],
    ceo: 'Enrique Lores',
    employees: 24500,
    hq: 'San Jose, CA',
    founded: 1998,
    sharesOut: 1.0,
    pe: 16.8,
    dividendYield: 0.7,
  },
  {
    ticker: 'V',
    name: 'Visa',
    kind: 'stock',
    price: 296.84,
    change: 0.41,
    sector: 'Financials',
    color: '#1A1F71',
    brand: 'visa',
    about:
      'Visa operates one of the largest electronic payment networks in the world, connecting cardholders, merchants, and financial institutions across more than 200 countries.',
    lists: ['Payments'],
    ceo: 'Ryan McInerney',
    employees: 31600,
    hq: 'San Francisco, CA',
    founded: 1958,
    sharesOut: 1.95,
    pe: 31.2,
    dividendYield: 0.78,
  },
  {
    ticker: 'MA',
    name: 'Mastercard',
    kind: 'stock',
    price: 512.37,
    change: 0.27,
    sector: 'Financials',
    color: '#EB001B',
    brand: 'mastercard',
    about:
      'Mastercard runs a global payments network and offers fraud prevention, data analytics, and open-banking services to banks, merchants, and governments.',
    lists: ['Payments'],
    ceo: 'Michael Miebach',
    employees: 35300,
    hq: 'Purchase, NY',
    founded: 1966,
    sharesOut: 0.92,
    pe: 36.5,
    dividendYield: 0.58,
  },
  {
    ticker: 'AXP',
    name: 'American Express',
    kind: 'stock',
    price: 268.91,
    change: -0.66,
    sector: 'Financials',
    color: '#006FCF',
    brand: 'amex',
    about:
      'American Express issues charge and credit cards, runs its own payment network, and provides travel and lifestyle services to consumers and businesses.',
    lists: ['Payments', 'Banks'],
    ceo: 'Stephen Squeri',
    employees: 75100,
    hq: 'New York, NY',
    founded: 1850,
    sharesOut: 0.7,
    pe: 19.4,
    dividendYield: 1.12,
  },
  {
    ticker: 'PINS',
    name: 'Pinterest',
    kind: 'stock',
    price: 33.18,
    change: 1.95,
    sector: 'Communication',
    color: '#E60023',
    brand: 'pinterest',
    about:
      'Pinterest is a visual discovery platform where people save and shop ideas for home, style, food, and travel, funded by advertising.',
    lists: ['Social Media', 'Advertising'],
    ceo: 'Bill Ready',
    employees: 4700,
    hq: 'San Francisco, CA',
    founded: 2008,
    sharesOut: 0.68,
    pe: 28.6,
  },
  {
    ticker: 'SNAP',
    name: 'Snap',
    kind: 'stock',
    price: 11.42,
    change: -2.74,
    sector: 'Communication',
    color: '#FFFC00',
    brand: 'snapchat',
    about:
      'Snap makes Snapchat, a camera and messaging app built around disappearing photos and stories, plus Spectacles augmented-reality glasses.',
    lists: ['Social Media'],
    ceo: 'Evan Spiegel',
    employees: 4900,
    hq: 'Santa Monica, CA',
    founded: 2011,
    sharesOut: 1.68,
  },
  {
    ticker: 'ZM',
    name: 'Zoom Communications',
    kind: 'stock',
    price: 76.05,
    change: 0.88,
    sector: 'Technology',
    color: '#0B5CFF',
    brand: 'zoom',
    about:
      'Zoom provides video meetings, team chat, phone, contact-center, and AI companion tools used by businesses, schools, and individuals.',
    lists: ['Cloud', 'Subscriptions'],
    ceo: 'Eric Yuan',
    employees: 7400,
    hq: 'San Jose, CA',
    founded: 2011,
    sharesOut: 0.31,
    pe: 23.7,
  },
  {
    ticker: 'BTC',
    name: 'Bitcoin',
    kind: 'crypto',
    price: 68420.15,
    change: 2.36,
    sector: 'Crypto',
    color: '#F7931A',
    glyph: '₿',
    about:
      'Bitcoin is the first decentralized digital currency. Transactions are verified by a global network of miners and recorded on a public ledger, with issuance capped at 21 million coins.',
    lists: ['Crypto'],
    circulating: 19.79e6,
    maxSupply: 21e6,
    launched: 2009,
    consensus: 'Proof of work',
  },
  {
    ticker: 'ETH',
    name: 'Ethereum',
    kind: 'crypto',
    price: 3384.62,
    change: -1.18,
    sector: 'Crypto',
    color: '#627EEA',
    glyph: 'Ξ',
    about:
      'Ethereum is a programmable blockchain for smart contracts and decentralized applications. Ether pays for computation and secures the network through staking.',
    lists: ['Crypto'],
    circulating: 120.4e6,
    maxSupply: null,
    launched: 2015,
    consensus: 'Proof of stake',
  },
  {
    ticker: 'SOL',
    name: 'Solana',
    kind: 'crypto',
    price: 162.48,
    change: 5.71,
    sector: 'Crypto',
    color: '#9945FF',
    glyph: '◎',
    about:
      'Solana is a high-throughput blockchain designed for fast, low-cost transactions, popular for payments, trading, and consumer apps.',
    lists: ['Crypto'],
    circulating: 470e6,
    maxSupply: null,
    launched: 2020,
    consensus: 'Proof of stake + history',
  },
];

export const STOCKS = ASSETS.filter((asset) => asset.kind === 'stock');
export const CRYPTO = ASSETS.filter((asset) => asset.kind === 'crypto');
export const findAsset = (ticker: string) => ASSETS.find((asset) => asset.ticker === ticker);

export interface Position {
  qty: number;
  avgCost: number;
}
export const START_POSITIONS: Record<string, Position> = {
  AAPL: { qty: 12, avgCost: 168.4 },
  MSFT: { qty: 4, avgCost: 352.1 },
  GOOGL: { qty: 10, avgCost: 141.2 },
  SPOT: { qty: 6, avgCost: 288.75 },
  V: { qty: 5, avgCost: 271.3 },
  PINS: { qty: 30, avgCost: 38.9 },
  BTC: { qty: 0.085, avgCost: 52310 },
  ETH: { qty: 1.4, avgCost: 2875 },
};
export const START_CASH = 2450;
export const START_WATCHLIST = ['META', 'RDDT', 'MA', 'SOL'];

// ---------------------------------------------------------------------------
// Seeded randomness

function hash(text: string) {
  let h = 2166136261;
  for (let i = 0; i < text.length; i++) {
    h ^= text.charCodeAt(i);
    h = Math.imul(h, 16777619);
  }
  return h >>> 0;
}

export function rng(seed: string) {
  let a = hash(seed);
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function gauss(next: () => number) {
  const u = Math.max(next(), 1e-9);
  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * next());
}

const between = (next: () => number, min: number, max: number) => min + (max - min) * next();

// ---------------------------------------------------------------------------
// Price history

/** Fixed "now" so every launch draws the same timeline. */
const NOW = Date.UTC(2026, 9, 29, 20, 0);
const DAY = 86400000;

interface RangeSpec {
  candles: number;
  steps: number;
  sigma: number;
  span: number;
  returns: [number, number];
}
const SPECS: Record<Range, RangeSpec> = {
  '1D': { candles: 26, steps: 3, sigma: 0.012, span: 0.27 * DAY, returns: [0, 0] },
  '1W': { candles: 28, steps: 3, sigma: 0.03, span: 7 * DAY, returns: [-0.05, 0.07] },
  '1M': { candles: 22, steps: 3, sigma: 0.055, span: 30 * DAY, returns: [-0.08, 0.12] },
  '3M': { candles: 26, steps: 3, sigma: 0.09, span: 91 * DAY, returns: [-0.12, 0.2] },
  '1Y': { candles: 26, steps: 3, sigma: 0.16, span: 365 * DAY, returns: [-0.2, 0.55] },
  '5Y': { candles: 30, steps: 3, sigma: 0.3, span: 1826 * DAY, returns: [-0.25, 2.4] },
};

export interface PricePoint {
  x: number;
  y: number;
  label: string;
}
export interface Candle {
  x: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}
export interface History {
  points: PricePoint[];
  candles: Candle[];
  start: number;
  end: number;
}

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function clock(date: Date) {
  const hours = date.getUTCHours();
  const minutes = date.getUTCMinutes();
  return `${hours % 12 || 12}:${String(minutes).padStart(2, '0')} ${hours >= 12 ? 'PM' : 'AM'}`;
}
function timeLabel(range: Range, time: number) {
  // Labels are written in market time (ET), four hours behind the UTC clock.
  const date = new Date(time - 4 * 3600000);
  if (range === '1D') return clock(date);
  if (range === '1W') return `${WEEKDAYS[date.getUTCDay()]} ${clock(date)}`;
  return `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`;
}

const historyCache = new Map<string, History>();

/** A seeded bridge walk that starts at the range's opening price and ends at today's price. */
export function getHistory(asset: Asset, range: Range): History {
  const key = `${asset.ticker}:${range}`;
  const cached = historyCache.get(key);
  if (cached) return cached;
  const spec = SPECS[range];
  const next = rng(key);
  const crypto = asset.kind === 'crypto';
  const vol = crypto ? 2 : 1;
  const end = asset.price;
  const rangeReturn = range === '1D' ? asset.change / 100 : between(next, spec.returns[0] * vol, spec.returns[1] * vol);
  const start = end / (1 + rangeReturn);
  const count = spec.candles * spec.steps;
  const stepSigma = (spec.sigma * vol) / Math.sqrt(count);
  const walk = [0];
  for (let i = 1; i <= count; i++) walk.push(walk[i - 1] + gauss(next) * stepSigma);
  const logStart = Math.log(start);
  const logEnd = Math.log(end);
  const span = crypto && range === '1D' ? DAY : spec.span;
  const values = walk.map((value, i) => {
    const t = i / count;
    return Math.exp(logStart + (logEnd - logStart) * t + value - t * walk[count]);
  });
  const points = values.map((y, i) => ({ x: i, y, label: timeLabel(range, NOW - span * (1 - i / count)) }));
  const baseVolume = averageVolume(asset) / (range === '1D' ? spec.candles : 1);
  const candles: Candle[] = [];
  for (let c = 0; c < spec.candles; c++) {
    const chunk = values.slice(c * spec.steps, (c + 1) * spec.steps + 1);
    const open = chunk[0];
    const close = chunk[chunk.length - 1];
    const wick = 1 + stepSigma * 0.6 * next();
    candles.push({
      x: c,
      open,
      close,
      high: Math.max(...chunk) * wick,
      low: Math.min(...chunk) / wick,
      volume: baseVolume * between(next, 0.55, 1.6) * (range === '1D' && (c < 3 || c > spec.candles - 4) ? 1.8 : 1),
    });
  }
  const history = { points, candles, start, end };
  historyCache.set(key, history);
  return history;
}

/** Twenty-odd intraday points for list-row sparklines. */
export function sparkline(asset: Asset) {
  return getHistory(asset, '1D')
    .points.filter((_, i) => i % 3 === 0)
    .map((point) => point.y);
}

// ---------------------------------------------------------------------------
// Statistics

export function averageVolume(asset: Asset) {
  const next = rng(`${asset.ticker}:volume`);
  if (asset.kind === 'crypto') return marketCap(asset) * between(next, 0.025, 0.06);
  return (asset.sharesOut ?? 1) * 1e9 * between(next, 0.003, 0.012);
}

export function marketCap(asset: Asset) {
  if (asset.kind === 'crypto') return (asset.circulating ?? 0) * asset.price;
  return (asset.sharesOut ?? 1) * 1e9 * asset.price;
}

export interface KeyStats {
  open: number;
  high: number;
  low: number;
  volume: number;
  avgVolume: number;
  marketCap: number;
  low52: number;
  high52: number;
  prevClose: number;
}

export function keyStats(asset: Asset): KeyStats {
  const day = getHistory(asset, '1D');
  const year = getHistory(asset, '1Y');
  const next = rng(`${asset.ticker}:stats`);
  const avgVolume = averageVolume(asset);
  return {
    open: day.candles[0].open,
    high: Math.max(...day.candles.map((candle) => candle.high)),
    low: Math.min(...day.candles.map((candle) => candle.low)),
    volume: avgVolume * between(next, 0.7, 1.4),
    avgVolume,
    marketCap: marketCap(asset),
    low52: Math.min(...year.candles.map((candle) => candle.low)),
    high52: Math.max(...year.candles.map((candle) => candle.high)),
    prevClose: day.start,
  };
}

export interface Ratings {
  buy: number;
  hold: number;
  sell: number;
  targetLow: number;
  targetAvg: number;
  targetHigh: number;
}

export function analystRatings(asset: Asset): Ratings {
  const next = rng(`${asset.ticker}:ratings`);
  const total = Math.round(between(next, 24, 58));
  const buyShare = between(next, 0.35, 0.9);
  const buy = Math.round(total * buyShare);
  const sell = Math.round((total - buy) * between(next, 0, 0.35));
  const targetAvg = asset.price * between(next, 1.02, 1.22);
  return {
    buy,
    hold: total - buy - sell,
    sell,
    targetLow: asset.price * between(next, 0.72, 0.92),
    targetAvg,
    targetHigh: targetAvg * between(next, 1.12, 1.3),
  };
}

export interface Quarter {
  label: string;
  estimate: number;
  actual: number;
  revenue: number;
  margin: number;
}
const QUARTERS = ["Q4 '25", "Q1 '26", "Q2 '26", "Q3 '26"];

export function earnings(asset: Asset) {
  const next = rng(`${asset.ticker}:earnings`);
  const annualEps = asset.pe ? asset.price / asset.pe : -asset.price * 0.02;
  const revenueBase = marketCap(asset) / between(next, 5, 11) / 4;
  const baseMargin = asset.pe ? between(next, 12, 34) : between(next, -8, 2);
  const quarters: Quarter[] = QUARTERS.map((label, i) => {
    const estimate = (annualEps / 4) * (0.9 + i * 0.04) * between(next, 0.94, 1.06);
    const beat = next() < 0.75 ? between(next, 0.01, 0.09) : -between(next, 0.01, 0.05);
    return {
      label,
      estimate,
      actual: estimate + Math.abs(estimate) * beat,
      revenue: revenueBase * (0.9 + i * 0.035) * between(next, 0.97, 1.03),
      margin: baseMargin + i * 0.4 + between(next, -1.5, 1.5),
    };
  });
  const last = quarters[quarters.length - 1];
  return {
    quarters,
    next: { label: "Q4 '26", date: 'Jan 28, 2027', estimate: last.estimate * between(next, 1.01, 1.08) },
  };
}

export interface NewsItem {
  id: string;
  source: string;
  age: string;
  title: string;
  move: number;
}
const SOURCES = ['Market Wire', 'The Ledger', 'Sprout Daily', 'Ticker Tape', 'Capital Brief'];
const STOCK_HEADLINES = [
  '{name} shares move after analysts revisit price targets',
  'What to watch from {name} ahead of next quarter',
  '{name} expands buyback program, sample filing shows',
  'Options traders lean bullish on {ticker} into the close',
  'Is {name} still a long-term hold? Three charts to consider',
];
const CRYPTO_HEADLINES = [
  '{name} climbs as on-chain activity hits a monthly high',
  'Funds tracking {name} see another week of inflows',
  'Why {ticker} volatility is cooling this month',
  '{name} developers outline the next network upgrade',
  'Miners and stakers: who is holding {ticker} now',
];

export function news(asset: Asset): NewsItem[] {
  const next = rng(`${asset.ticker}:news`);
  const templates = asset.kind === 'crypto' ? CRYPTO_HEADLINES : STOCK_HEADLINES;
  return templates.slice(0, 4).map((template, i) => ({
    id: `${asset.ticker}-news-${i}`,
    source: SOURCES[Math.floor(next() * SOURCES.length)],
    age: i === 0 ? `${1 + Math.floor(next() * 50)}m` : `${i * 3 + Math.floor(next() * 3)}h`,
    title: template.replace('{name}', asset.name).replace('{ticker}', asset.ticker),
    move: asset.change + between(next, -1.2, 1.2),
  }));
}

/** Assets that share a list with this one, ordered by overlap. */
export function peopleAlsoOwn(asset: Asset) {
  return ASSETS.filter((other) => other.ticker !== asset.ticker && other.kind === asset.kind)
    .map((other) => ({
      other,
      score:
        other.lists.filter((list) => asset.lists.includes(list)).length + (other.sector === asset.sector ? 0.5 : 0),
    }))
    .sort((a, b) => b.score - a.score || a.other.ticker.localeCompare(b.other.ticker))
    .slice(0, 6)
    .map((item) => item.other);
}

export const LISTS = Array.from(new Set(ASSETS.flatMap((asset) => asset.lists)));
export const assetsInList = (list: string) => ASSETS.filter((asset) => asset.lists.includes(list));

// ---------------------------------------------------------------------------
// Market-wide

export const SECTORS = [
  'Technology',
  'Communication',
  'Financials',
  'Consumer',
  'Healthcare',
  'Energy',
  'Industrials',
  'Utilities',
  'Real Estate',
];
export const SECTOR_PERIODS = ['1D', '1W', '1M', '3M', 'YTD', '1Y'];
const PERIOD_SCALE = [1.2, 2.6, 4.5, 7, 11, 14];

export const SECTOR_RETURNS: number[][] = SECTORS.map((sector) => {
  const next = rng(`sector:${sector}`);
  const bias = between(next, -0.4, 0.9);
  return PERIOD_SCALE.map((scale) => Math.round((bias + between(next, -1, 1)) * scale * 10) / 10);
});

export const INDEXES = [
  { name: 'S&P 500', value: 5864.21, change: 0.74 },
  { name: 'Nasdaq', value: 18512.6, change: 1.12 },
  { name: 'Dow', value: 42390.8, change: 0.21 },
];

/** Twelve months of dividend income from the demo positions. */
export const DIVIDENDS = (() => {
  const next = rng('dividends');
  return ['Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'].map((month, i) => ({
    category: month,
    value: Math.round((i % 3 === 2 ? between(next, 9, 14) : between(next, 1.5, 5)) * 100) / 100,
  }));
})();

index.ts

import { registerRootComponent } from 'expo';
import App from './App';

registerRootComponent(App);

screens/AssetScreen.tsx

import { useState } from 'react';
import { BulletChart, ComboChart, GroupedBarChart, RadialBarChart } from '@plocks/charts';
import { Badge, Block, Button, Dialog, IconButton, Progress, ScrollArea, SegmentedControl, Text } from '@plocks/ui';
import { AssetLogo } from '../components/AssetLogo';
import { AssetCard, SectionTitle, StatGrid, type Stat } from '../components/common';
import { PriceChart, type ChartMode } from '../components/PriceChart';
import { TradePanel, type Side } from '../components/TradePanel';
import {
  analystRatings,
  earnings,
  getHistory,
  keyStats,
  news,
  peopleAlsoOwn,
  RANGES,
  type Asset,
  type Position,
  type Range,
} from '../data';
import { C, compact, money, pct, price, quantity, signed, trend } from '../theme';

const RANGE_WORDS: Record<Range, string> = {
  '1D': 'Today',
  '1W': 'Past week',
  '1M': 'Past month',
  '3M': 'Past 3 months',
  '1Y': 'Past year',
  '5Y': 'Past 5 years',
};

export function AssetScreen({
  asset,
  position,
  cash,
  portfolioValue,
  watched,
  wide,
  onBack,
  onToggleWatch,
  onOpen,
  onOpenList,
  onTrade,
}: {
  asset: Asset;
  position?: Position;
  cash: number;
  portfolioValue: number;
  watched: boolean;
  wide: boolean;
  onBack: () => void;
  onToggleWatch: () => void;
  onOpen: (ticker: string) => void;
  onOpenList: (list: string) => void;
  onTrade: (side: Side, qty: number) => void;
}) {
  const [range, setRange] = useState<Range>('1D');
  const [mode, setMode] = useState<ChartMode>('line');
  const [ticket, setTicket] = useState<Side | null>(null);
  const crypto = asset.kind === 'crypto';
  const history = getHistory(asset, range);
  const move = history.end - history.start;
  const movePct = (move / history.start) * 100;
  const stats = keyStats(asset);
  const owned = position && position.qty > 0 ? position : undefined;
  const columns = wide ? 3 : 2;

  const header = (
    <Block
      gap={0}
      h={56}
      px={8}
      direction="row"
      align="center"
      justify="space-between"
      borderBottomWidth={1}
      borderBottomColor={C.line}
    >
      <IconButton
        icon="chevronLeft"
        variant="ghost"
        iconColor={C.ink}
        accessibilityLabel="Back to list"
        onPress={onBack}
      />
      <Text c={C.ink} fw="bold" size={15}>
        {asset.ticker}
      </Text>
      <IconButton
        icon="bookmark"
        iconVariant={watched ? 'filled' : 'outlined'}
        variant="ghost"
        iconColor={C.darkGreen}
        accessibilityLabel={watched ? 'Remove from watchlist' : 'Add to watchlist'}
        onPress={onToggleWatch}
      />
    </Block>
  );

  const content = (
    <Block gap={0} w="100%" maw={760}>
      <Block gap={12} pt={22} direction="row" align="center">
        <AssetLogo asset={asset} size={48} />
        <Block gap={0} flex={1}>
          <Text c={C.ink} fw="bold" size={24} numberOfLines={1}>
            {asset.name}
          </Text>
          <Text c={C.muted} size={13}>
            {asset.ticker} · {crypto ? 'Cryptocurrency' : asset.sector}
          </Text>
        </Block>
      </Block>
      <Text c={C.ink} fw="bold" size={36} mt={16}>
        {price(asset.price)}
      </Text>
      <Text c={trend(move)} fw="semibold" size={14}>
        {signed(move)} ({pct(movePct)}) {RANGE_WORDS[range]}
      </Text>
      {range !== '1D' && (
        <Text c={trend(asset.change)} size={12} mt={2}>
          {pct(asset.change)} {crypto ? 'past 24 hours' : 'today'}
        </Text>
      )}

      <Block gap={0} mt={18}>
        <PriceChart history={history} range={range} mode={mode} label={asset.name} height={wide ? 280 : 230} />
      </Block>
      <Block gap={10} mt={10} direction="row" align="center">
        <Block gap={0} flex={1}>
          <SegmentedControl
            data={RANGES}
            value={range}
            onChange={(value) => setRange(value as Range)}
            color={trend(move)}
            variant="ghost"
            size="sm"
            fullWidth
            accessibilityLabel="Chart time range"
          />
        </Block>
        <SegmentedControl
          data={[
            { value: 'line', label: 'Line' },
            { value: 'candles', label: 'Candles' },
          ]}
          value={mode}
          onChange={(value) => setMode(value as ChartMode)}
          size="sm"
          color={C.ink}
          accessibilityLabel="Chart style"
        />
      </Block>

      {owned && (
        <PositionSection asset={asset} position={owned} prevClose={stats.prevClose} portfolioValue={portfolioValue} />
      )}

      <SectionTitle>About</SectionTitle>
      <Text c={C.ink} size={14} lh={21}>
        {asset.about}
      </Text>
      <StatGrid
        columns={wide && !crypto ? 4 : columns}
        stats={
          crypto
            ? [
                { label: 'Launched', value: String(asset.launched) },
                { label: 'Consensus', value: asset.consensus ?? '—' },
                { label: 'Category', value: asset.lists.join(', ') },
              ]
            : [
                { label: 'CEO', value: asset.ceo ?? '—' },
                { label: 'Employees', value: (asset.employees ?? 0).toLocaleString('en-US') },
                { label: 'Headquarters', value: asset.hq ?? '—' },
                { label: 'Founded', value: String(asset.founded) },
              ]
        }
      />

      <SectionTitle>Key statistics</SectionTitle>
      <StatGrid columns={columns} stats={crypto ? cryptoStats(asset, stats) : stockStats(asset, stats)} />
      <Text c={C.muted} fw="semibold" size={12} mt={20} mb={8}>
        52-WEEK RANGE
      </Text>
      <BulletChart
        h={wide ? 70 : 64}
        min={stats.low52}
        max={stats.high52}
        value={asset.price}
        target={owned && owned.avgCost >= stats.low52 && owned.avgCost <= stats.high52 ? owned.avgCost : undefined}
        ranges={[{ value: stats.high52, color: C.pale, label: '52-week range' }]}
        color={C.green}
        targetColor={C.ink}
        barThickness={0.4}
        withAxis
        ticks={4}
        valueFormatter={(value) => money(value, value >= 1000 ? 0 : 2)}
        accessibilityLabel={`52-week range ${money(stats.low52)} to ${money(stats.high52)}, now ${money(asset.price)}`}
      />
      <Text c={C.muted} size={12} mt={4}>
        Bar shows today's price
        {owned && owned.avgCost >= stats.low52 && owned.avgCost <= stats.high52 ? '; tick marks your average cost' : ''}
        .
      </Text>
      {crypto && <SupplySection asset={asset} />}

      {!crypto && <RatingsSection asset={asset} />}
      {!crypto && <EarningsSection asset={asset} wide={wide} />}

      <SectionTitle>News</SectionTitle>
      {news(asset).map((item) => (
        <Block key={item.id} gap={4} py={13} borderBottomWidth={1} borderBottomColor={C.line}>
          <Text c={C.muted} fw="semibold" size={12}>
            {item.source} · {item.age}
          </Text>
          <Text c={C.ink} fw="semibold" size={15} lh={21}>
            {item.title}
          </Text>
          <Text c={trend(item.move)} size={12}>
            {asset.ticker} {pct(item.move)}
          </Text>
        </Block>
      ))}

      <SectionTitle>People also own</SectionTitle>
      <ScrollArea horizontal showsHorizontalScrollIndicator={false} contentProps={{ direction: 'row', gap: 10, pb: 4 }}>
        {peopleAlsoOwn(asset).map((other) => (
          <AssetCard key={other.ticker} asset={other} onPress={() => onOpen(other.ticker)} />
        ))}
      </ScrollArea>

      <SectionTitle>Related lists</SectionTitle>
      <Block gap={8} direction="row" wrap>
        {asset.lists.map((list) => (
          <Badge key={list} color={C.darkGreen} variant="light" size="lg" onPress={() => onOpenList(list)}>
            {list}
          </Badge>
        ))}
      </Block>
      <Text c={C.muted} size={11} mt={30}>
        Sample data for a UI demo. Prices, statistics, ratings, and headlines are generated locally and are not real
        market information.
      </Text>
    </Block>
  );

  return (
    <Block gap={0} flex={1}>
      {header}
      <Block gap={0} flex={1} direction="row">
        <ScrollArea key={asset.ticker} flex={1} contentProps={{ align: 'center', px: 20, pb: 40 }}>
          {content}
        </ScrollArea>
        {wide && (
          <Block gap={0} w={300} p={18} borderLeftWidth={1} borderLeftColor={C.line}>
            <TradePanel key={asset.ticker} asset={asset} position={position} cash={cash} onSubmit={onTrade} />
          </Block>
        )}
      </Block>
      {!wide && (
        <Block
          gap={12}
          px={18}
          py={12}
          direction="row"
          align="center"
          borderTopWidth={1}
          borderTopColor={C.line}
          bg={C.white}
        >
          <Block gap={0} flex={1}>
            <Text c={C.muted} size={11}>
              {owned ? 'Your position' : 'Buying power'}
            </Text>
            <Text c={C.ink} fw="bold" size={15}>
              {owned ? money(owned.qty * asset.price) : money(cash)}
            </Text>
          </Block>
          {!!owned && <Button title="Sell" variant="outline" color={C.red} onPress={() => setTicket('Sell')} />}
          <Button title="Buy" color={C.green} onPress={() => setTicket('Buy')} />
        </Block>
      )}
      {!wide && !!ticket && (
        <Dialog
          opened
          variant="bottomsheet"
          accessibilityLabel={`${ticket} ${asset.ticker}`}
          onClose={() => setTicket(null)}
        >
          <Block gap={0} p={20}>
            <TradePanel
              asset={asset}
              position={position}
              cash={cash}
              initialSide={ticket}
              onSubmit={(side, qty) => {
                onTrade(side, qty);
                setTicket(null);
              }}
              onCancel={() => setTicket(null)}
            />
          </Block>
        </Dialog>
      )}
    </Block>
  );
}

function stockStats(asset: Asset, stats: ReturnType<typeof keyStats>): Stat[] {
  return [
    { label: 'Market cap', value: compact(stats.marketCap) },
    { label: 'P/E ratio', value: asset.pe ? asset.pe.toFixed(2) : '—' },
    { label: 'Dividend yield', value: asset.dividendYield ? `${asset.dividendYield.toFixed(2)}%` : '—' },
    { label: 'Average volume', value: compact(stats.avgVolume) },
    { label: 'Volume', value: compact(stats.volume) },
    { label: 'Open', value: money(stats.open) },
    { label: "Today's high", value: money(stats.high) },
    { label: "Today's low", value: money(stats.low) },
    { label: '52-week high', value: money(stats.high52) },
    { label: '52-week low', value: money(stats.low52) },
    { label: 'Previous close', value: money(stats.prevClose) },
    { label: 'Shares outstanding', value: compact((asset.sharesOut ?? 0) * 1e9) },
  ];
}

function cryptoStats(asset: Asset, stats: ReturnType<typeof keyStats>): Stat[] {
  return [
    { label: 'Market cap', value: compact(stats.marketCap) },
    { label: 'Volume (24h)', value: compact(stats.volume) },
    { label: 'Avg volume (30d)', value: compact(stats.avgVolume) },
    { label: 'Circulating supply', value: `${compact(asset.circulating ?? 0)} ${asset.ticker}` },
    { label: 'Max supply', value: asset.maxSupply ? `${compact(asset.maxSupply)} ${asset.ticker}` : 'No cap' },
    { label: 'Fully diluted value', value: asset.maxSupply ? compact(asset.maxSupply * asset.price) : '—' },
    { label: '24h high', value: money(stats.high) },
    { label: '24h low', value: money(stats.low) },
    { label: '24h open', value: money(stats.open) },
    { label: '52-week high', value: money(stats.high52) },
    { label: '52-week low', value: money(stats.low52) },
    { label: 'Trading', value: '24/7' },
  ];
}

function PositionSection({
  asset,
  position,
  prevClose,
  portfolioValue,
}: {
  asset: Asset;
  position: Position;
  prevClose: number;
  portfolioValue: number;
}) {
  const value = position.qty * asset.price;
  const cost = position.qty * position.avgCost;
  const today = position.qty * (asset.price - prevClose);
  const total = value - cost;
  const rows = [
    {
      label: "Today's return",
      value: `${signed(today)} (${pct((asset.price / prevClose - 1) * 100)})`,
      color: trend(today),
    },
    { label: 'Total return', value: `${signed(total)} (${pct((total / cost) * 100)})`, color: trend(total) },
  ];
  return (
    <>
      <SectionTitle>Your position</SectionTitle>
      <Block gap={0} bg={C.panel} radius={16} p={16}>
        <Block gap={0} direction="row">
          <Block gap={2} flex={1}>
            <Text c={C.muted} size={12}>
              {asset.kind === 'crypto' ? 'Quantity' : 'Shares'}
            </Text>
            <Text c={C.ink} fw="bold" size={20}>
              {quantity(position.qty)}
            </Text>
          </Block>
          <Block gap={2} flex={1}>
            <Text c={C.muted} size={12}>
              Market value
            </Text>
            <Text c={C.ink} fw="bold" size={20}>
              {money(value)}
            </Text>
          </Block>
        </Block>
        <Block gap={0} direction="row" mt={14}>
          <Block gap={2} flex={1}>
            <Text c={C.muted} size={12}>
              Average cost
            </Text>
            <Text c={C.ink} fw="semibold" size={15}>
              {price(position.avgCost)}
            </Text>
          </Block>
          <Block gap={2} flex={1}>
            <Text c={C.muted} size={12}>
              Portfolio diversity
            </Text>
            <Text c={C.ink} fw="semibold" size={15}>
              {((value / portfolioValue) * 100).toFixed(2)}%
            </Text>
          </Block>
        </Block>
        {rows.map((row) => (
          <Block
            key={row.label}
            gap={0}
            direction="row"
            justify="space-between"
            mt={14}
            pt={12}
            borderTopWidth={1}
            borderTopColor={C.line}
          >
            <Text c={C.muted} size={13}>
              {row.label}
            </Text>
            <Text c={row.color} fw="semibold" size={13}>
              {row.value}
            </Text>
          </Block>
        ))}
      </Block>
    </>
  );
}

function SupplySection({ asset }: { asset: Asset }) {
  const circulating = asset.circulating ?? 0;
  return (
    <>
      <SectionTitle>Supply</SectionTitle>
      {asset.maxSupply ? (
        <Block gap={8}>
          <Progress value={(circulating / asset.maxSupply) * 100} color={asset.color} size={10} radius="xl" />
          <Text c={C.muted} size={13}>
            {((circulating / asset.maxSupply) * 100).toFixed(1)}% of the {compact(asset.maxSupply)} {asset.ticker} cap
            is in circulation. {compact(asset.maxSupply - circulating)} {asset.ticker} remain to be issued.
          </Text>
        </Block>
      ) : (
        <Text c={C.muted} size={13}>
          {asset.name} has no fixed maximum supply. {compact(circulating)} {asset.ticker} are in circulation, with new
          issuance paid to validators.
        </Text>
      )}
    </>
  );
}

function RatingsSection({ asset }: { asset: Asset }) {
  const ratings = analystRatings(asset);
  const total = ratings.buy + ratings.hold + ratings.sell;
  const share = (count: number) => Math.round((count / total) * 100);
  return (
    <>
      <SectionTitle>Analyst ratings</SectionTitle>
      <Block gap={16} direction="row" align="center" wrap>
        <Block gap={0} w={170} h={170}>
          <RadialBarChart
            w={170}
            h={170}
            data={[{ value: share(ratings.buy), max: 100, label: 'Buy', color: C.green, trackColor: C.pale }]}
            barThickness={12}
            showValueLabels={false}
            centerLabel={`${share(ratings.buy)}%`}
            centerSubLabel="Buy"
            accessibilityLabel={`${share(ratings.buy)} percent of ${total} analysts rate ${asset.ticker} a buy`}
          />
        </Block>
        <Block gap={10} flex={1} miw={200}>
          {[
            { label: 'Buy', count: ratings.buy, color: C.green },
            { label: 'Hold', count: ratings.hold, color: '#9AA6A3' },
            { label: 'Sell', count: ratings.sell, color: C.red },
          ].map((row) => (
            <Block key={row.label} gap={10} direction="row" align="center">
              <Text c={C.ink} fw="semibold" size={13} w={36}>
                {row.label}
              </Text>
              <Block gap={0} flex={1}>
                <Progress value={share(row.count)} color={row.color} size={10} radius="xl" />
              </Block>
              <Text c={C.ink} fw="semibold" size={13} ta="right" w={40}>
                {share(row.count)}%
              </Text>
            </Block>
          ))}
          <Text c={C.muted} size={12}>
            Based on {total} sample analyst ratings
          </Text>
        </Block>
      </Block>
      <Text c={C.muted} fw="semibold" size={12} mt={20} mb={4}>
        12-MONTH PRICE TARGETS
      </Text>
      <BulletChart
        h={64}
        min={Math.floor(Math.min(ratings.targetLow, asset.price) * 0.97)}
        max={Math.ceil(ratings.targetHigh * 1.02)}
        value={asset.price}
        target={ratings.targetAvg}
        ranges={[
          { value: ratings.targetLow, color: '#F2F5F4', label: 'Below low target' },
          { value: ratings.targetHigh, color: C.pale, label: 'Analyst target range' },
          { value: Math.ceil(ratings.targetHigh * 1.02), color: '#F2F5F4', label: 'Above high target' },
        ]}
        color={C.ink}
        targetColor={C.green}
        barThickness={0.4}
        withAxis
        ticks={4}
        valueFormatter={(value) => money(value, 0)}
        accessibilityLabel={`Price targets from ${money(ratings.targetLow)} to ${money(ratings.targetHigh)}, average ${money(ratings.targetAvg)}`}
      />
      <Text c={C.muted} size={12} mt={4}>
        Bar shows today's price ({money(asset.price, 0)}); green tick is the average target (
        {money(ratings.targetAvg, 0)}), shaded band spans low to high targets.
      </Text>
    </>
  );
}

function EarningsSection({ asset, wide }: { asset: Asset; wide: boolean }) {
  const { quarters, next } = earnings(asset);
  const beats = quarters.filter((quarter) => quarter.actual >= quarter.estimate).length;
  return (
    <>
      <SectionTitle>Earnings</SectionTitle>
      <GroupedBarChart
        h={210}
        series={[
          {
            id: 'estimate',
            name: 'Estimated EPS',
            color: '#B6C2BF',
            data: quarters.map((q) => ({ category: q.label, value: round(q.estimate) })),
          },
          {
            id: 'actual',
            name: 'Actual EPS',
            color: C.green,
            data: quarters.map((q) => ({ category: q.label, value: round(q.actual) })),
          },
        ]}
        legend={{ show: true, position: 'bottom' }}
        yAxis={{ show: true, labelFormatter: (value) => `$${value.toFixed(2)}`, labelColor: C.muted }}
        xAxis={{ show: true, labelColor: C.muted }}
        grid={{ show: true, color: C.line }}
        liveTooltip
        accessibilityLabel={`${asset.ticker} estimated versus actual earnings per share for the last four quarters`}
      />
      <Text c={C.muted} size={13} mt={6}>
        Beat estimates in {beats} of the last 4 quarters. {next.label} report expected {next.date} · est. EPS{' '}
        {money(next.estimate)}.
      </Text>

      <Text c={C.ink} fw="bold" size={17} mt={26} mb={6}>
        Revenue and net margin
      </Text>
      <ComboChart
        h={wide ? 220 : 200}
        layers={[
          {
            type: 'bar',
            id: 'revenue',
            name: 'Revenue',
            color: '#2F7DD3',
            data: quarters.map((q, x) => ({ x, y: q.revenue })),
          },
          {
            type: 'line',
            id: 'margin',
            name: 'Net margin',
            color: C.amber,
            targetAxis: 'right',
            showPoints: true,
            data: quarters.map((q, x) => ({ x, y: Math.round(q.margin * 10) / 10 })),
          },
        ]}
        xDomain={[-0.6, quarters.length - 0.4]}
        yDomain={[0, Math.max(...quarters.map((q) => q.revenue)) * 1.15]}
        yDomainRight={[
          Math.min(0, ...quarters.map((q) => q.margin)) * 1.3,
          Math.max(5, ...quarters.map((q) => q.margin)) * 1.5,
        ]}
        xAxis={{
          show: true,
          ticks: quarters.map((_, x) => x),
          labelFormatter: (x) => quarters[Math.round(x)]?.label ?? '',
          labelColor: C.muted,
        }}
        yAxis={{ show: true, labelFormatter: (value) => `$${compact(value)}`, labelColor: C.muted }}
        yAxisRight={{ show: true, labelFormatter: (value) => `${value.toFixed(0)}%`, labelColor: C.muted }}
        grid={{ show: true, color: C.line }}
        legend={{ show: true, position: 'bottom' }}
        multiTooltip
        accessibilityLabel={`${asset.ticker} quarterly revenue and net margin`}
      />
    </>
  );
}

const round = (value: number) => Math.round(value * 100) / 100;

screens/TabScreens.tsx

import { useState } from 'react';
import { BarChart, DonutChart, HeatmapChart, WaffleChart } from '@plocks/charts';
import { Badge, Block, Icon, Input, ScrollArea, SegmentedControl, Text } from '@plocks/ui';
import { AssetLogo } from '../components/AssetLogo';
import { AssetCard, AssetRow, ChangeText, SectionTitle } from '../components/common';
import { PortfolioChart } from '../components/PriceChart';
import {
  ASSETS,
  CRYPTO,
  DIVIDENDS,
  getHistory,
  INDEXES,
  LISTS,
  RANGES,
  SECTOR_PERIODS,
  SECTOR_RETURNS,
  SECTORS,
  STOCKS,
  type Asset,
  type Position,
  type Range,
} from '../data';
import { C, compact, money, pct, quantity, signed, SLICE_COLORS, trend } from '../theme';

export type Activity = { id: string; side: 'Buy' | 'Sell'; ticker: string; qty: number; total: number };

interface PortfolioProps {
  positions: Record<string, Position>;
  cash: number;
  onOpen: (ticker: string) => void;
}

const heldValue = (asset: Asset, positions: Record<string, Position>) =>
  (positions[asset.ticker]?.qty ?? 0) * asset.price;
const holdingDetail = (asset: Asset, position: Position) =>
  `${quantity(position.qty)} ${asset.kind === 'crypto' ? asset.ticker : position.qty === 1 ? 'share' : 'shares'}`;

export function HomeScreen({
  positions,
  cash,
  watchlist,
  onOpen,
  wide,
}: PortfolioProps & { watchlist: string[]; wide: boolean }) {
  const [range, setRange] = useState<Range>('1D');
  const held = ASSETS.filter((asset) => (positions[asset.ticker]?.qty ?? 0) > 0);
  const reference = getHistory(STOCKS[0], range).points;
  const labels = reference.map((point) => point.label);
  const values = reference.map(
    (_, i) =>
      cash + held.reduce((sum, asset) => sum + positions[asset.ticker].qty * getHistory(asset, range).points[i].y, 0),
  );
  const total = values[values.length - 1];
  const move = total - values[0];
  const slices = [
    ...held
      .map((asset) => ({ label: asset.ticker, value: heldValue(asset, positions) }))
      .sort((a, b) => b.value - a.value),
    { label: 'Cash', value: cash },
  ].map((slice, i) => ({
    ...slice,
    value: Math.round(slice.value * 100) / 100,
    color: SLICE_COLORS[Math.min(i, SLICE_COLORS.length - 1)],
  }));
  const stocksHeld = held.filter((asset) => asset.kind === 'stock');
  const cryptoHeld = held.filter((asset) => asset.kind === 'crypto');
  const stockValue = stocksHeld.reduce((sum, asset) => sum + heldValue(asset, positions), 0);
  const cryptoValue = cryptoHeld.reduce((sum, asset) => sum + heldValue(asset, positions), 0);
  const movers = [...STOCKS].sort((a, b) => Math.abs(b.change) - Math.abs(a.change)).slice(0, 6);

  return (
    <Block gap={0}>
      <Block gap={0} pt={26}>
        <Text c={C.muted} fw="semibold" size={13}>
          Investing
        </Text>
        <Text c={C.ink} fw="bold" size={38} mt={2}>
          {money(total)}
        </Text>
        <Text c={trend(move)} fw="semibold" size={13}>
          {signed(move)} ({pct((move / values[0]) * 100)}) {range === '1D' ? 'today' : `past ${range}`}
        </Text>
      </Block>
      <Block gap={0} my={18}>
        <PortfolioChart values={values} labels={labels} height={wide ? 240 : 190} />
      </Block>
      <SegmentedControl
        data={RANGES}
        value={range}
        onChange={(value) => setRange(value as Range)}
        color={trend(move)}
        variant="ghost"
        size="sm"
        fullWidth
        accessibilityLabel="Portfolio time range"
      />
      <Block gap={0} bg={C.panel} radius={15} p={17} mt={20} direction="row" justify="space-between" align="center">
        <Block gap={0}>
          <Text c={C.muted} size={12}>
            Buying power
          </Text>
          <Text c={C.ink} fw="bold" size={20}>
            {money(cash)}
          </Text>
        </Block>
        <Icon name="chevronRight" color={C.muted} size={20} />
      </Block>
      <Block gap={10} direction="row" mt={14}>
        {INDEXES.map((index) => (
          <Block key={index.name} gap={2} flex={1} p={12} radius={12} borderWidth={1} borderColor={C.line}>
            <Text c={C.muted} size={11} numberOfLines={1}>
              {index.name}
            </Text>
            <Text c={C.ink} fw="semibold" size={13} numberOfLines={1}>
              {index.value.toLocaleString('en-US', { maximumFractionDigits: 0 })}
            </Text>
            <ChangeText value={index.change} size={11} />
          </Block>
        ))}
      </Block>

      <SectionTitle>Stocks</SectionTitle>
      {stocksHeld.map((asset) => (
        <AssetRow
          key={asset.ticker}
          asset={asset}
          detail={holdingDetail(asset, positions[asset.ticker])}
          onPress={() => onOpen(asset.ticker)}
        />
      ))}
      {!stocksHeld.length && <Text c={C.muted}>No stocks yet.</Text>}

      <SectionTitle>Crypto</SectionTitle>
      {cryptoHeld.map((asset) => (
        <AssetRow
          key={asset.ticker}
          asset={asset}
          detail={holdingDetail(asset, positions[asset.ticker])}
          onPress={() => onOpen(asset.ticker)}
        />
      ))}
      {!cryptoHeld.length && <Text c={C.muted}>No crypto yet.</Text>}

      <SectionTitle>Allocation</SectionTitle>
      <Block gap={20} direction={wide ? 'row' : 'column'} align="center">
        <Block gap={0} w={220} h={220}>
          <DonutChart
            size={220}
            w={220}
            h={220}
            padding={{ top: 0, right: 0, bottom: 0, left: 0 }}
            data={slices}
            innerRadiusRatio={0.68}
            padAngle={1.2}
            centerLabel={(_, __, focused) => focused?.label ?? 'Total'}
            centerValueFormatter={(value) => `$${compact(value)}`}
            legend={{ show: false }}
            accessibilityLabel="Portfolio allocation by holding"
          />
        </Block>
        <Block gap={0} flex={wide ? 1 : undefined} w={wide ? undefined : '100%'}>
          {slices.map((slice) => (
            <Block
              key={slice.label}
              gap={10}
              direction="row"
              align="center"
              py={7}
              borderBottomWidth={1}
              borderBottomColor={C.line}
            >
              <Block gap={0} w={10} h={10} radius={5} bg={slice.color} />
              <Text c={C.ink} fw="semibold" size={13} flex={1}>
                {slice.label}
              </Text>
              <Text c={C.muted} size={13}>
                {money(slice.value)}
              </Text>
              <Text c={C.ink} fw="semibold" size={13} ta="right" w={52}>
                {((slice.value / total) * 100).toFixed(1)}%
              </Text>
            </Block>
          ))}
        </Block>
      </Block>
      <Text c={C.muted} fw="semibold" size={12} mt={22} mb={8}>
        ASSET MIX · EACH SQUARE IS 1% OF YOUR PORTFOLIO
      </Text>
      <WaffleChart
        h={wide ? 170 : 150}
        maw={wide ? 360 : undefined}
        rows={5}
        columns={20}
        gap={3}
        cellRadius={3}
        data={[
          { name: 'Stocks', value: stockValue, color: SLICE_COLORS[0] },
          { name: 'Crypto', value: cryptoValue, color: SLICE_COLORS[3] },
          { name: 'Cash', value: cash, color: SLICE_COLORS[8] },
        ]}
        legend={{ show: true, position: 'bottom' }}
        accessibilityLabel={`Asset mix: stocks ${Math.round((stockValue / total) * 100)}%, crypto ${Math.round((cryptoValue / total) * 100)}%, cash ${Math.round((cash / total) * 100)}%`}
      />

      <SectionTitle>Top movers</SectionTitle>
      <ScrollArea horizontal showsHorizontalScrollIndicator={false} contentProps={{ direction: 'row', gap: 10, pb: 4 }}>
        {movers.map((asset) => (
          <AssetCard key={asset.ticker} asset={asset} onPress={() => onOpen(asset.ticker)} />
        ))}
      </ScrollArea>

      <SectionTitle>Watchlist</SectionTitle>
      {watchlist.length ? (
        ASSETS.filter((asset) => watchlist.includes(asset.ticker)).map((asset) => (
          <AssetRow key={asset.ticker} asset={asset} onPress={() => onOpen(asset.ticker)} />
        ))
      ) : (
        <Text c={C.muted}>Open a stock or coin and tap the bookmark to add it here.</Text>
      )}
    </Block>
  );
}

export function SearchScreen({
  query,
  setQuery,
  onOpen,
  wide,
}: {
  query: string;
  setQuery: (value: string) => void;
  onOpen: (ticker: string) => void;
  wide: boolean;
}) {
  const term = query.trim().toLowerCase();
  const results = ASSETS.filter((asset) =>
    `${asset.ticker} ${asset.name} ${asset.sector} ${asset.lists.join(' ')}`.toLowerCase().includes(term),
  );
  return (
    <Block gap={0} pt={24}>
      <Text c={C.ink} fw="bold" size={26}>
        Search
      </Text>
      <Input
        variant="filled"
        value={query}
        onChangeText={setQuery}
        placeholder="Search stocks, crypto, and lists"
        radius={12}
        mt={18}
        mb={14}
        inputColor={C.ink}
        inputFontSize={15}
        clearable
      />
      <Block gap={8} direction="row" wrap mb={8}>
        {LISTS.map((list) => (
          <Badge
            key={list}
            color={C.darkGreen}
            variant={query === list ? 'filled' : 'light'}
            size="lg"
            onPress={() => setQuery(query === list ? '' : list)}
          >
            {list}
          </Badge>
        ))}
      </Block>
      {term ? (
        <>
          <Text c={C.muted} fw="bold" size={12} mt={14}>
            {results.length} RESULTS
          </Text>
          {results.map((asset) => (
            <AssetRow key={asset.ticker} asset={asset} onPress={() => onOpen(asset.ticker)} />
          ))}
        </>
      ) : (
        <>
          <SectionTitle>Sector performance</SectionTitle>
          <HeatmapChart
            h={wide ? 400 : 360}
            data={{ rows: SECTORS, cols: SECTOR_PERIODS, values: SECTOR_RETURNS }}
            gap={3}
            cellCornerRadius={4}
            colorScale={{ type: 'diverging', colors: [C.red, '#F3F5F4', C.green], midpoint: 0, domain: [-12, 12] }}
            showCellLabels
            valueFormatter={({ value }) => `${value > 0 ? '+' : ''}${value.toFixed(1)}`}
            xAxis={{ show: true, labelColor: C.muted }}
            yAxis={{ show: true, labelColor: C.ink }}
            grid={{ show: false }}
            legend={{ show: false }}
            tooltip={{ show: true }}
            accessibilityLabel="Sample sector returns by period, in percent"
          />
          <Text c={C.muted} size={12} mt={4}>
            Percent change by sector and period (sample data)
          </Text>
          <SectionTitle>Stocks</SectionTitle>
          {STOCKS.map((asset) => (
            <AssetRow key={asset.ticker} asset={asset} onPress={() => onOpen(asset.ticker)} />
          ))}
          <SectionTitle>Crypto</SectionTitle>
          {CRYPTO.map((asset) => (
            <AssetRow key={asset.ticker} asset={asset} onPress={() => onOpen(asset.ticker)} />
          ))}
        </>
      )}
    </Block>
  );
}

export function WatchlistScreen({ watchlist, onOpen }: { watchlist: string[]; onOpen: (ticker: string) => void }) {
  return (
    <Block gap={0} pt={24}>
      <Text c={C.ink} fw="bold" size={26}>
        Watchlist
      </Text>
      <Text c={C.muted} size={13} mt={5} mb={14}>
        Keep an eye on what interests you.
      </Text>
      {watchlist.length ? (
        ASSETS.filter((asset) => watchlist.includes(asset.ticker)).map((asset) => (
          <AssetRow key={asset.ticker} asset={asset} onPress={() => onOpen(asset.ticker)} />
        ))
      ) : (
        <Text c={C.muted}>Open a stock or coin and tap the bookmark to add it here.</Text>
      )}
    </Block>
  );
}

export function AccountScreen({ positions, cash, activity, onOpen }: PortfolioProps & { activity: Activity[] }) {
  const equity = ASSETS.reduce((sum, asset) => sum + heldValue(asset, positions), 0);
  const cost = ASSETS.reduce(
    (sum, asset) => sum + (positions[asset.ticker]?.qty ?? 0) * (positions[asset.ticker]?.avgCost ?? 0),
    0,
  );
  const dividendTotal = DIVIDENDS.reduce((sum, item) => sum + item.value, 0);
  return (
    <Block gap={0} pt={24}>
      <Text c={C.ink} fw="bold" size={26}>
        Account
      </Text>
      <Block bg={C.panel} radius={16} p={18} mt={20} gap={8}>
        <Text c={C.muted} size={12}>
          Demo account
        </Text>
        <Text c={C.ink} fw="bold" size={24}>
          {money(cash + equity)}
        </Text>
        <Text c={C.muted} size={13}>
          Invested {money(equity)} · Cash {money(cash)}
        </Text>
        <Text c={trend(equity - cost)} fw="semibold" size={13}>
          Total return {signed(equity - cost)} ({pct(cost ? ((equity - cost) / cost) * 100 : 0)})
        </Text>
      </Block>

      <SectionTitle>Dividend income</SectionTitle>
      <Text c={C.muted} size={13} mb={8}>
        {money(dividendTotal)} received over the past 12 months
      </Text>
      <BarChart
        h={190}
        data={DIVIDENDS}
        barColor={C.green}
        barBorderRadius={4}
        xAxis={{ show: true, labelColor: C.muted }}
        yAxis={{ show: true, labelFormatter: (value) => `$${value.toFixed(0)}`, labelColor: C.muted }}
        grid={{ show: true, color: C.line }}
        tooltip={{ show: true, formatter: (datum) => `${datum.category}: ${money(datum.value)}` }}
        accessibilityLabel="Monthly dividend income, sample data"
      />

      <SectionTitle>Recent activity</SectionTitle>
      {activity.length ? (
        activity.map((item) => {
          const asset = ASSETS.find((candidate) => candidate.ticker === item.ticker);
          return (
            <Block
              key={item.id}
              gap={12}
              direction="row"
              align="center"
              py={12}
              borderBottomWidth={1}
              borderBottomColor={C.line}
              onPress={asset ? () => onOpen(asset.ticker) : undefined}
            >
              {asset && <AssetLogo asset={asset} size={34} />}
              <Text c={C.ink} fw="semibold" flex={1}>
                {item.side} {quantity(item.qty)} {item.ticker}
              </Text>
              <Text c={C.muted}>{money(item.total)}</Text>
            </Block>
          );
        })
      ) : (
        <Text c={C.muted}>No trades yet. Open a stock or coin to try a simulated order.</Text>
      )}
      <Text c={C.muted} size={12} mt={30}>
        Educational UI example. Prices are fictional sample data ({compact(ASSETS.length)} assets) and no real orders
        are placed.
      </Text>
    </Block>
  );
}

theme.ts

export const C = {
  ink: '#101616',
  muted: '#6F7C79',
  green: '#00B67A',
  darkGreen: '#007C56',
  line: '#E6ECE9',
  pale: '#E9F8F1',
  panel: '#F7FAF8',
  white: '#FFF',
  red: '#D45B5B',
  amber: '#C98A12',
};

/** Allocation palette, fixed order so a slice keeps its color between renders. */
export const SLICE_COLORS = [
  '#00B67A',
  '#2F7DD3',
  '#8B5CF6',
  '#E08A1E',
  '#0EA5A4',
  '#D45B5B',
  '#64748B',
  '#C2A013',
  '#B6C2BF',
];

export const money = (value: number, digits = 2) =>
  (value < 0 ? '-$' : '$') +
  Math.abs(value).toLocaleString('en-US', { minimumFractionDigits: digits, maximumFractionDigits: digits });

/** Sub-dollar coins and tokens need more precision than whole-dollar stocks. */
export const price = (value: number) => money(value, value < 1 ? 4 : 2);

export const signed = (value: number) => (value >= 0 ? '+' : '-') + money(Math.abs(value));

export const pct = (value: number) => `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;

export const compact = (value: number) => {
  const abs = Math.abs(value);
  if (abs >= 1e12) return `${(value / 1e12).toFixed(2)}T`;
  if (abs >= 1e9) return `${(value / 1e9).toFixed(2)}B`;
  if (abs >= 1e6) return `${(value / 1e6).toFixed(2)}M`;
  if (abs >= 1e3) return `${(value / 1e3).toFixed(1)}K`;
  return value.toFixed(0);
};

export const quantity = (value: number) =>
  value.toLocaleString('en-US', { maximumFractionDigits: Number.isInteger(value) ? 0 : 6 });

export const trend = (value: number) => (value >= 0 ? C.darkGreen : C.red);