#!/usr/bin/env bash
# StockGram — terminal portfolio + ASCII price charts
# StockGram by Page Telegram Volunteer Services
#
# Usage:
#   ./stockgram.sh                 Interactive TUI
#   ./stockgram.sh --help          Keybindings and flags
#   ./stockgram.sh --chart SYM [RANGE] [STYLE]
#   ./stockgram.sh --quotes SYM[,SYM...]
#   ./stockgram.sh --check-deps     Report required tools
#   ./stockgram.sh --install-deps   Prompt to install missing tools
set -u

# Finder / double-click often starts /bin/bash 3.2 with no Homebrew PATH.
# StockGram needs Bash 4+ (${var^^}, declare -A) and python3 on PATH.
if [[ -x /opt/homebrew/bin/brew ]]; then
  eval "$(/opt/homebrew/bin/brew shellenv bash)"
elif [[ -x /usr/local/bin/brew ]]; then
  eval "$(/usr/local/bin/brew shellenv bash)"
fi
if ((BASH_VERSINFO[0] < 4)); then
  _sg_bash=""
  if [[ -x /opt/homebrew/bin/bash ]]; then
    _sg_bash=/opt/homebrew/bin/bash
  elif [[ -x /usr/local/bin/bash ]]; then
    _sg_bash=/usr/local/bin/bash
  fi
  if [[ -n "$_sg_bash" ]]; then
    exec "$_sg_bash" "$0" "$@"
  fi
  echo "StockGram needs Bash 4 or newer. Install with: brew install bash" >&2
  exit 1
fi
unset _sg_bash

# Finder GUI launch with no terminal: open Terminal.app in bash.
# Skip when already in Terminal/iTerm, or when stdin is a TTY, or when
# the parent is a shell (scripts, CI, this installer).
if [[ ! -t 0 && -z "${TERM_PROGRAM:-}" && -z "${STOCKGRAM_IN_TERMINAL:-}" ]]; then
  _sg_parent="$(ps -o comm= -p "${PPID:-0}" 2>/dev/null || true)"
  _sg_parent="${_sg_parent##*/}"
  case "$_sg_parent" in
    launchd|Finder|open|loginwindow|applet|StockGram)
      _sg_self="${BASH_SOURCE[0]}"
      if [[ "$_sg_self" != /* ]]; then
        _sg_self="$(cd "$(dirname "$_sg_self")" && pwd)/$(basename "$_sg_self")"
      fi
      _sg_term_bash="${BASH:-}"
      if [[ ! -x "$_sg_term_bash" ]]; then
        if [[ -x /opt/homebrew/bin/bash ]]; then
          _sg_term_bash=/opt/homebrew/bin/bash
        elif [[ -x /usr/local/bin/bash ]]; then
          _sg_term_bash=/usr/local/bin/bash
        else
          _sg_term_bash=/bin/bash
        fi
      fi
      osascript \
        -e 'tell application "Terminal" to activate' \
        -e "tell application \"Terminal\" to do script \"export STOCKGRAM_IN_TERMINAL=1; exec $(printf '%q' "$_sg_term_bash") $(printf '%q' "$_sg_self")\"" \
        >/dev/null
      unset _sg_self _sg_parent _sg_term_bash
      exit 0
      ;;
  esac
  unset _sg_parent
fi

# Avoid dirname so a missing coreutils still lets the installer prompt run.
_sg_src="${BASH_SOURCE[0]}"
if [[ "$_sg_src" == */* ]]; then
  SCRIPT_DIR="${_sg_src%/*}"
  [[ -z "$SCRIPT_DIR" ]] && SCRIPT_DIR="/"
else
  SCRIPT_DIR="."
fi
if [[ -d "$SCRIPT_DIR" ]]; then
  SCRIPT_DIR="$(cd "$SCRIPT_DIR" && pwd 2>/dev/null || printf '%s' "$SCRIPT_DIR")"
fi
unset _sg_src
APP_NAME="StockGram"
APP_CREDIT="StockGram by Page Telegram Volunteer Services"
UA="Mozilla/5.0 (compatible; StockGram/1.0; +https://finance.yahoo.com)"
YF="https://query1.finance.yahoo.com"
CONFIG_DIR="${STOCKGRAM_HOME:-${XDG_CONFIG_HOME:-$HOME/.config}/stockgram}"
WATCHLIST_FILE="$CONFIG_DIR/watchlist"
CACHE_DIR="${TMPDIR:-/tmp}/stockgram-$UID"

ensure_dirs() {
  mkdir -p "$CONFIG_DIR" "$CACHE_DIR"
}

# --- dependencies -----------------------------------------------------------
# Required host tools. Python uses only the standard library (no pip packages).
DEP_CMDS=(python3 curl mkdir)
DEP_TUI_CMDS=(tput stty)

have_cmd() { command -v "$1" >/dev/null 2>&1; }

pkg_for_cmd() {
  local cmd="$1" mgr="$2"
  case "$mgr:$cmd" in
    apt:python3|dnf:python3|yum:python3|zypper:python3|apk:python3|pacman:python3) echo python3 ;;
    brew:python3) echo python3 ;;
    apt:curl|dnf:curl|yum:curl|zypper:curl|apk:curl|pacman:curl|brew:curl) echo curl ;;
    apt:tput) echo ncurses-bin ;;
    dnf:tput|yum:tput|zypper:tput|apk:tput|pacman:tput|brew:tput) echo ncurses ;;
    apt:stty|dnf:stty|yum:stty|zypper:stty|apk:stty|pacman:stty|brew:stty) echo coreutils ;;
    apt:mkdir|dnf:mkdir|yum:mkdir|zypper:mkdir|apk:mkdir|pacman:mkdir|brew:mkdir) echo coreutils ;;
    *) echo "$cmd" ;;
  esac
}

detect_pkg_mgr() {
  if have_cmd apt-get && have_cmd dpkg; then
    echo apt
  elif have_cmd dnf; then
    echo dnf
  elif have_cmd yum; then
    echo yum
  elif have_cmd zypper; then
    echo zypper
  elif have_cmd pacman; then
    echo pacman
  elif have_cmd apk; then
    echo apk
  elif have_cmd brew; then
    echo brew
  else
    echo ""
  fi
}

install_cmd_for() {
  local mgr="$1"
  shift
  local pkgs=("$@")
  case "$mgr" in
    apt)    printf 'apt-get update && apt-get install -y %s' "${pkgs[*]}" ;;
    dnf)    printf 'dnf install -y %s' "${pkgs[*]}" ;;
    yum)    printf 'yum install -y %s' "${pkgs[*]}" ;;
    zypper) printf 'zypper --non-interactive install %s' "${pkgs[*]}" ;;
    pacman) printf 'pacman -Sy --noconfirm %s' "${pkgs[*]}" ;;
    apk)    printf 'apk add --no-cache %s' "${pkgs[*]}" ;;
    brew)   printf 'brew install %s' "${pkgs[*]}" ;;
    *)      printf 'true' ;;
  esac
}

collect_missing_cmds() {
  local c
  MISSING_CMDS=()
  for c in "${DEP_CMDS[@]}" "${DEP_TUI_CMDS[@]}"; do
    have_cmd "$c" || MISSING_CMDS+=("$c")
  done
}

python_modules_ok() {
  have_cmd python3 || return 1
  python3 - <<'PY' 2>/dev/null
import importlib
for name in (
    "json", "html", "re", "sys", "time", "textwrap",
    "urllib.request", "urllib.error", "urllib.parse",
    "xml.etree.ElementTree", "datetime",
):
    importlib.import_module(name)
PY
}

prompt_yes_no() {
  local msg="$1" reply=""
  if { printf '' >/dev/tty; } 2>/dev/null; then
    printf '%s' "$msg" >/dev/tty
    IFS= read -r reply </dev/tty || reply=""
  elif [[ -t 0 ]]; then
    printf '%s' "$msg" >&2
    IFS= read -r reply || reply=""
  else
    return 1
  fi
  reply="${reply,,}"
  [[ "$reply" == y || "$reply" == yes ]]
}

run_pkg_install() {
  local shell_cmd="$1"
  echo "$APP_CREDIT"
  echo "Installing: $shell_cmd"
  if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
    bash -lc "$shell_cmd"
    return
  fi
  if [[ "$shell_cmd" == brew\ * ]]; then
    bash -lc "$shell_cmd"
    return
  fi
  if have_cmd sudo; then
    echo "Administrator privileges are required."
    sudo bash -lc "$shell_cmd"
    return
  fi
  echo "Cannot install automatically (not root, no sudo)." >&2
  echo "Run as root:" >&2
  echo "  $shell_cmd" >&2
  return 1
}

