/* ═══════════════════════════════════════════════════════════════════
   COIN WATCHLIST RAIL · left side, 24 coins, sparkline + group dot
   ═══════════════════════════════════════════════════════════════════ */

function CoinRail({ activeSym, onSelect, coins: propCoins, portfolioTotal, portfolioPnl, onEditHoldings }) {
  /* collapsible rail — reclaim space for charts; remembered across pages */
  const [railHidden, setRailHidden] = React.useState(
    () => localStorage.getItem('st-rail-hidden') === '1');
  const toggleRail = () => {
    localStorage.setItem('st-rail-hidden', railHidden ? '0' : '1');
    setRailHidden(!railHidden);
    setTimeout(() => window.dispatchEvent(new Event('resize')), 60);
  };
  const [filter, setFilter] = React.useState('ALL');
  const [query, setQuery] = React.useState('');
  const COINS = propCoins || ST_COINS;

  const filtered = React.useMemo(() => {
    return COINS.filter(c => {
      const g = ST_GROUP[c.group];
      if (filter !== 'ALL' && g && g.label !== filter) return false;
      if (query && !c.sym.toLowerCase().includes(query.toLowerCase())) return false;
      return true;
    });
  }, [filter, query, COINS]);

  const filters = ['ALL', 'INST', 'MOM', 'DEFI', 'MEME'];

  if (railHidden) {
    return (
      <aside onClick={toggleRail} title="Show watchlist" style={{
        width: 24, flexShrink: 0, borderRight: `1px solid ${ST.border}`,
        background: ST.bg, cursor: 'pointer', display: 'flex',
        flexDirection: 'column', alignItems: 'center', paddingTop: 14, gap: 12,
      }}>
        <span style={{ color: ST.amber, fontSize: 12, lineHeight: 1 }}>▸</span>
        <span className="mono" style={{ writingMode: 'vertical-rl', fontSize: 8.5,
          letterSpacing: '0.24em', color: ST.ink4 }}>WATCHLIST</span>
      </aside>
    );
  }

  return (
    <aside style={{
      width: 232, flexShrink: 0,
      borderRight: `1px solid ${ST.border}`,
      background: ST.bg,
      display: 'flex', flexDirection: 'column',
      minHeight: 0,
    }}>
      {/* brand */}
      <div style={{
        padding: '14px 16px',
        borderBottom: `1px solid ${ST.border}`,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <ShadowMark />
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, color: ST.ink, letterSpacing: '-0.01em' }}>Shadow</div>
          <div className="mono" style={{ fontSize: 9, color: ST.ink3, letterSpacing: '0.16em' }}>TERMINAL</div>
        </div>
        <span className="st-live-dot" style={{ marginLeft: 'auto' }} />
        <a href="../settings/" title="Settings" aria-label="Settings" style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 22, height: 22, borderRadius: 6, color: ST.ink3,
          textDecoration: 'none', transition: 'color .15s, background .15s',
        }}
          onMouseEnter={e => { e.currentTarget.style.color = ST.amber; e.currentTarget.style.background = `${ST.amber}14`; }}
          onMouseLeave={e => { e.currentTarget.style.color = ST.ink3; e.currentTarget.style.background = 'transparent'; }}>
          <svg width="14.5" height="14.5" viewBox="0 0 24 24" fill="none" stroke="currentColor"
            strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
            <circle cx="12" cy="12" r="3.15" />
            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
          </svg>
        </a>
        <button onClick={toggleRail} title="Hide watchlist" style={{
          width: 20, height: 20, borderRadius: 5, padding: 0, lineHeight: 1,
          background: 'transparent', border: `1px solid ${ST.border}`,
          color: ST.ink3, cursor: 'pointer', fontSize: 10,
        }}>◂</button>
      </div>

      {/* global product nav */}
      <ShadowNav />

      {/* search */}
      <div style={{ padding: '10px 12px', borderBottom: `1px solid ${ST.border}` }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 10px',
          background: ST.panel, borderRadius: 6,
          border: `1px solid ${ST.border}`,
        }}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <circle cx="5" cy="5" r="3.2" stroke={ST.ink3} strokeWidth="1.2" />
            <path d="M 7.5 7.5 L 10 10" stroke={ST.ink3} strokeWidth="1.2" strokeLinecap="round" />
          </svg>
          <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Search · /"
            className="mono"
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: ST.ink, fontSize: 11, padding: 0,
            }}
          />
          <span className="mono" style={{ fontSize: 9, color: ST.ink4 }}>{filtered.length}</span>
        </div>

        {/* group filter chips */}
        <div style={{ display: 'flex', gap: 4, marginTop: 8, flexWrap: 'wrap' }}>
          {filters.map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className="mono"
              style={{
                padding: '3px 7px', fontSize: 9, letterSpacing: '0.08em',
                background: filter === f ? `${ST.amber}1A` : 'transparent',
                color: filter === f ? ST.amber : ST.ink3,
                border: `1px solid ${filter === f ? ST.amber + '40' : ST.border}`,
                borderRadius: 3, cursor: 'pointer',
              }}
            >{f}</button>
          ))}
        </div>
      </div>

      {/* sticky group header for active coin */}
      <div style={{
        padding: '10px 16px 6px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <span className="eyebrow">WATCHLIST</span>
        <span className="mono" style={{ fontSize: 9, color: ST.ink4 }}>24h%</span>
      </div>

      {/* list */}
      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
        {filtered.map(c => (
          <CoinRow key={c.sym} {...c}
            active={c.sym === (activeSym || c.active)}
            onClick={() => onSelect && onSelect(c.sym)} />
        ))}
      </div>

      {/* portfolio summary */}
      <div style={{
        padding: '12px 16px',
        borderTop: `1px solid ${ST.border}`,
        background: ST.panel,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span className="eyebrow">PORTFOLIO</span>
          <span onClick={onEditHoldings} className="mono" style={{
            fontSize: 9, color: ST.amber, cursor: 'pointer', letterSpacing: '0.06em',
            border: `1px solid ${ST.amber}40`, borderRadius: 3, padding: '1px 6px',
          }}>✎ EDIT</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 2 }}>
          <div className="num" style={{ fontSize: 19, fontWeight: 500, color: ST.ink }}>
            {portfolioTotal != null
              ? `$${portfolioTotal.toLocaleString('en-US', {maximumFractionDigits:0})}`
              : <span style={{ fontSize: 13, color: ST.ink4 }}>—</span>}
          </div>
          {portfolioPnl != null && (
            <span className="num" style={{ fontSize: 11, fontWeight: 600, color: portfolioPnl >= 0 ? ST.green : ST.red }}>
              {portfolioPnl >= 0 ? '+' : ''}{portfolioPnl.toFixed(2)}%
            </span>
          )}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
          <span className="mono" style={{ fontSize: 10, color: ST.ink3 }}>
            {portfolioTotal != null ? 'my holdings' : 'add your holdings →'}
          </span>
        </div>
      </div>
    </aside>
  );
}