require_dependencies() {
  local report_only="${1:-0}"
  collect_missing_cmds
  local py_ok=1
  if have_cmd python3; then
    python_modules_ok || py_ok=0
  fi

  if ((${#MISSING_CMDS[@]} == 0)) && ((py_ok)); then
    if ((report_only)); then
      echo "$APP_CREDIT"
      echo "All dependencies are installed:"
      local c ver
      for c in "${DEP_CMDS[@]}" "${DEP_TUI_CMDS[@]}"; do
        ver="$("$c" --version 2>/dev/null | head -1 || true)"
        [[ -z "$ver" ]] && ver="$("$c" -V 2>/dev/null | head -1 || true)"
        [[ -z "$ver" ]] && ver="$(command -v "$c")"
        echo "  $c  ($ver)"
      done
      echo "  python3 standard library  ok"
    fi
    return 0
  fi

  echo "$APP_CREDIT" >&2
  echo "Missing required tools:" >&2
  local c
  for c in "${MISSING_CMDS[@]+"${MISSING_CMDS[@]}"}"; do
    echo "  - $c" >&2
  done
  if ((!py_ok)); then
    echo "  - python3 standard library modules (json, urllib, xml)" >&2
    echo "    Reinstall python3 if this persists." >&2
  fi

  local mgr
  mgr="$(detect_pkg_mgr)"
  local pkgs=() seen=" "
  for c in "${MISSING_CMDS[@]+"${MISSING_CMDS[@]}"}"; do
    local p
    p="$(pkg_for_cmd "$c" "${mgr:-unknown}")"
    if [[ "$seen" != *" $p "* ]]; then
      pkgs+=("$p")
      seen+=" $p "
    fi
  done
  if ((!py_ok)); then
    local pp
    pp="$(pkg_for_cmd python3 "${mgr:-unknown}")"
    if [[ "$seen" != *" $pp "* ]]; then
      pkgs+=("$pp")
    fi
  fi

  local howto=""
  if [[ -n "$mgr" && ${#pkgs[@]} -gt 0 ]]; then
    howto="$(install_cmd_for "$mgr" "${pkgs[@]}")"
    echo >&2
    echo "Install with:" >&2
    echo "  $howto" >&2
  else
    echo >&2
    echo "Install python3, curl, ncurses (tput), and coreutils (stty) with your package manager." >&2
  fi

  ((report_only)) && return 1

  if [[ -n "${STOCKGRAM_ASSUME_YES:-}" ]]; then
    [[ -n "$howto" ]] || return 1
    run_pkg_install "$howto" || return 1
  elif [[ -n "$howto" ]] && prompt_yes_no "Install missing packages now? [y/N] "; then
    run_pkg_install "$howto" || return 1
  else
    echo "Install the packages above, then run StockGram again." >&2
    return 1
  fi

  collect_missing_cmds
  py_ok=0
  have_cmd python3 && python_modules_ok && py_ok=1
  if ((${#MISSING_CMDS[@]})); then
    echo "Still missing: ${MISSING_CMDS[*]}" >&2
    return 1
  fi
  if ((!py_ok)); then
    echo "python3 is present but required modules failed to import." >&2
    return 1
  fi
  echo "Dependencies OK."
}

# --- defaults ---------------------------------------------------------------
REFRESH_SECS=(2 5 10 15 30 60 300 900 1800 3600)
REFRESH_LABELS=("2s" "5s" "10s" "15s" "30s" "1m" "5m" "15m" "30m" "1h")
REFRESH_IDX=2

RANGES=("1d" "5d" "1mo" "3mo" "6mo" "ytd" "1y" "2y" "5y" "10y")
RANGE_LABELS=("1D" "5D" "1M" "3M" "6M" "YTD" "1Y" "2Y" "5Y" "10Y")
RANGE_IDX=0

STYLES=("line" "area" "ohlc")
STYLE_IDX=0

DEFAULT_TICKERS=(AAPL MSFT GOOG AMZN NVDA TSLA META SPY QQQ)

ZOOM="1"
PAN="1"          # 1 = follow latest (live edge)
SELECTED=0
VIEW="list"      # list | chart | help
STATUS=""
CHART_SYMBOL=""
TICKERS=()
SAVED_STTY=""
ALT_SCREEN=0
COLS=80
ROWS=24
LAST_ROWS=0
LAST_COLS=0
NEED_REDRAW=0
DENSITY="normal"
BANNER_H=3
FOOTER_H=2
NEWS_H=7
LIST_H=10
LIST_TOP=4
NEWS_TOP=14
INNER=76
NAME_W=14
SPARK_W=16
SYM_W=6
PRICE_W=10
LIVE_W=16
PCT_W=8
VOL_W=7
RANGE_W=15
SHOW_SPARK=1
SHOW_VOL=0
SHOW_RANGE=0
SHOW_52W=0
SHOW_SHARES=1
SHOW_VALUE=0
SHARES_W=6
VALUE_W=10
NEWS_SYM=""
NEWS_ITEMS=()
NEWS_IDX=0
NEWS_SRC=""
NEWS_AT=0
NEWS_ERR=""
NEWS_TTL=60          # auto-refresh selected ticker RSS every 1 minute
LAST_QUOTE_AT=0
PAUSED=0
FORCE_CLEAR=1
LAST_VIEW=""
CHART_CACHE=""
CHART_CACHE_KEY=""
ARTICLE_TITLE=""
ARTICLE_URL=""
ARTICLE_VIA=""
ARTICLE_LINES=()
ARTICLE_SCROLL=0
ASSET_HELD=0
ASSET_VALUE_FMT="--"
ASSET_DAY_FMT="--"
ASSET_PCT_FMT="--"
ASSET_DIR="FL"

# --- colors -----------------------------------------------------------------
if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then
  C_RESET=$'\033[0m'
  C_BOLD=$'\033[1m'
  C_DIM=$'\033[2m'
  C_RED=$'\033[31m'
  C_GREEN=$'\033[32m'
  C_YELLOW=$'\033[33m'
  C_BLUE=$'\033[34m'
  C_MAGENTA=$'\033[35m'
  C_CYAN=$'\033[36m'
  C_WHITE=$'\033[37m'
  C_BG=$'\033[44m'
  C_REV=$'\033[7m'
  C_UP=$'\033[1;32m'
  C_DN=$'\033[1;31m'
else
  C_RESET="" C_BOLD="" C_DIM="" C_RED="" C_GREEN="" C_YELLOW=""
  C_BLUE="" C_MAGENTA="" C_CYAN="" C_WHITE="" C_BG="" C_REV=""
  C_UP="" C_DN=""
fi

# --- python helper (Yahoo fetch + ASCII plot) -------------------------------
read -r -d '' STOCKGRAM_PY <<'PY' || true
import html, json, os, re, sys, time, urllib.error, urllib.parse, urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone

UA = "Mozilla/5.0 (compatible; StockGram/1.0; +https://finance.yahoo.com)"
YF = "https://query1.finance.yahoo.com"

def http_get(url, timeout=15, accept="application/json"):
    req = urllib.request.Request(url, headers={
        "User-Agent": UA,
        "Accept": accept,
        "Accept-Language": "en-US,en;q=0.8",
    })
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.read()
    except urllib.error.HTTPError as e:
        if e.code in (404, 400):
            raise RuntimeError("No data found, symbol may be delisted") from e
        raise RuntimeError(f"Quote service HTTP {e.code}") from e
    except urllib.error.URLError as e:
        raise RuntimeError(f"Network error: {e.reason}") from e

def fmt_price(p):
    if p is None:
        return "--"
    try:
        p = float(p)
    except (TypeError, ValueError):
        return "--"
    ap = abs(p)
    if ap >= 10000:
        return f"{p:,.2f}"
    if ap >= 1:
        return f"{p:.2f}"
    if ap >= 0.01:
        return f"{p:.4f}"
    return f"{p:.6f}"

def fmt_vol(v):
    try:
        v = float(v or 0)
    except (TypeError, ValueError):
        return "--"
    if v >= 1e12:
        return f"{v/1e12:.2f}T"
    if v >= 1e9:
        return f"{v/1e9:.2f}B"
    if v >= 1e6:
        return f"{v/1e6:.2f}M"
    if v >= 1e3:
        return f"{v/1e3:.1f}K"
    return f"{int(v)}"

def fmt_chg(ch, pct):
    if ch is None:
        return "--", "--"
    sign = "+" if ch > 0 else ""
    pct_s = "--" if pct is None else f"{sign}{pct:.2f}%"
    return f"{sign}{fmt_price(ch)}", pct_s

def sparkline(vals, width=40):
    chars = " .:=*#"
    clean = [float(v) for v in vals if v is not None]
    if not clean:
        return "-" * width
    if len(clean) > width:
        step = len(clean) / width
        buck = []
        for i in range(width):
            sl = clean[int(i * step):int((i + 1) * step) or None]
            buck.append(sl[-1] if sl else clean[-1])
        clean = buck
    elif len(clean) < width:
        # stretch
        stretched = []
        for i in range(width):
            idx = int(round(i * (len(clean) - 1) / max(width - 1, 1)))
            stretched.append(clean[idx])
        clean = stretched
    lo, hi = min(clean), max(clean)
    span = hi - lo if hi != lo else 1.0
    out = []
    for v in clean:
        n = int(round((v - lo) / span * (len(chars) - 1)))
        out.append(chars[max(0, min(len(chars) - 1, n))])
    return "".join(out)

def row_from_meta(sym, meta, closes=None):
    price = meta.get("regularMarketPrice")
    prev = meta.get("previousClose") or meta.get("chartPreviousClose")
    ch = None if price is None or prev is None else float(price) - float(prev)
    pct = None if ch is None or not prev else (ch / float(prev)) * 100.0
    return {
        "symbol": sym,
        "name": meta.get("shortName") or meta.get("longName") or sym,
        "price": price,
        "prev": prev,
        "change": ch,
        "pct": pct,
        "day_high": meta.get("regularMarketDayHigh"),
        "day_low": meta.get("regularMarketDayLow"),
        "h52": meta.get("fiftyTwoWeekHigh"),
        "l52": meta.get("fiftyTwoWeekLow"),
        "vol": meta.get("regularMarketVolume"),
        "ccy": meta.get("currency") or "",
        "spark": sparkline(closes or [], 40),
        "ok": price is not None,
    }

def fetch_spark_chunk(symbols):
    q = urllib.parse.quote(",".join(symbols), safe=",-")
    url = f"{YF}/v7/finance/spark?symbols={q}&range=1d&interval=5m"
    data = json.loads(http_get(url))
    rows = {}
    for item in (data.get("spark") or {}).get("result") or []:
        sym = (item.get("symbol") or "").upper()
        resp = (item.get("response") or [None])[0] or {}
        meta = resp.get("meta") or {}
        quote = ((resp.get("indicators") or {}).get("quote") or [{}])[0]
        closes = quote.get("close") or []
        row = row_from_meta(sym, meta, closes)
        if row.get("ok"):
            rows[sym] = row
    return rows

def fetch_one_via_chart(sym):
    meta, pts = fetch_chart(sym, "5d", "1d")
    closes = [p[4] for p in pts]
    return row_from_meta(sym.upper(), meta, closes)

def fetch_spark(symbols):
    rows = {}
    chunk_size = 8
    for i in range(0, len(symbols), chunk_size):
        chunk = symbols[i:i + chunk_size]
        try:
            rows.update(fetch_spark_chunk(chunk))
        except Exception:
            for s in chunk:
                try:
                    row = fetch_one_via_chart(s)
                    if row.get("ok"):
                        rows[s.upper()] = row
                except Exception:
                    pass
    missing = [s for s in symbols if s.upper() not in rows]
    for s in missing:
        try:
            row = fetch_one_via_chart(s)
            if row.get("ok"):
                rows[s.upper()] = row
        except Exception:
            pass
    return rows

def cmd_quotes(argv):
    symbols = [s.strip().upper() for s in argv[0].split(",") if s.strip()]
    if not symbols:
        return
    try:
        rows = fetch_spark(symbols)
    except Exception as e:
        print(f"ERR|{e}", file=sys.stderr)
        for s in symbols:
            print(f"ERR|{s}|fetch failed")
        return
    for s in symbols:
        r = rows.get(s) or rows.get(s.upper())
        if not r or not r.get("ok"):
            print(f"ERR|{s}|not found")
            continue
        ch_s, pct_s = fmt_chg(r["change"], r["pct"])
        direction = "UP" if (r["change"] or 0) > 0 else ("DN" if (r["change"] or 0) < 0 else "FL")
        name = (r["name"] or s).replace("|", "/")
        print("|".join([
            "OK", s, name, fmt_price(r["price"]), ch_s, pct_s, direction,
            fmt_price(r["day_high"]), fmt_price(r["day_low"]),
            fmt_price(r["h52"]), fmt_price(r["l52"]),
            fmt_vol(r["vol"]), r["ccy"], r["spark"],
            f'{r["price"] if r["price"] is not None else ""}',
            f'{r["change"] if r["change"] is not None else 0}',
            f'{r["pct"] if r["pct"] is not None else 0}',
        ]))

def fetch_chart(symbol, range_, interval):
    enc = urllib.parse.quote(symbol, safe="-")
    url = (
        f"{YF}/v8/finance/chart/{enc}"
        f"?interval={urllib.parse.quote(interval)}"
        f"&range={urllib.parse.quote(range_)}"
        f"&includePrePost=false"
    )
    data = json.loads(http_get(url))
    err = (data.get("chart") or {}).get("error")
    if err:
        raise RuntimeError(err.get("description") or err.get("code") or "chart error")
    result = (data.get("chart") or {}).get("result")
    if not result:
        raise RuntimeError("No data found, symbol may be delisted")
    r = result[0]
    meta = r.get("meta") or {}
    ts = r.get("timestamp") or []
    q = ((r.get("indicators") or {}).get("quote") or [{}])[0]
    opens, highs, lows, closes = q.get("open") or [], q.get("high") or [], q.get("low") or [], q.get("close") or []
    vols = q.get("volume") or []
    pts = []
    for i, t in enumerate(ts):
        c = closes[i] if i < len(closes) else None
        if c is None:
            continue
        o = opens[i] if i < len(opens) and opens[i] is not None else c
        h = highs[i] if i < len(highs) and highs[i] is not None else c
        l = lows[i] if i < len(lows) and lows[i] is not None else c
        v = vols[i] if i < len(vols) and vols[i] is not None else 0
        pts.append((int(t), float(o), float(h), float(l), float(c), float(v)))
    if not pts:
        raise RuntimeError("No plottable prices")
    return meta, pts

def y_of(price, lo, hi, h):
    if hi <= lo:
        return h // 2
    return int(round((hi - price) / (hi - lo) * (h - 1)))

def window_points(pts, zoom, pan):
    n = len(pts)
    try:
        zoom = max(1.0, float(zoom))
    except (TypeError, ValueError):
        zoom = 1.0
    try:
        pan = min(1.0, max(0.0, float(pan)))
    except (TypeError, ValueError):
        pan = 1.0
    vis = max(8, int(round(n / zoom)))
    vis = min(n, vis)
    max_off = n - vis
    off = int(round(pan * max_off)) if max_off else 0
    return pts[off:off + vis], off, vis, n, zoom, pan

def bucket_ohlc(pts, width):
    if len(pts) <= width:
        # map each column to a point (may repeat)
        out = []
        for x in range(width):
            i = int(round(x * (len(pts) - 1) / max(width - 1, 1)))
            out.append(pts[i])
        return out
    out = []
    step = len(pts) / width
    for x in range(width):
        a = int(x * step)
        b = max(a + 1, int((x + 1) * step))
        sl = pts[a:b]
        o, h, l, c = sl[0][1], max(p[2] for p in sl), min(p[3] for p in sl), sl[-1][4]
        v = sum(p[5] for p in sl)
        out.append((sl[-1][0], o, h, l, c, v))
    return out

def draw_line(grid, ys, area=False):
    h = len(grid)
    w = len(grid[0]) if h else 0
    for x in range(w):
        y = ys[x]
        if area:
            for yy in range(y, h):
                if 0 <= yy < h:
                    grid[yy][x] = "."
        if x > 0:
            y0 = ys[x - 1]
            if y != y0:
                step = 1 if y > y0 else -1
                for yy in range(y0 + step, y, step):
                    if 0 <= yy < h and grid[yy][x] in (" ", "."):
                        grid[yy][x] = "|"
                ch = "\\" if y > y0 else "/"
            else:
                ch = "-"
            if 0 <= y < h:
                grid[y][x] = ch
        if 0 <= y < h:
            if x == w - 1:
                grid[y][x] = "@"
            elif grid[y][x] in (" ", ".", "|"):
                grid[y][x] = "*"

def draw_ohlc(grid, candles, lo, hi):
    h = len(grid)
    w = len(grid[0]) if h else 0
    for x in range(min(w, len(candles))):
        _t, o, hi_p, lo_p, c, _v = candles[x]
        y_h = y_of(hi_p, lo, hi, h)
        y_l = y_of(lo_p, lo, hi, h)
        y_o = y_of(o, lo, hi, h)
        y_c = y_of(c, lo, hi, h)
        y_top, y_bot = min(y_h, y_l), max(y_h, y_l)
        for y in range(y_top, y_bot + 1):
            if 0 <= y < h:
                grid[y][x] = "|"
        b0, b1 = min(y_o, y_c), max(y_o, y_c)
        body = "#" if c < o else "+"
        if b0 == b1:
            body = "=" if c >= o else "-"
        for y in range(b0, b1 + 1):
            if 0 <= y < h:
                grid[y][x] = body
        if 0 <= y_c < h and x == w - 1:
            grid[y_c][x] = "@"

def fmt_axis_ts(ts, range_):
    dt = datetime.fromtimestamp(ts, tz=timezone.utc)
    if range_ in ("1d", "5d"):
        return dt.strftime("%H:%M")
    if range_ in ("1mo", "3mo"):
        return dt.strftime("%b %d")
    return dt.strftime("%Y-%m-%d")

def session_flag(meta):
    now = time.time()
    ctp = meta.get("currentTradingPeriod") or {}
    reg = ctp.get("regular") or {}
    start, end = reg.get("start"), reg.get("end")
    if start is not None and end is not None and start <= now <= end:
        return "LIVE"
    pre = ctp.get("pre") or {}
    if pre.get("start") and pre.get("end") and pre["start"] <= now <= pre["end"]:
        return "PRE"
    post = ctp.get("post") or {}
    if post.get("start") and post.get("end") and post["start"] <= now <= post["end"]:
        return "POST"
    return "CLOSED"

def cmd_chart(argv):
    # symbol range interval width height style zoom pan refresh_label range_label
    symbol = argv[0].upper()
    range_ = argv[1]
    interval = argv[2]
    width = max(24, int(argv[3]))
    height = max(6, int(argv[4]))
    style = argv[5] if len(argv) > 5 else "line"
    zoom = argv[6] if len(argv) > 6 else "1"
    pan = argv[7] if len(argv) > 7 else "1"
    refresh_label = argv[8] if len(argv) > 8 else ""
    range_label = argv[9] if len(argv) > 9 else range_.upper()
    mode = argv[10] if len(argv) > 10 else ""

    meta, pts = fetch_chart(symbol, range_, interval)
    win, off, vis, n, zoom_f, pan_f = window_points(pts, zoom, pan)
    # plot area scales with the terminal: shrink labels on tight screens
    axis_w = 11 if width >= 56 else (8 if width >= 40 else 6)
    plot_w = max(12, width - axis_w - 1)
    if mode == "full":
        title_h = 2
    else:
        title_h = 4 if height >= 18 else (3 if height >= 14 else 2)
    x_h = 1
    plot_h = max(4, height - title_h - x_h)

    closes = [p[4] for p in win]
    highs = [p[2] for p in win]
    lows = [p[3] for p in win]
    lo = min(lows)
    hi = max(highs)
    pad = (hi - lo) * 0.06 if hi != lo else max(abs(hi) * 0.01, 0.01)
    ylo, yhi = lo - pad, hi + pad

    grid = [[" " for _ in range(plot_w)] for _ in range(plot_h)]
    candles = bucket_ohlc(win, plot_w)
    if style == "ohlc":
        draw_ohlc(grid, candles, ylo, yhi)
    else:
        ys = [y_of(c[4], ylo, yhi, plot_h) for c in candles]
        draw_line(grid, ys, area=(style == "area"))

    # Live day change comes from spark (previousClose is absent on long-range charts)
    live = {}
    try:
        live = fetch_spark([symbol]).get(symbol) or {}
    except Exception:
        live = {}
    price = live.get("price")
    if price is None:
        price = meta.get("regularMarketPrice")
    if price is None:
        price = pts[-1][4]
    prev = live.get("prev")
    if prev is None:
        prev = meta.get("previousClose")
    ch = live.get("change")
    if ch is None and price is not None and prev is not None:
        ch = float(price) - float(prev)
    pct = live.get("pct")
    if pct is None and ch is not None and prev:
        pct = (ch / float(prev)) * 100.0
    ch_s, pct_s = fmt_chg(ch, pct)
    direction = "UP" if (ch or 0) > 0 else ("DN" if (ch or 0) < 0 else "FLAT")
    name = meta.get("shortName") or meta.get("longName") or symbol
    ccy = meta.get("currency") or ""
    sess = session_flag(meta)
    tz = meta.get("timezone") or "UTC"
    last_ts = meta.get("regularMarketTime") or pts[-1][0]
    last_dt = datetime.fromtimestamp(int(last_ts), tz=timezone.utc).strftime("%Y-%m-%d %H:%M")
    open_p = win[0][1]
    close_p = win[-1][4]
    vol = sum(p[5] for p in win)
    win_lo = min(p[3] for p in win)
    win_hi = max(p[2] for p in win)

    # current-price marker on the y scale
    y_px = y_of(float(price), ylo, yhi, plot_h)

    left_w = width
    def fit(s):
        s = s[:left_w]
        return s + " " * (left_w - len(s))

    dir_mark = "^" if direction == "UP" else ("v" if direction == "DN" else "=")
    follow = "LIVE-FOLLOW" if abs(pan_f - 1.0) < 1e-9 else "HIST"
    if title_h <= 2:
        print(fit(
            f"{symbol} {fmt_price(price)} {dir_mark}{ch_s} ({pct_s})  "
            f"{range_label} {style} {sess}"
        ))
        print(fit(
            f"{fmt_axis_ts(win[0][0], range_)}..{fmt_axis_ts(win[-1][0], range_)}  "
            f"H {fmt_price(win_hi)} L {fmt_price(win_lo)}  {follow}"
        ))
    else:
        line1 = f"{symbol}  {name}"
        right1 = f"{sess}"
        padn = max(1, width - len(line1) - len(right1))
        print(fit(f"{line1}{' ' * padn}{right1}"))

        line2 = f"{fmt_price(price)} {ccy}  {dir_mark} {ch_s}  ({pct_s})  {direction}"
        right2 = f"{last_dt} {tz}"
        padn = max(1, width - len(line2) - len(right2))
        print(fit(f"{line2}{' ' * padn}{right2}"))

        print(fit(
            f"Range {range_label}  Zoom {zoom_f:.2f}x  "
            f"Bars {vis}/{n}  {follow}  Refresh {refresh_label}  Style {style}"
        ))
        if title_h >= 4:
            print(fit(
                f"Win {fmt_axis_ts(win[0][0], range_)} .. {fmt_axis_ts(win[-1][0], range_)}   "
                f"O {fmt_price(open_p)}  H {fmt_price(win_hi)}  "
                f"L {fmt_price(win_lo)}  C {fmt_price(close_p)}  Vol {fmt_vol(vol)}"
            ))

    # y labels: top, mid, bot + current
    labels = {
        0: fmt_price(yhi),
        plot_h // 2: fmt_price((yhi + ylo) / 2),
        plot_h - 1: fmt_price(ylo),
        y_px: fmt_price(float(price)),
    }
    for y in range(plot_h):
        if y in labels and y in (0, plot_h // 2, plot_h - 1):
            lab = labels[y].rjust(axis_w - 2)
            edge = "+"
        elif y == y_px:
            lab = fmt_price(float(price)).rjust(axis_w - 2)
            edge = ">"
        else:
            lab = " " * (axis_w - 2)
            edge = "|"
        row = "".join(grid[y])
        if y == y_px:
            row = "".join((":" if ch == " " else ch) for ch in row)
        print(fit(f"{lab} {edge}{row}"))

    # x axis
    left = fmt_axis_ts(win[0][0], range_)
    mid = fmt_axis_ts(win[len(win) // 2][0], range_)
    right = fmt_axis_ts(win[-1][0], range_)
    axis = " " * axis_w + left
    room = plot_w - len(left)
    mid_pos = (plot_w // 2) - len(mid) // 2
    # build axis under plot
    under = [" "] * plot_w
    def place(s, pos):
        pos = max(0, min(plot_w - len(s), pos))
        for i, ch in enumerate(s):
            under[pos + i] = ch
    place(left, 0)
    place(mid, plot_w // 2 - len(mid) // 2)
    place(right, plot_w - len(right))
    print(fit(" " * axis_w + "".join(under)))

    printed = title_h + plot_h + x_h
    while printed < height:
        print(fit(""))
        printed += 1

    print(f"META|{symbol}|{direction}|{ch_s}|{pct_s}|{sess}|{zoom_f:.4f}|{pan_f:.4f}|{n}|{off}|{vis}|{name}|{ccy}")

def strip_html(s):
    s = re.sub(r"(?is)<script[^>]*>.*?</script>", " ", s or "")
    s = re.sub(r"(?is)<style[^>]*>.*?</style>", " ", s)
    s = re.sub(r"(?s)<[^>]+>", " ", s)
    s = html.unescape(s)
    s = re.sub(r"\s+", " ", s).strip()
    return s

def parse_pubdate(s):
    s = (s or "").strip()
    fmts = (
        "%a, %d %b %Y %H:%M:%S %z",
        "%a, %d %b %Y %H:%M:%S %Z",
        "%Y-%m-%dT%H:%M:%S%z",
        "%Y-%m-%dT%H:%M:%SZ",
    )
    for fmt in fmts:
        try:
            raw = s
            if fmt.endswith("Z") and raw.endswith("Z"):
                raw = raw[:-1] + "+0000"
            if raw.endswith("GMT"):
                raw = raw[:-3] + "+0000"
                return datetime.strptime(raw, "%a, %d %b %Y %H:%M:%S %z")
            return datetime.strptime(raw, fmt)
        except ValueError:
            continue
    return None

def parse_rss_items(xml_bytes, default_source):
    root = ET.fromstring(xml_bytes)
    items = []
    for el in root.findall(".//item"):
        title = strip_html(el.findtext("title") or "")
        if not title:
            continue
        desc = strip_html(el.findtext("description") or "")
        src_el = el.find("source")
        source = ""
        if src_el is not None:
            source = strip_html((src_el.text or "") or src_el.get("url") or "")
        if not source:
            source = default_source
        # Google News titles often end with " - Outlet"
        if " - " in title and source == "Google News":
            left, right = title.rsplit(" - ", 1)
            if left and right and len(right) < 48:
                title, source = left, right
        pub_el = el.findtext("pubDate") or el.findtext("{http://purl.org/dc/elements/1.1/}date") or ""
        dt = parse_pubdate(pub_el)
        unix = int(dt.timestamp()) if dt else 0
        if dt:
            pub_s = dt.strftime("%Y-%m-%d %H:%M")
        else:
            pub_s = (pub_el or "")[:16]
        link = (el.findtext("link") or "").strip()
        if not link:
            guid = el.find("guid")
            if guid is not None:
                permalink = (guid.get("isPermaLink") or "true").lower()
                if permalink != "false":
                    link = (guid.text or "").strip()
        items.append((
            unix, pub_s,
            source.replace("|", "/"),
            title.replace("|", "/"),
            desc.replace("|", "/"),
            (link or "").replace("|", "%7C"),
        ))
    return items

def cmd_news(argv):
    symbol = (argv[0] if argv else "").strip().upper()
    if not symbol:
        print("ERR|symbol required")
        return
    enc = urllib.parse.quote(symbol, safe="-")
    q = urllib.parse.quote(f"{symbol} stock")
    feeds = (
        (f"https://feeds.finance.yahoo.com/rss/2.0/headline?s={enc}&region=US&lang=en-US", "Yahoo Finance"),
        (f"https://news.google.com/rss/search?q={q}&hl=en-US&gl=US&ceid=US:en", "Google News"),
    )
    last_err = None
    for url, src in feeds:
        try:
            raw = http_get(url, timeout=10)
            items = parse_rss_items(raw, src)
            if not items:
                continue
            print(f"SRC|{src}|{len(items)}")
            for unix, pub_s, source, title, desc, link in items[:30]:
                print(f"OK|{unix}|{pub_s}|{source}|{title}|{desc}|{link}")
            return
        except Exception as e:
            last_err = e
            continue
    print(f"ERR|{last_err or 'No headlines found'}")

def decode_html(raw):
    if isinstance(raw, str):
        return raw
    for enc in ("utf-8", "latin-1"):
        try:
            return raw.decode(enc)
        except UnicodeDecodeError:
            continue
    return raw.decode("utf-8", "replace")

def extract_readable(raw):
    html_s = decode_html(raw)
    title = ""
    m = re.search(r"(?is)<meta[^>]+property=['\"]og:title['\"][^>]*content=['\"]([^'\"]+)", html_s)
    if not m:
        m = re.search(r"(?is)<meta[^>]+content=['\"]([^'\"]+)['\"][^>]*property=['\"]og:title['\"]", html_s)
    if m:
        title = html.unescape(m.group(1)).strip()
    if not title:
        m = re.search(r"(?is)<title[^>]*>(.*?)</title>", html_s)
        if m:
            title = strip_html(m.group(1))
    lead = ""
    m = re.search(r"(?is)<meta[^>]+property=['\"]og:description['\"][^>]*content=['\"]([^'\"]+)", html_s)
    if not m:
        m = re.search(r"(?is)<meta[^>]+content=['\"]([^'\"]+)['\"][^>]*property=['\"]og:description['\"]", html_s)
    if not m:
        m = re.search(r"(?is)<meta[^>]+name=['\"]description['\"][^>]*content=['\"]([^'\"]+)", html_s)
    if m:
        lead = html.unescape(m.group(1)).strip()
    body_html = html_s
    for pat in (
        r"(?is)<article\b[^>]*>(.*?)</article>",
        r"(?is)<main\b[^>]*>(.*?)</main>",
        r"(?is)<div[^>]+(?:article-body|caas-body|post-content|entry-content|story-body)[^>]*>(.*)$",
    ):
        m = re.search(pat, html_s)
        if m and len(m.group(1)) > 200:
            body_html = m.group(1)
            break
    body_html = re.sub(r"(?is)<script[^>]*>.*?</script>", " ", body_html)
    body_html = re.sub(r"(?is)<style[^>]*>.*?</style>", " ", body_html)
    body_html = re.sub(r"(?is)<(nav|footer|aside|form|noscript)\b[^>]*>.*?</\1>", " ", body_html)
    paras = []
    for p in re.findall(r"(?is)<p\b[^>]*>(.*?)</p>", body_html):
        t = strip_html(p)
        if len(t) >= 40:
            paras.append(t)
    if paras:
        text = "\n\n".join(paras)
        if lead and lead[:80] not in text[:400]:
            text = lead + "\n\n" + text
        return title, text[:16000]
    text = strip_html(body_html)
    text = re.sub(r"\n{3,}", "\n\n", text).strip()
    if lead and lead[:80] not in (text or "")[:400]:
        text = (lead + "\n\n" + (text or "")).strip()
    return title, (text or lead or "")[:16000]

def cmd_article(argv):
    import textwrap
    url = (argv[0] if argv else "").strip()
    width = int(argv[1]) if len(argv) > 1 and str(argv[1]).isdigit() else 72
    title = argv[2] if len(argv) > 2 else ""
    fallback = argv[3] if len(argv) > 3 else ""
    width = max(20, min(120, width))
    via = "rss"
    text = ""
    err = ""
    if url:
        try:
            raw = http_get(url, timeout=12, accept="text/html,application/xhtml+xml,*/*;q=0.8")
            fetched_title, text = extract_readable(raw)
            if fetched_title and not title:
                title = fetched_title
            elif fetched_title and title and fetched_title != title:
                if len(fetched_title) > len(title):
                    title = fetched_title
            if text and len(strip_html(text)) >= 80:
                via = "article"
            else:
                text = ""
        except Exception as e:
            err = str(e)
    if not text:
        text = (fallback or "").strip()
        via = "rss"
        if not text:
            text = err or "No article text available for this headline."
    print(f"TITLE|{(title or 'Article').replace('|', '/')}")
    print(f"URL|{(url or '').replace('|', '%7C')}")
    print(f"VIA|{via}")
    chunks = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()] or [text]
    for i, para in enumerate(chunks):
        if i:
            print("P|")
        for line in textwrap.wrap(para, width=width) or [""]:
            print(f"P|{line}")

def main():
    if len(sys.argv) < 2:
        print("usage: quotes|chart|news|article ...", file=sys.stderr)
        sys.exit(2)
    cmd = sys.argv[1]
    if cmd == "quotes":
        cmd_quotes(sys.argv[2:])
    elif cmd == "chart":
        try:
            cmd_chart(sys.argv[2:])
        except Exception as e:
            print(f"ERR|{e}")
            sys.exit(1)
    elif cmd == "news":
        try:
            cmd_news(sys.argv[2:])
        except Exception as e:
            print(f"ERR|{e}")
            sys.exit(1)
    elif cmd == "article":
        try:
            cmd_article(sys.argv[2:])
        except Exception as e:
            print(f"ERR|{e}")
            sys.exit(1)
    else:
        print("unknown command", file=sys.stderr)
        sys.exit(2)

if __name__ == "__main__":
    main()
PY

py() {
  python3 -c "$STOCKGRAM_PY" "$@"
}

# --- watchlist --------------------------------------------------------------
declare -A SHARES=()

normalize_shares() {
  local v="${1:-0}"
  v="${v//,/}"
  v="${v// /}"
  [[ -z "$v" ]] && { printf '0'; return; }
  if [[ "$v" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
    printf '%s' "$v"
  else
    printf '0'
  fi
}

set_share_count() {
  local t="$1" v
  v="$(normalize_shares "${2:-0}")"
  if [[ "$v" == "0" || "$v" == "0.0" || "$v" == "0.00" ]]; then
    SHARES["$t"]="0"
  else
    SHARES["$t"]="$v"
  fi
}

share_count() {
  local t="$1"
  printf '%s' "${SHARES[$t]:-0}"
}

load_watchlist() {
  TICKERS=()
  SHARES=()
  if [[ -f "$WATCHLIST_FILE" ]]; then
    local line sym rest sh
    while IFS= read -r line || [[ -n "$line" ]]; do
      line="${line%%#*}"
      line="${line#"${line%%[![:space:]]*}"}"
      line="${line%"${line##*[![:space:]]}"}"
      [[ -z "$line" ]] && continue
      if [[ "$line" =~ ^([A-Za-z0-9._^=-]+)[=:]([0-9]+([.][0-9]+)?)$ ]]; then
        sym="${BASH_REMATCH[1]^^}"
        sh="${BASH_REMATCH[2]}"
      else
        read -r sym rest <<< "$line"
        sym="${sym^^}"
        sym="${sym// /}"
        sh="$(normalize_shares "${rest:-0}")"
      fi
      [[ -z "$sym" ]] && continue
      if ticker_exists "$sym"; then
        set_share_count "$sym" "$sh"
        continue
      fi
      TICKERS+=("$sym")
      set_share_count "$sym" "$sh"
    done < "$WATCHLIST_FILE"
  fi
  if ((${#TICKERS[@]} == 0)); then
    TICKERS=("${DEFAULT_TICKERS[@]}")
    save_watchlist
  fi
}

save_watchlist() {
  mkdir -p "$CONFIG_DIR"
  local t sh
  : > "$WATCHLIST_FILE"
  for t in "${TICKERS[@]+"${TICKERS[@]}"}"; do
    sh="$(share_count "$t")"
    if [[ "$sh" != "0" && "$sh" != "0.0" && "$sh" != "0.00" ]]; then
      printf '%s %s\n' "$t" "$sh" >> "$WATCHLIST_FILE"
    else
      printf '%s\n' "$t" >> "$WATCHLIST_FILE"
    fi
  done
}

ticker_exists() {
  local t="$1" x
  for x in "${TICKERS[@]+"${TICKERS[@]}"}"; do
    [[ "$x" == "$t" ]] && return 0
  done
  return 1
}

add_ticker() {
  local t="${1^^}"
  t="${t// /}"
  [[ -z "$t" ]] && { STATUS="Empty symbol"; return 1; }
  if ticker_exists "$t"; then
    STATUS="$t already in portfolio"
    return 1
  fi
  if ! curl -fsS --max-time 12 -A "$UA" \
      "$YF/v8/finance/chart/$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1], safe="-"))' "$t")?interval=1d&range=5d" \
      | python3 -c 'import json,sys; d=json.load(sys.stdin); e=(d.get("chart") or {}).get("error"); r=(d.get("chart") or {}).get("result");
raise SystemExit(0 if r else 1)' 2>/dev/null; then
    STATUS="Could not add $t — unknown or delisted"
    return 1
  fi
  TICKERS+=("$t")
  set_share_count "$t" 0
  save_watchlist
  SELECTED=$((${#TICKERS[@]} - 1))
  STATUS="Added $t"
}

remove_selected() {
  if ((${#TICKERS[@]} == 0)); then
    STATUS="Portfolio is empty"
    return
  fi
  local t="${TICKERS[$SELECTED]}"
  local next=()
  local i
  for i in "${!TICKERS[@]}"; do
    ((i == SELECTED)) && continue
    next+=("${TICKERS[$i]}")
  done
  TICKERS=("${next[@]+"${next[@]}"}")
  unset "SHARES[$t]"
  save_watchlist
  if ((${#TICKERS[@]} == 0)); then
    SELECTED=0
  elif ((SELECTED >= ${#TICKERS[@]})); then
    SELECTED=$((${#TICKERS[@]} - 1))
  fi
  STATUS="Removed $t"
}

# --- terminal ---------------------------------------------------------------
term_size() {
  local c="" l=""
  if read -r l c < <(stty size 2>/dev/null); then
    :
  else
    c="${COLUMNS:-}"
    l="${LINES:-}"
    [[ -z "$c" ]] && c=$(tput cols 2>/dev/null || echo 80)
    [[ -z "$l" ]] && l=$(tput lines 2>/dev/null || echo 24)
  fi
  [[ "$c" =~ ^[0-9]+$ ]] || c=80
  [[ "$l" =~ ^[0-9]+$ ]] || l=24
  ((c < 40)) && c=40
  ((l < 12)) && l=12
  local changed=0
  if ((c != COLS || l != ROWS)); then
    changed=1
  fi
  COLS=$c
  ROWS=$l
  compute_layout
  if ((changed)); then
    LAST_COLS=$COLS
    LAST_ROWS=$ROWS
  fi
}

compute_layout() {
  # Density from both size and aspect: small fonts / large windows = wide.
  if ((ROWS <= 18 || COLS < 64)); then
    DENSITY="compact"
  elif ((COLS >= 120 && ROWS >= 30)); then
    DENSITY="wide"
  else
    DENSITY="normal"
  fi

  case "$DENSITY" in
    compact)
      BANNER_H=2
      FOOTER_H=1
      ;;
    wide)
      BANNER_H=3
      FOOTER_H=2
      ;;
    *)
      BANNER_H=3
      FOOTER_H=2
      ;;
  esac
  ((ROWS < 16)) && BANNER_H=1
  ((ROWS < 14)) && FOOTER_H=1

  local avail=$((ROWS - BANNER_H - FOOTER_H))
  ((avail < 8)) && avail=8

  local news_min=4 news_max=6
  case "$DENSITY" in
    compact) news_min=5; news_max=6 ;;
    wide)    news_min=7; news_max=$((avail / 3 + 4)); ((news_max > 16)) && news_max=16 ;;
    *)       news_min=5; news_max=$((6 + (avail - 16) / 5)); ((news_max < 6)) && news_max=6; ((news_max > 12)) && news_max=12 ;;
  esac

  local list_min=5
  local ticker_n=${#TICKERS[@]}
  local list_want=$((ticker_n + 3))
  ((list_want < list_min + 2)) && list_want=$((list_min + 2))
  ((list_want > avail - news_min)) && list_want=$((avail - news_min))

  NEWS_H=$((avail - list_want))
  ((NEWS_H > news_max)) && NEWS_H=$news_max
  ((NEWS_H < news_min)) && NEWS_H=$news_min
  LIST_H=$((avail - NEWS_H))
  ((LIST_H < list_min)) && LIST_H=$list_min
  # Reconcile if we overflow (tiny terminal)
  if ((BANNER_H + LIST_H + NEWS_H + FOOTER_H > ROWS)); then
    LIST_H=$((ROWS - BANNER_H - NEWS_H - FOOTER_H))
    ((LIST_H < 4)) && LIST_H=4
  fi

  LIST_TOP=$((BANNER_H + 1))
  NEWS_TOP=$((LIST_TOP + LIST_H))
  INNER=$((COLS - 4))
  ((INNER < 12)) && INNER=12

  # Column pack — leftover width goes to name / sparkline
  SYM_W=6
  PRICE_W=10
  LIVE_W=14
  PCT_W=7
  VOL_W=7
  RANGE_W=15
  SHARES_W=6
  VALUE_W=10
  SHOW_VOL=0
  SHOW_RANGE=0
  SHOW_52W=0
  SHOW_SPARK=0
  SHOW_SHARES=1
  SHOW_VALUE=0
  NAME_W=8
  SPARK_W=0
  ((COLS >= 88)) && LIVE_W=16
  ((COLS >= 96)) && PCT_W=8

  local fixed=$((1 + SYM_W + 1 + SHARES_W + 1 + PRICE_W + 1 + LIVE_W + 1 + PCT_W))
  local remain=$((INNER - fixed))
  if ((remain >= 6)); then
    NAME_W=8
    ((COLS >= 80)) && NAME_W=12
    ((COLS >= 100)) && NAME_W=16
    ((COLS >= 120)) && NAME_W=22
    ((NAME_W > remain - 2)) && NAME_W=$((remain - 2))
    ((NAME_W < 6)) && NAME_W=6
    remain=$((INNER - fixed - NAME_W - 1))
  else
    NAME_W=$((remain > 4 ? remain : 4))
    remain=0
  fi
  SHOW_VOL=0
  SHOW_RANGE=0
  SHOW_52W=0
  SHOW_VALUE=0
  if ((COLS >= 92 && remain >= VALUE_W + 2)); then
    SHOW_VALUE=1
    remain=$((remain - VALUE_W - 1))
  fi
  if ((COLS >= 118 && remain >= VOL_W + 2)); then
    SHOW_VOL=1
    remain=$((remain - VOL_W - 1))
  fi
  if ((COLS >= 138 && remain >= RANGE_W + 2)); then
    SHOW_RANGE=1
    remain=$((remain - RANGE_W - 1))
  fi
  if ((COLS >= 162 && remain >= 16)); then
    SHOW_52W=1
    remain=$((remain - 16))
  fi
  if ((COLS >= 78 && remain >= 8)); then
    SHOW_SPARK=1
    SPARK_W=$remain
    ((SPARK_W > 40)) && SPARK_W=40
  else
    SHOW_SPARK=0
    SPARK_W=0
  fi
}

enter_raw() {
  SAVED_STTY="$(stty -g 2>/dev/null || true)"
  # min 1 so `read -t` actually waits for a key or the refresh timeout
  # -icrnl keeps Enter as CR; empty-line reads are still treated as Enter.
  stty -echo -icanon -icrnl min 1 time 0 2>/dev/null || stty -echo -icanon -icrnl 2>/dev/null || stty -echo -icanon 2>/dev/null || true
}

leave_raw() {
  if [[ -n "$SAVED_STTY" ]]; then
    stty "$SAVED_STTY" 2>/dev/null || stty echo icanon
  else
    stty echo icanon 2>/dev/null || true
  fi
}

enter_alt() {
  printf '\033[?1049h\033[?25l\033[H\033[J'
  # distinguish Shift+Enter without remapping Shift+letter (U, G, ...)
  printf '\033[>4;1m'
  ALT_SCREEN=1
  FORCE_CLEAR=1
}

leave_alt() {
  if ((ALT_SCREEN)); then
    printf '\033[>4;0m'
    printf '\033[?25h\033[?1049l'
    ALT_SCREEN=0
  else
    printf '\033[?25h'
  fi
}

cleanup() {
  leave_raw
  leave_alt
}
trap cleanup EXIT
trap 'NEED_REDRAW=1' WINCH
trap 'exit 0' INT TERM

read_key() {
  local timeout="$1"
  local k k2 k3 k4
  KEY=""
  if ((NEED_REDRAW)); then
    KEY="RESIZE"
    NEED_REDRAW=0
    return 0
  fi
  # -d '' so newline is a character, not a line delimiter (Enter would otherwise
  # complete the read with an empty $k).
  if ! IFS= read -rsn1 -d '' -t "$timeout" k; then
    if ((NEED_REDRAW)); then
      KEY="RESIZE"
      NEED_REDRAW=0
    else
      KEY="TIMEOUT"
    fi
    return 0
  fi
  # Successful read of a delimiter-only line (legacy / some terminals).
  if [[ -z "$k" ]]; then
    KEY="ENTER"
    return 0
  fi
  if [[ "$k" == $'\x1b' ]]; then
    IFS= read -rsn1 -t 0.05 k2 || { KEY="ESC"; return 0; }
    if [[ "$k2" == '[' ]]; then
      local seq="" ch
      while IFS= read -rsn1 -t 0.05 ch; do
        seq+="$ch"
        case "$ch" in
          [A-Za-z~u]) break ;;
        esac
        (( ${#seq} > 24 )) && break
      done
      case "$seq" in
        A) KEY="UP" ;;
        B) KEY="DOWN" ;;
        C) KEY="RIGHT" ;;
        D) KEY="LEFT" ;;
        H) KEY="HOME" ;;
        F) KEY="END" ;;
        Z) KEY="S-TAB" ;;
        5~) KEY="PGUP" ;;
        6~) KEY="PGDN" ;;
        3~) KEY="DEL" ;;
        13\;2~|27\;2\;13~|13\;2u|13\;2\;*) KEY="S-ENTER" ;;
        27\;2\;13~) KEY="S-ENTER" ;;
        *)
          if [[ "$seq" == *";2;13~" || "$seq" == "13;2u" || "$seq" == 27\;2\;13~ ]]; then
            KEY="S-ENTER"
          else
            KEY="ESC"
          fi
          ;;
      esac
      return 0
    fi
    if [[ "$k2" == 'O' ]]; then
      IFS= read -rsn1 -t 0.05 k3 || { KEY="ESC"; return 0; }
      case "$k3" in
        A) KEY="UP" ;;
        B) KEY="DOWN" ;;
        C) KEY="RIGHT" ;;
        D) KEY="LEFT" ;;
        H) KEY="HOME" ;;
        F) KEY="END" ;;
        M) KEY="ENTER" ;;
        *) KEY="ESC" ;;
      esac
      return 0
    fi
    # ESC then CR/LF — some terminals send this for Shift+Enter
    if [[ "$k2" == $'\r' || "$k2" == $'\n' ]]; then
      KEY="S-ENTER"
      return 0
    fi
    KEY="ESC"
    return 0
  fi
  case "$k" in
    $'\n'|$'\r'|$'\x0a'|$'\x0d') KEY="ENTER" ;;
    $'\x7f'|$'\x08') KEY="BACKSPACE" ;;
    ' ') KEY="SPACE" ;;
    *) KEY="$k" ;;
  esac
}

prompt_text() {
  local msg="$1"
  REPLY_TEXT=""
  leave_raw
  printf '\033[?25h'
  term_size
  printf '\033[%d;1H\033[K%s' "$ROWS" "$msg"
  IFS= read -r REPLY_TEXT || REPLY_TEXT=""
  printf '\033[?25l'
  enter_raw
  FORCE_CLEAR=1
}

# --- range / refresh --------------------------------------------------------
range_value() { printf '%s' "${RANGES[$RANGE_IDX]}"; }
range_label() { printf '%s' "${RANGE_LABELS[$RANGE_IDX]}"; }
style_value() { printf '%s' "${STYLES[$STYLE_IDX]}"; }
refresh_secs() { printf '%s' "${REFRESH_SECS[$REFRESH_IDX]}"; }
refresh_label() { printf '%s' "${REFRESH_LABELS[$REFRESH_IDX]}"; }

interval_for_range() {
  case "$(range_value)" in
    1d)  echo 1m ;;
    5d)  echo 5m ;;
    1mo) echo 30m ;;
    3mo|6mo|ytd|1y) echo 1d ;;
    2y)  echo 1d ;;
    5y|10y) echo 1wk ;;
    *) echo 1d ;;
  esac
}

cycle_refresh() {
  local dir="${1:-1}"
  REFRESH_IDX=$(( (REFRESH_IDX + dir + ${#REFRESH_SECS[@]}) % ${#REFRESH_SECS[@]} ))
  STATUS="Update every $(refresh_label)"
}

cycle_range() {
  local dir="${1:-1}"
  RANGE_IDX=$(( (RANGE_IDX + dir + ${#RANGES[@]}) % ${#RANGES[@]} ))
  ZOOM="1"
  PAN="1"
  STATUS="History $(range_label)"
}

cycle_style() {
  STYLE_IDX=$(( (STYLE_IDX + 1) % ${#STYLES[@]} ))
  STATUS="Chart style $(style_value)"
}

clamp_selected() {
  local n=${#TICKERS[@]}
  ((n == 0)) && { SELECTED=0; LIST_START=0; return; }
  ((SELECTED < 0)) && SELECTED=0
  ((SELECTED >= n)) && SELECTED=$((n - 1))
}

# Keep the highlighted ticker inside the visible portfolio rows.
sync_list_window() {
  local body="$1"
  local n=${#TICKERS[@]}
  ((body < 1)) && body=1
  ((n == 0)) && { LIST_START=0; return; }
  if ((SELECTED < LIST_START)); then
    LIST_START=$SELECTED
  fi
  if ((SELECTED >= LIST_START + body)); then
    LIST_START=$((SELECTED - body + 1))
  fi
  local max_start=$((n - body))
  ((max_start < 0)) && max_start=0
  ((LIST_START > max_start)) && LIST_START=$max_start
  ((LIST_START < 0)) && LIST_START=0
}

# --- drawing ----------------------------------------------------------------
hline() {
  local w="${1:-$COLS}" ch="${2:--}"
  local i s=""
  for ((i = 0; i < w; i++)); do s+="$ch"; done
  printf '%s' "$s"
}

fit_str() {
  local s="$1" w="$2"
  local n=${#s}
  if ((n > w)); then
    printf '%s' "${s:0:w}"
  else
    printf '%s%*s' "$s" $((w - n)) ""
  fi
}

goto_rc() {
  printf '\033[%d;%dH' "$1" "$2"
}

begin_paint() {
  if [[ "$VIEW" != "$LAST_VIEW" ]]; then
    if [[ "$VIEW" != article && "$LAST_VIEW" != article ]]; then
      FORCE_CLEAR=1
    fi
    LAST_VIEW="$VIEW"
  fi
  if ((FORCE_CLEAR)); then
    printf '\033[H\033[J\033[?25l'
    FORCE_CLEAR=0
  else
    printf '\033[H\033[?25l'
  fi
}

eol() {
  printf '\033[K'
}

toggle_pause() {
  if ((PAUSED)); then
    PAUSED=0
    STATUS="Live updates resumed"
  else
    PAUSED=1
    STATUS="Updates paused  [space] resume"
  fi
}

refresh_state_label() {
  if ((PAUSED)); then
    printf 'PAUSED'
  else
    printf '%s' "$(refresh_label)"
  fi
}

# Fill ASSET_* and POS_VALUE from current quotes and share counts.
declare -A POS_VALUE=()
compute_assets() {
  ASSET_HELD=0
  ASSET_VALUE_FMT="--"
  ASSET_DAY_FMT="--"
  ASSET_PCT_FMT="--"
  ASSET_DIR="FL"
  POS_VALUE=()
  local t raw sh
  local rows=""
  for t in "${TICKERS[@]+"${TICKERS[@]}"}"; do
    sh="$(share_count "$t")"
    [[ "$sh" == "0" || "$sh" == "0.0" || "$sh" == "0.00" ]] && continue
    raw="${QUOTE_BY_SYM[$t]:-}"
    [[ "$raw" != OK\|* ]] && continue
    local _ok _sym _name _price _chg _pct _dir _dh _dl _h52 _l52 _vol _ccy _spark px ch
    IFS='|' read -r _ok _sym _name _price _chg _pct _dir _dh _dl _h52 _l52 _vol _ccy _spark px ch _rest <<< "$raw"
    [[ -z "$px" ]] && continue
    rows+="${t}|${sh}|${px}|${ch:-0}"$'\n'
  done
  [[ -z "$rows" ]] && return 0
  local out
  out="$(printf '%s' "$rows" | python3 -c '
import sys
held = 0
val = 0.0
day = 0.0
vals = []
for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    parts = line.split("|")
    if len(parts) < 4:
        continue
    sym, shs, pxs, chs = parts[0], parts[1], parts[2], parts[3]
    try:
        sh = float(shs); px = float(pxs); ch = float(chs)
    except ValueError:
        continue
    if sh <= 0:
        continue
    held += 1
    pos = sh * px
    val += pos
    day += sh * ch
    vals.append("%s|%.2f" % (sym, pos))
def money(x):
    sign = "-" if x < 0 else ""
    return "%s$%s" % (sign, "{:,.2f}".format(abs(x)))
prev = val - day
pct = (day / prev * 100.0) if prev else 0.0
dire = "UP" if day > 0 else ("DN" if day < 0 else "FL")
dsign = "+" if day > 0 else ("-" if day < 0 else "")
print("SUM|%s|%s|%s%s|%s%.2f%%|%s" % (held, money(val), dsign, money(abs(day)), dsign, abs(pct), dire))
for item in vals:
    print("V|" + item)
')"
  [[ -z "$out" ]] && return 0
  local line kind
  while IFS= read -r line; do
    [[ -z "$line" ]] && continue
    IFS='|' read -r kind _rest <<< "$line"
    if [[ "$kind" == SUM ]]; then
      IFS='|' read -r _k ASSET_HELD ASSET_VALUE_FMT ASSET_DAY_FMT ASSET_PCT_FMT ASSET_DIR <<< "$line"
    elif [[ "$kind" == V ]]; then
      local vs ym
      IFS='|' read -r _k ym vs <<< "$line"
      [[ -n "$ym" ]] && POS_VALUE["$ym"]="$vs"
    fi
  done <<< "$out"
}

# Box from 1-based row `top`, height `height`, full terminal width.
draw_window_frame() {
  local top="$1" height="$2" title="$3" color="${4:-$C_CYAN}"
  local bot=$((top + height - 1))
  local inner=$((COLS - 2))
  ((inner < 8)) && inner=8
  local r
  goto_rc "$top" 1
  printf '%s+%s+%s' "$color" "$(hline "$inner" "-")" "$C_RESET"
  local t=" ${title} "
  (( ${#t} > inner - 2 )) && t="${t:0:inner-2}"
  goto_rc "$top" 3
  printf '%s%s%s' "$color$C_BOLD" "$t" "$C_RESET"
  for ((r = top + 1; r < bot; r++)); do
    goto_rc "$r" 1
    printf '%s|%s' "$color" "$C_RESET"
    goto_rc "$r" "$COLS"
    printf '%s|%s' "$color" "$C_RESET"
  done
  goto_rc "$bot" 1
  printf '%s+%s+%s' "$color" "$(hline "$inner" "-")" "$C_RESET"
}

# Write text inside a window; column 3, clipped to inner width.
win_write() {
  local row="$1" text="$2" color="${3:-}"
  local inner=$((COLS - 4))
  ((inner < 8)) && inner=8
  goto_rc "$row" 3
  printf '%s%s%s' "$color" "$(fit_str "$text" "$inner")" "$C_RESET"
}

wrap_lines() {
  local text="$1" width="$2" max_lines="${3:-4}"
  WRAP_LINES=()
  local line
  while IFS= read -r line; do
    WRAP_LINES+=("$line")
  done < <(python3 - "$text" "$width" "$max_lines" <<'PY'
import sys, textwrap
text, width, max_lines = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
width = max(8, width)
lines = textwrap.wrap(text or "", width=width) or [""]
if len(lines) > max_lines:
    lines = lines[:max_lines]
    if len(lines[-1]) > 3:
        lines[-1] = lines[-1][:-3] + "..."
for line in lines:
    print(line)
PY
)
}

banner_lines() {
  term_size
  local now geo pace
  now="$(date '+%Y-%m-%d %H:%M:%S')"
  geo="${COLS}x${ROWS} ${DENSITY}"
  if ((PAUSED)); then
    pace="PAUSED"
  else
    pace="$(refresh_label)"
  fi
  if ((BANNER_H <= 1)); then
    printf '%s%s  %s%s' "$C_YELLOW$C_BOLD" "$(fit_str "$APP_CREDIT" $((COLS - ${#geo} - 2)))" "$geo" "$C_RESET"
    eol
    printf '\n'
    return
  fi
  local right="$geo  $now"
  printf '%s%s%s%s%s' "$C_YELLOW$C_BOLD" "$(fit_str "$APP_CREDIT" $((COLS - ${#right} - 1)))" \
    "$C_DIM" "$right" "$C_RESET"
  eol
  printf '\n'
  if ((BANNER_H == 2)); then
    printf '%s%s  quotes %s  news 1m%s' "$C_DIM" \
      "$(fit_str "ASCII charts + RSS" 28)" "$pace" "$C_RESET"
    eol
    printf '\n'
    return
  fi
  printf '%s%s%s' "$C_CYAN" "$(fit_str "ASCII portfolio + history charts" "$COLS")" "$C_RESET"
  eol
  printf '\n'
  printf '%s%s  quotes %s  news auto 1m  %s%s' "$C_DIM" \
    "$(fit_str "Yahoo Finance" 22)" "$pace" "$now" "$C_RESET"
  eol
  printf '\n'
}

draw_help() {
  term_size
  banner_lines
  cat <<EOF
${C_BOLD}Portfolio window${C_RESET}
  Up/Down or j/k     select ticker (loads that stock's RSS news)
  Left/Right         scroll headlines in the news window
  c or C or Enter    open fullscreen ASCII chart
  s                  set share count for the selected ticker
  Space              pause / resume auto-updates (quotes, news, charts)
  G                  sort list by biggest day gains (%)
  a                  add ticker (call letters)
  x or Delete        remove selected ticker
  u / U              faster / slower update (2s .. 1h)
  R                  refresh quotes and news
  ?                  this help
  q                  quit

${C_BOLD}News window${C_RESET}
  Headlines for the selected ticker (Yahoo Finance RSS, Google fallback)
  Auto-refresh       every 1 minute from that stock's RSS feed
  Left/Right         previous / next headline
  Home / End         first / last headline
  Shift+Enter or o   open article text in a dialog (RSS preview + fetched body)

${C_BOLD}Chart${C_RESET}
  Left/Right         scroll history (pan)
  Home / End         oldest / newest (live follow)
  + or =             zoom in
  - or _             zoom out
  [ / ]              shorter / longer range (1D .. 10Y)
  1-9,0              1D 5D 1M 3M 6M YTD 1Y 2Y 5Y / 0=10Y
  c                  cycle style: line, area, ohlc
  n / p              next / previous ticker
  Space              pause / resume auto-updates
  u / U              update interval 2s .. 1h
  Esc or q           back to portfolio

${C_BOLD}Layout${C_RESET}
  Windows and ASCII charts resize with the terminal (${COLS}x${ROWS}, ${DENSITY}).
  Wider screens add position value, volume, day range, and longer sparklines.
  The portfolio footer keeps a running total of share positions.

${C_DIM}Data: Yahoo Finance public chart API. Not investment advice.
$APP_CREDIT${C_RESET}

Press any key to return.
EOF
}

# quote cache keyed by ticker symbol (survives scroll / failed refresh)
declare -A QUOTE_BY_SYM=()
LIST_START=0
SORT_MODE="watch"   # watch | gains

fetch_news() {
  local sym="${1:-}"
  local keep_title="" keep_idx=0 same=0
  local -a old_items=()
  local old_src="$NEWS_SRC"
  if [[ "$NEWS_SYM" == "$sym" ]]; then
    same=1
    keep_idx=$NEWS_IDX
    if ((${#NEWS_ITEMS[@]} > 0 && NEWS_IDX >= 0 && NEWS_IDX < ${#NEWS_ITEMS[@]})); then
      old_items=("${NEWS_ITEMS[@]}")
      IFS='|' read -r _ok _unix _pub _src keep_title _desc <<< "${NEWS_ITEMS[$NEWS_IDX]}"
    fi
  fi
  NEWS_ITEMS=()
  NEWS_SRC=""
  NEWS_ERR=""
  NEWS_SYM="$sym"
  NEWS_AT="$(date +%s)"
  if [[ -z "$sym" ]]; then
    NEWS_ERR="No ticker selected"
    NEWS_IDX=0
    return 1
  fi
  local out
  if ! out=$(py news "$sym" 2>"$CACHE_DIR/news.err"); then
    NEWS_ERR="News fetch failed"
    if ((${#old_items[@]} > 0)); then
      NEWS_ITEMS=("${old_items[@]}")
      NEWS_SRC="$old_src"
      NEWS_IDX=$keep_idx
      NEWS_ERR="RSS update failed; showing last headlines"
    fi
    return 1
  fi
  local line
  while IFS= read -r line; do
    [[ -z "$line" ]] && continue
    if [[ "$line" == SRC\|* ]]; then
      IFS='|' read -r _k NEWS_SRC _n <<< "$line"
    elif [[ "$line" == OK\|* ]]; then
      NEWS_ITEMS+=("$line")
    elif [[ "$line" == ERR\|* ]]; then
      NEWS_ERR="${line#ERR|}"
    fi
  done <<< "$out"
  if ((${#NEWS_ITEMS[@]} == 0)); then
    if ((${#old_items[@]} > 0)); then
      NEWS_ITEMS=("${old_items[@]}")
      NEWS_SRC="$old_src"
      NEWS_IDX=$keep_idx
      NEWS_ERR="No new headlines; showing last list"
      return 1
    fi
    [[ -z "$NEWS_ERR" ]] && NEWS_ERR="No headlines for $sym"
    NEWS_IDX=0
    return 1
  fi
  NEWS_ERR=""
  NEWS_IDX=0
  if ((same && ${#NEWS_ITEMS[@]} > 0)); then
    if ((keep_idx == 0)); then
      NEWS_IDX=0
    elif [[ -n "$keep_title" ]]; then
      local i title
      for i in "${!NEWS_ITEMS[@]}"; do
        IFS='|' read -r _ok _unix _pub _src title _desc <<< "${NEWS_ITEMS[$i]}"
        if [[ "$title" == "$keep_title" ]]; then
          NEWS_IDX=$i
          break
        fi
      done
    else
      NEWS_IDX=$keep_idx
    fi
    if ((NEWS_IDX >= ${#NEWS_ITEMS[@]})); then
      NEWS_IDX=$((${#NEWS_ITEMS[@]} - 1))
    fi
    ((NEWS_IDX < 0)) && NEWS_IDX=0
  fi
  return 0
}

ensure_news() {
  local force="${1:-0}"
  local sym="${TICKERS[$SELECTED]:-}"
  local now
  now="$(date +%s)"
  if [[ -z "$sym" ]]; then
    NEWS_ITEMS=()
    NEWS_SYM=""
    NEWS_ERR="No ticker selected"
    return 1
  fi
  if ((force == 0)) && [[ "$NEWS_SYM" == "$sym" ]]; then
    if (( ${#NEWS_ITEMS[@]} > 0 && now - NEWS_AT < NEWS_TTL )); then
      return 0
    fi
  fi
  if [[ "$NEWS_SYM" != "$sym" ]]; then
    NEWS_IDX=0
  fi
  fetch_news "$sym"
}

maybe_auto_refresh() {
  ((PAUSED)) && return
  [[ "$VIEW" == help || "$VIEW" == article ]] && return
  local now qint
  now="$(date +%s)"
  qint="$(refresh_secs)"
  if (( now - LAST_QUOTE_AT >= qint )); then
    fetch_quotes
  fi
  if [[ "$VIEW" != list ]]; then
    return
  fi
  local sel="${TICKERS[$SELECTED]:-}"
  if [[ -n "$sel" && "$NEWS_SYM" != "$sel" ]]; then
    ensure_news 1
  else
    ensure_news 0
  fi
}

loop_wait_secs() {
  if ((PAUSED)); then
    # Keep the input loop alive; do not poll quotes/charts.
    printf '60'
    return
  fi
  local now qint qleft nleft wait
  now="$(date +%s)"
  qint="$(refresh_secs)"
  qleft=$((LAST_QUOTE_AT + qint - now))
  nleft=$((NEWS_AT + NEWS_TTL - now))
  ((qleft < 1)) && qleft=1
  ((nleft < 1)) && nleft=1
  wait=$qleft
  if [[ "$VIEW" == list ]] && ((nleft < wait)); then
    wait=$nleft
  fi
  # After moving the highlight, wait briefly so rapid ↑↓ only fetch the final ticker.
  local sel="${TICKERS[$SELECTED]:-}"
  if [[ "$VIEW" == list && -n "$sel" && "$NEWS_SYM" != "$sel" ]]; then
    wait=0.35
  fi
  printf '%s' "$wait"
}

scroll_news() {
  local dir="$1"
  local n=${#NEWS_ITEMS[@]}
  ((n == 0)) && { STATUS="No headlines to scroll"; return; }
  NEWS_IDX=$(( (NEWS_IDX + dir + n) % n ))
  STATUS=""
}

fetch_quotes() {
  LAST_QUOTE_AT="$(date +%s)"
  if ((${#TICKERS[@]} == 0)); then
    return
  fi
  local joined
  joined=$(IFS=,; echo "${TICKERS[*]}")
  local out
  if ! out=$(py quotes "$joined" 2>"$CACHE_DIR/quotes.err"); then
    STATUS="Quote fetch failed"
    return
  fi
  local line _st sym
  while IFS= read -r line; do
    [[ "$line" == OK\|* || "$line" == ERR\|* ]] || continue
    IFS='|' read -r _st sym _rest <<< "$line"
    [[ -n "$sym" ]] && QUOTE_BY_SYM["$sym"]="$line"
  done <<< "$out"
  if [[ "$SORT_MODE" == gains ]]; then
    sort_by_gains quiet
  fi
}

# Biggest day gain first (percent). Missing quotes sink to the bottom.
sort_by_gains() {
  local quiet="${1:-}"
  if ((${#TICKERS[@]} == 0)); then
    [[ -z "$quiet" ]] && STATUS="Nothing to sort"
    return
  fi
  local keep="${TICKERS[$SELECTED]:-}"
  local sorted t raw pct
  sorted="$(
    for t in "${TICKERS[@]}"; do
      raw="${QUOTE_BY_SYM[$t]:-}"
      pct="-999999"
      if [[ "$raw" == OK\|* ]]; then
        pct="${raw##*|}"
      fi
      printf '%s\t%s\n' "$pct" "$t"
    done | LC_ALL=C sort -t $'\t' -k1,1nr
  )"
  TICKERS=()
  while IFS=$'\t' read -r pct t; do
    [[ -n "$t" ]] && TICKERS+=("$t")
  done <<< "$sorted"
  SELECTED=0
  if [[ -n "$keep" ]]; then
    local i
    for i in "${!TICKERS[@]}"; do
      if [[ "${TICKERS[$i]}" == "$keep" ]]; then
        SELECTED=$i
        break
      fi
    done
  fi
  LIST_START=0
  SORT_MODE="gains"
  if [[ -z "$quiet" ]]; then
    save_watchlist
    STATUS="Sorted by biggest gains (%)"
  fi
}

color_for_dir() {
  case "$1" in
    UP) printf '%s' "$C_UP" ;;
    DN) printf '%s' "$C_DN" ;;
    *)  printf '%s' "$C_DIM" ;;
  esac
}

arrow_for_dir() {
  case "$1" in
    UP) printf '%s' "^" ;;
    DN) printf '%s' "v" ;;
    *)  printf '%s' "=" ;;
  esac
}

draw_list() {
  term_size
  banner_lines
  compute_assets

  local list_h=$LIST_H list_top=$LIST_TOP news_h=$NEWS_H news_top=$NEWS_TOP inner=$INNER
  local sel_sym="${TICKERS[$SELECTED]:-}"
  local header_row=$((list_top + 1))
  local first_row=$((list_top + 2))
  local last_row=$((list_top + list_h - 2))
  ((last_row >= news_top)) && last_row=$((news_top - 1))
  ((last_row >= list_top + list_h - 1)) && last_row=$((list_top + list_h - 2))
  local summary_row=$last_row
  ((last_row > first_row)) && last_row=$((last_row - 1))
  local body_rows=$((last_row - first_row + 1))
  ((body_rows < 1)) && body_rows=1
  sync_list_window "$body_rows"
  local view_end=$((LIST_START + body_rows))
  ((view_end > ${#TICKERS[@]})) && view_end=${#TICKERS[@]}
  local port_title="PORTFOLIO  ${#TICKERS[@]} tickers"
  if ((${#TICKERS[@]} > body_rows)); then
    port_title="PORTFOLIO  $((LIST_START + 1))-${view_end}/${#TICKERS[@]}  ↑↓ scroll"
  fi
  [[ "$SORT_MODE" == gains ]] && port_title+="  GAINERS"
  if ((PAUSED)); then
    port_title+="  PAUSED"
  fi
  if ((ASSET_HELD > 0)); then
    port_title+="  ${ASSET_VALUE_FMT}"
  fi
  port_title+="  ${COLS}x${ROWS} ${DENSITY}"
  draw_window_frame "$list_top" "$list_h" "$port_title" "$C_CYAN"

  local hdr
  hdr="$(printf '%-6s %*s %-*s %*s' \
    "SYM" "$SHARES_W" "SHRS" "$NAME_W" "NAME" "$PRICE_W" "PRICE")"
  if ((SHOW_VALUE)); then
    hdr+="$(printf ' %*s' "$VALUE_W" "VALUE")"
  fi
  hdr+="$(printf ' %*s %*s' "$LIVE_W" "LIVE MOVE" "$PCT_W" "CHG %")"
  ((SHOW_VOL)) && hdr+="$(printf ' %*s' "$VOL_W" "VOL")"
  ((SHOW_RANGE)) && hdr+="  DAY RANGE"
  ((SHOW_52W)) && hdr+="  52W"
  ((SHOW_SPARK)) && hdr+="  TODAY"
  win_write "$header_row" "$hdr" "$C_DIM"

  if ((${#TICKERS[@]} == 0)); then
    win_write "$first_row" "Portfolio is empty. Press a to add call letters." "$C_YELLOW"
    local er
    for ((er = first_row + 1; er <= last_row; er++)); do
      win_write "$er" "" ""
    done
  else
    local i shown=0 row
    for ((i = LIST_START; i < ${#TICKERS[@]} && shown < body_rows; i++, shown++)); do
      row=$((first_row + shown))
      ((row > last_row)) && break
      ((row >= news_top)) && break
      local raw="${QUOTE_BY_SYM[${TICKERS[$i]}]:-}"
      local sym="${TICKERS[$i]}"
      local name="..." price="--" chg="--" pct="--" dir="FL" spark=""
      local _ok _sym _dh _dl _h52 _l52 _vol _ccy _spark px ch _rest
      local sh valtxt="--"
      sh="$(share_count "$sym")"
      if [[ "$raw" == OK\|* ]]; then
        IFS='|' read -r _ok _sym name price chg pct dir _dh _dl _h52 _l52 _vol _ccy spark px ch _rest <<< "$raw"
        valtxt="${POS_VALUE[$sym]:---}"
      elif [[ "$raw" == ERR\|* ]]; then
        name="(no data)"
        dir="FL"
      fi
      local shtxt="$sh"
      [[ "$sh" == "0" || "$sh" == "0.0" ]] && shtxt="-"
      local dcol
      dcol="$(color_for_dir "$dir")"
      local arr
      arr="$(arrow_for_dir "$dir")"
      local live
      case "$dir" in
        UP) live="$(printf 'UP %s %s' "$arr" "$chg")" ;;
        DN) live="$(printf 'DN %s %s' "$arr" "$chg")" ;;
        *)  live="$(printf 'FLAT %s' "$chg")" ;;
      esac
      local mark=" "
      ((i == SELECTED)) && mark=">"
      local rowtxt
      rowtxt="$(printf '%s%-5s %*s %-*s %*s' \
        "$mark" "$(fit_str "$sym" 5)" \
        "$SHARES_W" "$(fit_str "$shtxt" "$SHARES_W")" \
        "$NAME_W" "$(fit_str "$name" "$NAME_W")" \
        "$PRICE_W" "$price")"
      if ((SHOW_VALUE)); then
        rowtxt+="$(printf ' %*s' "$VALUE_W" "$(fit_str "$valtxt" "$VALUE_W")")"
      fi
      rowtxt+="$(printf ' %-*s %*s' \
        "$LIVE_W" "$(fit_str "$live" "$LIVE_W")" \
        "$PCT_W" "$(fit_str "$pct" "$PCT_W")")"
      if ((SHOW_VOL)); then
        rowtxt+="$(printf ' %*s' "$VOL_W" "$(fit_str "${_vol:---}" "$VOL_W")")"
      fi
      if ((SHOW_RANGE)); then
        rowtxt+="$(printf ' %s' "$(fit_str "${_dl:---}-${_dh:---}" "$RANGE_W")")"
      fi
      if ((SHOW_52W)); then
        rowtxt+="$(printf ' %s' "$(fit_str "${_l52:---}-${_h52:---}" 15)")"
      fi
      if ((SHOW_SPARK)); then
        rowtxt+=" $(fit_str "${spark:-}" "$SPARK_W")"
      fi
      if ((i == SELECTED)); then
        win_write "$row" "$rowtxt" "$C_REV$dcol"
      else
        win_write "$row" "$rowtxt" "$dcol"
      fi
    done
    local er
    for ((er = first_row + shown; er <= last_row; er++)); do
      win_write "$er" "" ""
    done
  fi

  local sum_col="$C_DIM" sum_txt
  if ((ASSET_HELD > 0)); then
    sum_col="$(color_for_dir "$ASSET_DIR")"
    sum_txt="ASSETS  ${ASSET_HELD} pos  ${ASSET_VALUE_FMT}  day ${ASSET_DAY_FMT}  ${ASSET_PCT_FMT}  [s] shares"
  else
    sum_txt="ASSETS  no positions  [s] set shares for a total"
  fi
  if ((PAUSED)); then
    sum_txt+="  PAUSED"
  fi
  win_write "$summary_row" "$sum_txt" "$sum_col$C_BOLD"

  # News window — confined; left/right scrolls this pane only
  local n=${#NEWS_ITEMS[@]}
  local news_age="--"
  if ((NEWS_AT > 0)); then
    news_age="$(( $(date +%s) - NEWS_AT ))s ago"
  fi
  local news_title="NEWS"
  if [[ -n "$sel_sym" ]]; then
    if ((n > 0)); then
      news_title="NEWS  ${sel_sym}  $((NEWS_IDX + 1))/${n}  ${NEWS_SRC:-RSS}  auto 1m  ${news_age}"
    else
      news_title="NEWS  ${sel_sym}  RSS auto 1m  ${news_age}"
    fi
  fi
  ((PAUSED)) && news_title+="  PAUSED"
  draw_window_frame "$news_top" "$news_h" "$news_title" "$C_MAGENTA"

  local nfirst=$((news_top + 1))
  local nlast=$((news_top + news_h - 2))
  local nbody=$((nlast - nfirst + 1))
  ((nbody < 2)) && nbody=2

  if [[ -z "$sel_sym" ]]; then
    win_write "$nfirst" "Select a ticker to load its news feed." "$C_DIM"
    local nr
    for ((nr = nfirst + 1; nr <= nlast; nr++)); do win_write "$nr" "" ""; done
  elif [[ "$NEWS_SYM" != "$sel_sym" ]]; then
    win_write "$nfirst" "Loading headlines for ${sel_sym}..." "$C_DIM"
    local nr
    for ((nr = nfirst + 1; nr <= nlast; nr++)); do win_write "$nr" "" ""; done
  elif [[ -n "$NEWS_ERR" && $n -eq 0 ]]; then
    win_write "$nfirst" "$NEWS_ERR" "$C_RED"
    local nr
    for ((nr = nfirst + 1; nr <= nlast; nr++)); do win_write "$nr" "" ""; done
  elif ((n == 0)); then
    win_write "$nfirst" "Loading headlines..." "$C_DIM"
    local nr
    for ((nr = nfirst + 1; nr <= nlast; nr++)); do win_write "$nr" "" ""; done
  else
    local item="${NEWS_ITEMS[$NEWS_IDX]}"
    local _ok unix pub source title desc link
    IFS='|' read -r _ok unix pub source title desc link <<< "$item"
    win_write "$nfirst" "$(printf '%s  %s' "$pub" "$source")" "$C_YELLOW"
    local title_h=1
    ((nbody >= 7)) && title_h=2
    local hint_h=1
    ((nbody < 4)) && hint_h=0
    local used=1
    wrap_lines "$title" "$inner" "$title_h"
    local wi r
    for ((wi = 0; wi < ${#WRAP_LINES[@]} && wi < title_h; wi++)); do
      r=$((nfirst + used))
      win_write "$r" "${WRAP_LINES[$wi]}" "$C_WHITE$C_BOLD"
      used=$((used + 1))
    done
    local preview="$desc"
    if [[ -z "$preview" ]]; then
      preview="No RSS summary. Shift+Enter opens the article."
    fi
    local prev_h=$((nbody - used - hint_h))
    ((prev_h < 1)) && prev_h=1
    wrap_lines "$preview" "$inner" "$prev_h"
    for ((wi = 0; wi < ${#WRAP_LINES[@]} && wi < prev_h; wi++)); do
      r=$((nfirst + used))
      ((r > nlast)) && break
      win_write "$r" "${WRAP_LINES[$wi]}" "$C_DIM"
      used=$((used + 1))
    done
    while ((used < nbody - hint_h)); do
      r=$((nfirst + used))
      ((r > nlast)) && break
      win_write "$r" "" ""
      used=$((used + 1))
    done
    if ((hint_h && nlast >= nfirst)); then
      local hint="Shift+Enter article"
      if ((n > 1)); then
        local next_i=$(( (NEWS_IDX + 1) % n ))
        local nitem="${NEWS_ITEMS[$next_i]}"
        local ntitle
        IFS='|' read -r _ok unix pub source ntitle desc link <<< "$nitem"
        hint="$(printf 'S-Enter article   next -> %s' "$ntitle")"
      fi
      win_write "$nlast" "$hint" "$C_DIM"
    fi
  fi

  local keys pace
  pace="$(refresh_state_label)"
  if ((COLS < 68)); then
    keys="[a] [x] [s]hrs [c] [space] [u]${pace} [q]"
  elif ((COLS < 110)); then
    keys="[a]dd [x]del [s]hares [c]hart [S-Enter]article [space]pause [u]${pace} [?] [q]"
  else
    keys="[a]dd [x]del [s]hares [c]hart [G]ains [Enter]chart [S-Enter]article [space]pause [up/dn]stock [<-/->]news [u]${pace} [?] [q]"
  fi
  if ((FOOTER_H <= 1)); then
    goto_rc "$ROWS" 1
    printf '\033[K%s%s%s' "$C_DIM" "$(fit_str "${STATUS:-$keys}" "$COLS")" "$C_RESET"
  else
    goto_rc $((ROWS - 1)) 1
    printf '\033[K%s%s%s' "$C_DIM" "$(fit_str "$keys" "$COLS")" "$C_RESET"
    goto_rc "$ROWS" 1
    printf '\033[K'
    if [[ -n "$STATUS" ]]; then
      printf '%s%s%s' "$C_YELLOW" "$(fit_str "$STATUS" "$COLS")" "$C_RESET"
    else
      printf '%s%s%s' "$C_DIM" "$(fit_str "$APP_CREDIT" "$COLS")" "$C_RESET"
    fi
  fi
}

chart_cache_key() {
  local foot=2
  ((ROWS < 16)) && foot=1
  local chart_rows=$((ROWS - foot))
  ((chart_rows < 6)) && chart_rows=6
  printf '%s' "${CHART_SYMBOL}|$(range_value)|$(interval_for_range)|${COLS}|${chart_rows}|$(style_value)|${ZOOM}|${PAN}"
}

load_chart_data() {
  term_size
  local key pace foot=2 chart_rows
  pace="$(refresh_state_label)"
  key="$(chart_cache_key)"
  if ((PAUSED)) && [[ -n "$CHART_CACHE" && "$CHART_CACHE_KEY" == "$key" ]]; then
    return
  fi
  ((ROWS < 16)) && foot=1
  chart_rows=$((ROWS - foot))
  ((chart_rows < 6)) && chart_rows=6
  local rc=0
  CHART_CACHE=$(py chart "$CHART_SYMBOL" "$(range_value)" "$(interval_for_range)" \
        "$COLS" "$chart_rows" "$(style_value)" "$ZOOM" "$PAN" \
        "$pace" "$(range_label)" "full" 2>"$CACHE_DIR/chart.err") || rc=$?
  CHART_CACHE_KEY="$key"
}

draw_chart() {
  term_size
  # Take the whole terminal: no portfolio/news panes, no list banner.
  local foot=2
  ((ROWS < 16)) && foot=1
  local chart_rows=$((ROWS - foot))
  ((chart_rows < 6)) && chart_rows=6

  local key pace out
  pace="$(refresh_state_label)"
  key="$(chart_cache_key)"
  if [[ -z "$CHART_CACHE" || "$CHART_CACHE_KEY" != "$key" ]]; then
    load_chart_data
  fi
  out="$CHART_CACHE"

  if [[ "$out" == ERR\|* ]]; then
    printf '%s%s%s' "$C_RED" "$(fit_str "CHART  ${CHART_SYMBOL}  ${out#ERR|}" "$COLS")" "$C_RESET"
    eol
    printf '\n'
    local r
    for ((r = 2; r <= chart_rows; r++)); do
      eol
      printf '\n'
    done
  else
    local line first=1
    local painted=0
    while IFS= read -r line; do
      [[ "$line" == META\|* ]] && continue
      if ((first)); then
        first=0
        printf '%s%s%s' "$C_BOLD$C_CYAN" "$line" "$C_RESET"
      elif [[ "$line" == *' UP '* || "$line" == *' UP'* || "$line" == *' UP' ]]; then
        printf '%s%s%s' "$C_UP" "$line" "$C_RESET"
      elif [[ "$line" == *' DN '* || "$line" == *' DN'* || "$line" == *' DN' ]]; then
        printf '%s%s%s' "$C_DN" "$line" "$C_RESET"
      else
        printf '%s' "$line"
      fi
      eol
      printf '\n'
      painted=$((painted + 1))
    done <<< "$out"
    while ((painted < chart_rows)); do
      eol
      printf '\n'
      painted=$((painted + 1))
    done
  fi

  local ckeys
  if ((COLS < 72)); then
    ckeys="[<-/->] [+/-] [[/]]$(range_label) [c] [space] [u]${pace} [q]"
  else
    ckeys="[<-/->]pan [+/-]zoom [[/]]$(range_label) [c]style [space]pause [u]${pace} [n/p]ticker [q]back  ${COLS}x${ROWS}"
  fi
  if ((foot <= 1)); then
    goto_rc "$ROWS" 1
    printf '%s%s%s' "$C_DIM" "$(fit_str "${STATUS:-$ckeys}" "$COLS")" "$C_RESET"
    eol
  else
    goto_rc $((ROWS - 1)) 1
    printf '%s%s%s' "$C_DIM" "$(fit_str "$ckeys" "$COLS")" "$C_RESET"
    eol
    goto_rc "$ROWS" 1
    if [[ -n "$STATUS" ]]; then
      printf '%s%s%s' "$C_YELLOW" "$(fit_str "$STATUS" "$COLS")" "$C_RESET"
    else
      printf '%s%s%s' "$C_DIM" "$(fit_str "$APP_CREDIT" "$COLS")" "$C_RESET"
    fi
    eol
  fi
}

draw_box_at() {
  local top="$1" left="$2" width="$3" height="$4" title="$5" color="${6:-$C_YELLOW}"
  local bot=$((top + height - 1))
  local inner=$((width - 2))
  ((inner < 8)) && inner=8
  local r
  goto_rc "$top" "$left"
  printf '%s+%s+%s' "$color" "$(hline "$inner" "-")" "$C_RESET"
  local t=" ${title} "
  (( ${#t} > inner - 2 )) && t="${t:0:inner-2}"
  goto_rc "$top" $((left + 2))
  printf '%s%s%s' "$color$C_BOLD" "$t" "$C_RESET"
  for ((r = top + 1; r < bot; r++)); do
    goto_rc "$r" "$left"
    printf '%s|%s|%s' "$color" "$(printf '%*s' "$inner" "")" "$C_RESET"
  done
  goto_rc "$bot" "$left"
  printf '%s+%s+%s' "$color" "$(hline "$inner" "-")" "$C_RESET"
}

box_write() {
  local row="$1" left="$2" width="$3" text="$4" color="${5:-}"
  local inner=$((width - 4))
  ((inner < 8)) && inner=8
  goto_rc "$row" $((left + 2))
  printf '%s%s%s' "$color" "$(fit_str "$text" "$inner")" "$C_RESET"
}

draw_article_dialog() {
  term_size
  local box_w=$((COLS - 6))
  ((box_w > 108)) && box_w=108
  ((box_w < 36)) && box_w=$((COLS - 2))
  ((box_w < 24)) && box_w=$COLS
  local box_h=$((ROWS - 4))
  ((box_h < 10)) && box_h=$((ROWS - 2))
  ((box_h < 8)) && box_h=$ROWS
  local top=$(( (ROWS - box_h) / 2 + 1 ))
  local left=$(( (COLS - box_w) / 2 + 1 ))
  ((top < 1)) && top=1
  ((left < 1)) && left=1
  local n=${#ARTICLE_LINES[@]}
  local title="ARTICLE"
  [[ -n "$ARTICLE_TITLE" ]] && title="ARTICLE  ${ARTICLE_TITLE}"
  draw_box_at "$top" "$left" "$box_w" "$box_h" "$title" "$C_YELLOW"

  local first=$((top + 1))
  local last=$((top + box_h - 2))
  local meta_h=2
  box_write "$first" "$left" "$box_w" "$(printf '%s  %s' "${ARTICLE_VIA:-rss}" "${ARTICLE_URL:-}")" "$C_DIM"
  box_write $((first + 1)) "$left" "$box_w" "Up/Down scroll   PgUp/PgDn   q close   space page" "$C_DIM"
  local body_top=$((first + meta_h))
  local body_h=$((last - body_top + 1))
  ((body_h < 1)) && body_h=1
  local max_start=$((n - body_h))
  ((max_start < 0)) && max_start=0
  ((ARTICLE_SCROLL > max_start)) && ARTICLE_SCROLL=$max_start
  ((ARTICLE_SCROLL < 0)) && ARTICLE_SCROLL=0
  local i r shown=0
  for ((i = ARTICLE_SCROLL; i < n && shown < body_h; i++, shown++)); do
    r=$((body_top + shown))
    box_write "$r" "$left" "$box_w" "${ARTICLE_LINES[$i]}" "$C_WHITE"
  done
  while ((shown < body_h)); do
    r=$((body_top + shown))
    box_write "$r" "$left" "$box_w" "" ""
    shown=$((shown + 1))
  done
}

open_article() {
  if ((${#NEWS_ITEMS[@]} == 0)); then
    STATUS="No headline to open"
    return
  fi
  local item="${NEWS_ITEMS[$NEWS_IDX]}"
  local _ok unix pub source title desc link
  IFS='|' read -r _ok unix pub source title desc link <<< "$item"
  if [[ -z "$link" && -z "$desc" ]]; then
    STATUS="No article text or link for this headline"
    return
  fi
  STATUS="Opening article..."
  local inner=$((COLS - 12))
  ((inner < 24)) && inner=24
  ((inner > 100)) && inner=100
  local out
  if ! out=$(py article "${link:-}" "$inner" "$title" "$desc" 2>"$CACHE_DIR/article.err"); then
    out="TITLE|${title}
URL|${link}
VIA|rss
P|${desc:-Could not load article.}"
  fi
  ARTICLE_TITLE=""
  ARTICLE_URL="$link"
  ARTICLE_VIA="rss"
  ARTICLE_LINES=()
  ARTICLE_SCROLL=0
  local line kind rest
  while IFS= read -r line; do
    [[ -z "$line" ]] && continue
    if [[ "$line" == ERR\|* ]]; then
      ARTICLE_LINES+=("${line#ERR|}")
      continue
    fi
    kind="${line%%|*}"
    rest="${line#*|}"
    case "$kind" in
      TITLE) ARTICLE_TITLE="$rest" ;;
      URL) ARTICLE_URL="$rest" ;;
      VIA) ARTICLE_VIA="$rest" ;;
      P) ARTICLE_LINES+=("$rest") ;;
    esac
  done <<< "$out"
  if ((${#ARTICLE_LINES[@]} == 0)); then
    if [[ -n "$desc" ]]; then
      wrap_lines "$desc" "$inner" 80
      ARTICLE_LINES=("${WRAP_LINES[@]}")
    else
      ARTICLE_LINES=("No article text available.")
    fi
  fi
  [[ -z "$ARTICLE_TITLE" ]] && ARTICLE_TITLE="$title"
  VIEW="article"
  STATUS=""
}

set_selected_shares() {
  if ((${#TICKERS[@]} == 0)); then
    STATUS="No ticker selected"
    return
  fi
  clamp_selected
  local t="${TICKERS[$SELECTED]}"
  local cur
  cur="$(share_count "$t")"
  prompt_text "Shares of $t [$cur]: "
  local v="$REPLY_TEXT"
  v="${v//,/}"
  v="${v#"${v%%[![:space:]]*}"}"
  v="${v%"${v##*[![:space:]]}"}"
  if [[ -z "$v" ]]; then
    STATUS="Shares unchanged"
    return
  fi
  if [[ ! "$v" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
    STATUS="Shares must be a number (got $v)"
    return
  fi
  set_share_count "$t" "$v"
  save_watchlist
  local shown
  shown="$(share_count "$t")"
  STATUS="$t  ${shown} shares"
}

draw() {
  # Fetch chart before wiping so the previous frame stays put during the request.
  if [[ "$VIEW" == chart ]]; then
    load_chart_data
  fi
  begin_paint
  case "$VIEW" in
    help) draw_help ;;
    chart) draw_chart ;;
    article)
      draw_list
      draw_article_dialog
      ;;
    *) draw_list ;;
  esac
}

open_chart() {
  if ((${#TICKERS[@]} == 0)); then
    STATUS="No ticker selected"
    return
  fi
  clamp_selected
  CHART_SYMBOL="${TICKERS[$SELECTED]}"
  ZOOM="1"
  PAN="1"
  VIEW="chart"
  STATUS="Chart $CHART_SYMBOL  $(range_label)"
}

zoom_in() {
  python3 - "$ZOOM" <<'PY'
import sys
z=float(sys.argv[1])
print(min(64.0, z * 1.5))
PY
}

zoom_out() {
  python3 - "$ZOOM" <<'PY'
import sys
z=float(sys.argv[1])
print(max(1.0, z / 1.5))
PY
}

pan_by() {
  local delta="$1"
  PAN=$(python3 - "$PAN" "$delta" <<'PY'
import sys
p=float(sys.argv[1]); d=float(sys.argv[2])
p=min(1.0, max(0.0, p+d))
print(f"{p:.6f}")
PY
)
}

# --- input ------------------------------------------------------------------
handle_list_key() {
  local prev=$SELECTED
  case "$KEY" in
    q|Q) exit 0 ;;
    UP|k|K) SELECTED=$((SELECTED - 1)); clamp_selected; STATUS="" ;;
    DOWN|j|J) SELECTED=$((SELECTED + 1)); clamp_selected; STATUS="" ;;
    PGUP) SELECTED=$((SELECTED - 10)); clamp_selected ;;
    PGDN) SELECTED=$((SELECTED + 10)); clamp_selected ;;
    LEFT) scroll_news -1 ;;
    RIGHT) scroll_news 1 ;;
    HOME) NEWS_IDX=0; STATUS="First headline" ;;
    END)
      if ((${#NEWS_ITEMS[@]} > 0)); then
        NEWS_IDX=$((${#NEWS_ITEMS[@]} - 1))
        STATUS="Last headline"
      fi
      ;;
    ENTER|$'\r'|$'\n'|c|C) open_chart ;;
    S-ENTER|o|O) open_article ;;
    s|S) set_selected_shares ;;
    SPACE) toggle_pause ;;
    a|A)
      local t
      prompt_text "Add ticker: "
      t="${REPLY_TEXT^^}"
      t="${t// /}"
      if [[ -n "$t" ]]; then
        add_ticker "$t"
        fetch_quotes
        fetch_news "${TICKERS[$SELECTED]:-}"
      else
        STATUS="Add cancelled"
      fi
      ;;
    x|X|DEL)
      remove_selected
      fetch_quotes
      fetch_news "${TICKERS[$SELECTED]:-}"
      ;;
    u) cycle_refresh 1 ;;
    U) cycle_refresh -1 ;;
    g|G)
      fetch_quotes
      sort_by_gains
      ;;
    R)
      CHART_CACHE=""
      CHART_CACHE_KEY=""
      fetch_quotes
      ensure_news 1
      STATUS="Refreshed quotes and news"
      ;;
    \?|h) VIEW="help" ;;
    TIMEOUT) ;;
  esac
  if ((SELECTED != prev)); then
    NEWS_IDX=0
    # Do not fetch RSS here — a fetch per arrow key blocks scrolling
    # and Yahoo 404s show up as "No data" while the list moves.
  fi
}

handle_chart_key() {
  case "$KEY" in
    q|Q|ESC) VIEW="list"; STATUS="" ;;
    LEFT)  pan_by -0.08; STATUS="Pan older" ;;
    RIGHT) pan_by  0.08; STATUS="Pan newer" ;;
    HOME)  PAN="0"; STATUS="Oldest" ;;
    END)   PAN="1"; STATUS="Live follow" ;;
    +|=)   ZOOM="$(zoom_in)"; STATUS="Zoom $ZOOM" ;;
    -|_)   ZOOM="$(zoom_out)"; STATUS="Zoom $ZOOM" ;;
    '[')   cycle_range -1 ;;
    ']')   cycle_range 1 ;;
    1) RANGE_IDX=0; ZOOM=1; PAN=1; STATUS="History 1D" ;;
    2) RANGE_IDX=1; ZOOM=1; PAN=1; STATUS="History 5D" ;;
    3) RANGE_IDX=2; ZOOM=1; PAN=1; STATUS="History 1M" ;;
    4) RANGE_IDX=3; ZOOM=1; PAN=1; STATUS="History 3M" ;;
    5) RANGE_IDX=4; ZOOM=1; PAN=1; STATUS="History 6M" ;;
    6) RANGE_IDX=5; ZOOM=1; PAN=1; STATUS="History YTD" ;;
    7) RANGE_IDX=6; ZOOM=1; PAN=1; STATUS="History 1Y" ;;
    8) RANGE_IDX=7; ZOOM=1; PAN=1; STATUS="History 2Y" ;;
    9) RANGE_IDX=8; ZOOM=1; PAN=1; STATUS="History 5Y" ;;
    0) RANGE_IDX=9; ZOOM=1; PAN=1; STATUS="History 10Y" ;;
    c|C) cycle_style ;;
    u) cycle_refresh 1 ;;
    U) cycle_refresh -1 ;;
    n|N)
      SELECTED=$((SELECTED + 1)); clamp_selected
      CHART_SYMBOL="${TICKERS[$SELECTED]}"
      ZOOM=1; PAN=1
      STATUS="Chart $CHART_SYMBOL"
      ;;
    p|P)
      SELECTED=$((SELECTED - 1)); clamp_selected
      CHART_SYMBOL="${TICKERS[$SELECTED]}"
      ZOOM=1; PAN=1
      STATUS="Chart $CHART_SYMBOL"
      ;;
    R)
      CHART_CACHE=""
      CHART_CACHE_KEY=""
      fetch_quotes
      STATUS="Refreshed"
      ;;
    SPACE) toggle_pause ;;
    \?|h) VIEW="help" ;;
    TIMEOUT) ;;
  esac
}

handle_article_key() {
  local n=${#ARTICLE_LINES[@]}
  local page=10
  ((page > ROWS - 8)) && page=$((ROWS - 8))
  ((page < 3)) && page=3
  case "$KEY" in
    q|Q|ESC|ENTER|$'\r'|$'\n') VIEW="list"; STATUS="" ;;
    UP|k|K) ARTICLE_SCROLL=$((ARTICLE_SCROLL - 1)) ;;
    DOWN|j|J) ARTICLE_SCROLL=$((ARTICLE_SCROLL + 1)) ;;
    PGUP) ARTICLE_SCROLL=$((ARTICLE_SCROLL - page)) ;;
    PGDN|SPACE) ARTICLE_SCROLL=$((ARTICLE_SCROLL + page)) ;;
    HOME) ARTICLE_SCROLL=0 ;;
    END) ARTICLE_SCROLL=$((n > 0 ? n - 1 : 0)) ;;
    TIMEOUT) ;;
  esac
  ((ARTICLE_SCROLL < 0)) && ARTICLE_SCROLL=0
}

handle_help_key() {
  case "$KEY" in
    TIMEOUT) ;;
    *) VIEW="list"; STATUS="" ;;
  esac
}

# --- CLI dump modes ---------------------------------------------------------
usage() {
  cat <<EOF
$APP_CREDIT

Usage:
  $(basename "$0")                      Interactive portfolio TUI
  $(basename "$0") --chart SYM [RANGE] [STYLE]
  $(basename "$0") --quotes SYM[,SYM...]
  $(basename "$0") --news SYM
  $(basename "$0") --check-deps
  $(basename "$0") --install-deps
  $(basename "$0") --help

Ranges: 1d 5d 1mo 3mo 6mo ytd 1y 2y 5y 10y
Styles: line  area  ohlc
Watchlist: $WATCHLIST_FILE

Portfolio keys: up/down select, left/right headlines, a add, x remove, s shares,
  Enter chart, Shift+Enter article, space pause, G gains
Chart keys: arrows pan, +/- zoom, [/] range, c style, space pause, q back

Layout: list, news, and ASCII charts scale to the terminal size (resize live).
News: selected ticker RSS headlines auto-refresh every 1 minute.
      Shift+Enter opens a preview/article dialog for the current headline.
Shares: press s to set how many shares you hold; the portfolio footer totals them.
Requires: python3, curl, tput (ncurses), stty (coreutils).
Missing tools are detected at startup and you are prompted to install them.
EOF
}

run_dump_chart() {
  local sym="${1^^}"
  local range="${2:-1y}"
  local style="${3:-line}"
  local idx=6
  local i
  for i in "${!RANGES[@]}"; do
    [[ "${RANGES[$i]}" == "$range" ]] && idx=$i
  done
  RANGE_IDX=$idx
  term_size
  echo "$APP_CREDIT"
  echo
  py chart "$sym" "$range" "$(interval_for_range)" "${COLS:-80}" 22 "$style" 1 1 "off" "${RANGE_LABELS[$RANGE_IDX]}" \
    | grep -v '^META|'
}

run_dump_quotes() {
  echo "$APP_CREDIT"
  echo
  py quotes "$1"
}

run_dump_news() {
  echo "$APP_CREDIT"
  echo
  py news "${1^^}"
}

# --- main loop --------------------------------------------------------------
main_loop() {
  load_watchlist
  enter_alt
  enter_raw
  fetch_quotes
  ensure_news 1
  draw
  while true; do
    read_key "$(loop_wait_secs)"
    if [[ "$KEY" == RESIZE ]]; then
      term_size
      FORCE_CLEAR=1
      STATUS="${COLS}x${ROWS} ${DENSITY}"
    else
      case "$VIEW" in
        help) handle_help_key ;;
        chart) handle_chart_key ;;
        article) handle_article_key ;;
        *) handle_list_key ;;
      esac
      # Do not block navigation or article/chart open on a quote/news fetch.
      case "$KEY" in
        ENTER|S-ENTER|c|C|g|G|o|O|s|S|UP|DOWN|k|K|j|J|PGUP|PGDN|HOME|END|LEFT|RIGHT) ;;
        *) maybe_auto_refresh ;;
      esac
    fi
    draw
  done
}

case "${1:-}" in
  -h|--help|help) usage; exit 0 ;;
  --check-deps)
    require_dependencies 1
    exit $?
    ;;
  --install-deps)
    STOCKGRAM_ASSUME_YES=1
    require_dependencies 0
    exit $?
    ;;
  --chart)
    require_dependencies 0 || exit 1
    ensure_dirs
    shift
    [[ $# -lt 1 ]] && { echo "symbol required"; exit 2; }
    run_dump_chart "$@"
    exit 0
    ;;
  --quotes)
    require_dependencies 0 || exit 1
    ensure_dirs
    shift
    [[ $# -lt 1 ]] && { echo "symbols required"; exit 2; }
    run_dump_quotes "$1"
    exit 0
    ;;
  --news)
    require_dependencies 0 || exit 1
    ensure_dirs
    shift
    [[ $# -lt 1 ]] && { echo "symbol required"; exit 2; }
    run_dump_news "$1"
    exit 0
    ;;
  "")
    require_dependencies 0 || exit 1
    ensure_dirs
    main_loop
    ;;
  *)
    echo "Unknown option: $1" >&2
    usage >&2
    exit 2
    ;;
esac