function CoinRow({ sym, name, price, chg, group, active, vol, onClick }) {
  const g = ST_GROUP[group] || { c: ST.ink3, label: 'N/A' };
  return (
    <div className={active ? '' : 'fx-row'} onClick={onClick} style={{
      display: 'grid',
      gridTemplateColumns: '3px 1fr 56px auto',
      alignItems: 'center', gap: 8,
      padding: '8px 16px 8px 13px',
      background: active ? 'linear-gradient(90deg, rgba(247,166,0,0.07) 0%, rgba(247,166,0,0) 100%)' : 'transparent',
      borderLeft: active ? `2px solid ${ST.amber}` : '2px solid transparent',
      paddingLeft: active ? 11 : 13,
      cursor: 'pointer',
      position: 'relative',
    }}>
      {/* group dot */}
      <div style={{
        width: 3, height: 24, borderRadius: 1, background: g.c, opacity: active ? 1 : 0.5,
      }} />

      {/* symbol + name */}
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
          <span className="mono" style={{
            fontSize: 12, fontWeight: 600,
            color: active ? ST.amber : ST.ink,
            letterSpacing: '-0.01em',
          }}>{sym}</span>
          <span className="mono" style={{ fontSize: 9, color: ST.ink4 }}>{g.label}</span>
        </div>
        <div className="mono" style={{ fontSize: 10, color: ST.ink3, marginTop: 1 }}>
          ${ST_fmt.price(price)}
        </div>
      </div>

      {/* sparkline */}
      <svg width="56" height="18" viewBox="0 0 56 18" style={{ display: 'block' }}>
        <path d={ST_sparkline(sym, 56, 16)}
          stroke={chg >= 0 ? ST.green : ST.red}
          strokeWidth="1" fill="none"
          strokeLinecap="round" strokeLinejoin="round"
          opacity={active ? 1 : 0.7} />
      </svg>

      {/* % change */}
      <span className="mono" style={{
        fontSize: 11, fontWeight: 500,
        color: chg >= 0 ? ST.green : ST.red,
        minWidth: 44, textAlign: 'right',
      }}>
        {ST_fmt.pct(chg, 2)}
      </span>
    </div>
  );
}

/* ── Shadow mark (logo glyph) ─────────────────────────────────────── */
function ShadowMark({ size = 26 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 26 26" style={{ flexShrink: 0 }}>
      <defs>
        <linearGradient id="sm-grad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%"   stopColor={ST.amber} />
          <stop offset="100%" stopColor="#C97800" />
        </linearGradient>
      </defs>
      <rect x="1" y="1" width="24" height="24" rx="6"
        fill="url(#sm-grad)" />
      <path d="M 8 9 L 13 13 L 8 17 M 13 9 L 18 13 L 13 17"
        stroke="#0B0D14" strokeWidth="1.8" fill="none"
        strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

window.CoinRail = CoinRail;
window.ShadowMark = ShadowMark;

/* ── Global product nav (shared across all pages) ──────────────────── */
const ST_NAV = [
  { id: 'dashboard', label: 'MARKET', href: '../dashboard/' },
  { id: 'coin',      label: 'COIN',   href: '../coin/' },
  { id: 'shadow',    label: 'SHADOW', href: '../shadow/' },
  { id: 'trade',     label: 'TRADE',  href: '../trade/' },
  { id: 'bots',      label: 'BOTS',   href: '../bots/' },
];

function ShadowNav() {
  const active = (window.ST_PAGE || '').toLowerCase();
  return (
    <nav style={{
      display: 'flex', gap: 3,
      padding: '8px 12px',
      borderBottom: `1px solid ${ST.border}`,
    }}>
      {ST_NAV.map(n => {
        const on = n.id === active;
        return (
          <a key={n.id} href={n.href}
            className="mono"
            title={n.label}
            style={{
              flex: 1, textAlign: 'center',
              padding: '5px 0', fontSize: 9, letterSpacing: '0.08em', fontWeight: 600,
              textDecoration: 'none',
              color: on ? ST.amber : ST.ink3,
              background: on ? `${ST.amber}16` : 'transparent',
              border: `1px solid ${on ? ST.amber + '44' : ST.border}`,
              borderRadius: 4,
              transition: 'color .15s, background .15s, border-color .15s',
            }}
            onMouseEnter={e => { if (!on) { e.currentTarget.style.color = ST.ink; e.currentTarget.style.borderColor = ST.borderHi; } }}
            onMouseLeave={e => { if (!on) { e.currentTarget.style.color = ST.ink3; e.currentTarget.style.borderColor = ST.border; } }}
          >{n.label}</a>
        );
      })}
    </nav>
  );
}
window.ShadowNav = ShadowNav;
