// terminal-watchlists.jsx — Watchlists screen + Holding Detail screen.
// Templated from screenshot 1: stock card → multi-line benchmark chart
// → time-period switcher → Description/Disclaimer links.

function WatchlistRow({ tile, onClick }) {
  const color = tile.up ? TM.green : TM.red;
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      display: 'grid', gridTemplateColumns: '1fr 80px 100px', gap: 12, alignItems: 'center',
      padding: '14px 16px', borderBottom: `1px solid ${TM.border}`,
    }}>
      <div>
        <div style={{ fontFamily: GE, fontSize: 15, fontWeight: 600, color: TM.text, letterSpacing: -0.2 }}>{tile.sym}</div>
        <div style={{ fontFamily: GE, fontSize: 12, color: TM.muted, marginTop: 2, letterSpacing: -0.1 }}>{tile.name}</div>
      </div>
      <div style={{ height: 30 }}>
        <MiniSpark data={tile.spark} color={color} height={30}/>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: GM, fontSize: 14, fontWeight: 600, color: TM.text, letterSpacing: -0.1 }}>
          {tile.base < 10 ? tile.price.toFixed(4) : tile.price.toLocaleString(undefined, { maximumFractionDigits: 2 })}
        </div>
        <div style={{ fontFamily: GM, fontSize: 11, color, marginTop: 2 }}>
          {tile.up ? '+' : ''}{tile.pct.toFixed(2)}%
        </div>
      </div>
    </button>
  );
}

function WatchlistsScreen({ onOpenDetail }) {
  const rows = watchlistRows();
  const [filter, setFilter] = React.useState('all');

  const filtered = filter === 'gainers' ? rows.filter(r => r.up)
                  : filter === 'losers' ? rows.filter(r => !r.up) : rows;

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto' }} className="tx-scroll">
      <TopBar title="Watchlists" subtitle={`${rows.length} symbols · last sync 14:02 ET`}
        right={<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <SearchButton/>
          <button style={{ color: TM.orange, fontFamily: GE, fontSize: 13, fontWeight: 500 }}>+ Add</button>
        </div>}/>

      <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
        <Segmented value={filter} onChange={setFilter} options={[
          { key: 'all',     label: 'All' },
          { key: 'gainers', label: 'Gainers' },
          { key: 'losers',  label: 'Losers' },
        ]}/>
        <button style={{ color: TM.muted, fontFamily: GM, fontSize: 11, letterSpacing: 0.6 }}>SORT ↓</button>
      </div>

      {filtered.map(tile => (
        <WatchlistRow key={tile.sym} tile={tile} onClick={() => onOpenDetail(tile.sym)}/>
      ))}

      <div style={{ padding: '32px 16px', textAlign: 'center', color: TM.mutedDim }}>
        <Pill color={TM.muted}>END OF WATCHLIST</Pill>
      </div>
    </div>
  );
}

// ── Holding Detail screen — the centerpiece template ─────────
function HoldingDetailScreen({ sym, onBack, onTrade }) {
  const tile = marketTileFor(sym);
  const holding = holdingFor(sym);
  const [period, setPeriod] = React.useState('1y');

  // Pull a multi-line series: holding · S&P · Council conviction
  const points = 60;
  const series = React.useMemo(() => {
    const seedH = tmHash('hist:' + sym + ':' + period);
    const seedS = tmHash('hist:SPY:' + period);
    const seedC = tmHash('conv:' + sym + ':' + period);
    const ratio = period === '3m' ? 0.6 : period === '5y' ? 1.8 : 1.0;
    const hist  = priceSeries(seedH, tile.base * 0.92, tile.price, points, 0.018 * ratio);
    const sp    = priceSeries(seedS, tile.base * 0.95, tile.base * 1.10, points, 0.012 * ratio);
    // Council conviction is a 60-65% baseline trending toward 80-95%.
    const conv  = priceSeries(seedC, tile.base * 0.65, tile.base * 0.92, points, 0.015 * ratio);
    return [
      { label: 'Position', color: tile.up ? TM.green : TM.red, data: hist },
      { label: 'S&P 500',  color: TM.muted, data: sp },
      { label: 'Council',  color: TM.cyan,  data: conv },
    ];
  }, [sym, period, tile.up, tile.base, tile.price]);

  const perfRows = [
    { label: 'Last 3 Months', val: '+4.21%',  color: TM.green },
    { label: 'Last 1 Year',   val: '+1.43%',  color: TM.green },
    { label: 'Last 5 Years',  val: '+12.11%', color: TM.green },
  ];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflowY: 'auto' }} className="tx-scroll">
      <TopBar title={`${holding ? 'Portfolio · ' : ''}${tile.name}`} onBack={onBack}
        right={<div style={{ display: 'flex', gap: 6 }}>
          <button style={{ width: 32, height: 32, borderRadius: 16, color: TM.muted }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.6"/>
              <line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" strokeWidth="1.6"/>
            </svg>
          </button>
          <button style={{ width: 32, height: 32, borderRadius: 16, color: TM.muted }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M5 12v7a1 1 0 001 1h12a1 1 0 001-1v-7M12 3v12M8 7l4-4 4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>}/>

      {/* Headline card */}
      <div style={{ padding: '16px 16px 8px', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 22,
          background: tile.up ? TM.greenSoft : TM.redSoft,
          border: `1px solid ${tile.up ? TM.green : TM.red}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: GM, fontSize: 13, fontWeight: 600, color: tile.up ? TM.green : TM.red,
        }}>{sym.slice(0, 3)}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: GE, fontSize: 17, fontWeight: 600, color: TM.text, letterSpacing: -0.3 }}>
            {sym} <span style={{ color: TM.muted, fontWeight: 400 }}>{tile.name}</span>
          </div>
          <div style={{ marginTop: 4, fontFamily: GM, fontSize: 12, color: TM.muted, letterSpacing: 0.2 }}>
            Post Mkt <span style={{ color: TM.text }}>{tile.price}</span>
            <span style={{ color: tile.up ? TM.green : TM.red, marginLeft: 8 }}>
              {tile.up ? '+' : ''}{tile.delta} {tile.up ? '+' : ''}{tile.pct.toFixed(2)}%
            </span>
          </div>
        </div>
        <button style={{
          width: 32, height: 32, borderRadius: 16, color: TM.orange,
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M12 21s-7-4.5-7-10a4 4 0 0 1 7-2.5A4 4 0 0 1 19 11c0 5.5-7 10-7 10z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
            <line x1="12" y1="5" x2="12" y2="3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
        </button>
      </div>

      {/* 3-up stat strip — Holding % · Market Cap · Avg Target */}
      <div style={{
        margin: '8px 16px 0', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
        background: TM.surfaceHi, border: `1px solid ${TM.border}`, borderRadius: 10,
        padding: '14px 0',
      }}>
        {[
          { k: 'Holding %',         v: holding ? `${(holding.value / 18420 * 100).toFixed(2)}%` : '—' },
          { k: 'Market Cap',        v: '565.64M' },
          { k: 'Avg Target',        v: '$' + (tile.base * 1.08).toFixed(2), arrow: true },
        ].map((it, i) => (
          <div key={i} style={{
            textAlign: 'center', padding: '0 8px',
            borderLeft: i === 0 ? 'none' : `1px solid ${TM.border}`,
          }}>
            <div style={{ fontFamily: GE, fontSize: 11, color: TM.muted, letterSpacing: -0.05, marginBottom: 4 }}>{it.k}</div>
            <div style={{ fontFamily: GM, fontSize: 17, fontWeight: 600, color: TM.text, letterSpacing: -0.2 }}>
              {it.v}{it.arrow && <span style={{ color: TM.muted, marginLeft: 2 }}>›</span>}
            </div>
          </div>
        ))}
      </div>

      {/* Performance section */}
      <SectionHeader title="Performance" action="i"/>
      <div style={{
        margin: '0 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0,
      }}>
        {perfRows.map(p => (
          <div key={p.label} style={{ padding: '8px 0' }}>
            <div style={{ fontFamily: GE, fontSize: 12, color: TM.muted, letterSpacing: -0.05 }}>{p.label}</div>
            <div style={{
              fontFamily: GM, fontSize: 22, fontWeight: 600, color: p.color, letterSpacing: -0.4,
              marginTop: 4,
            }}>{p.val}</div>
          </div>
        ))}
      </div>

      {/* Period switcher */}
      <div style={{ padding: '12px 16px 8px' }}>
        <Segmented value={period} onChange={setPeriod} options={[
          { key: '3m', label: 'Last 3 Months' },
          { key: '1y', label: 'Last 1 Year' },
          { key: '5y', label: 'Last 5 Years' },
        ]}/>
      </div>

      {/* Legend + multi-line chart */}
      <div style={{ padding: '0 16px 0', display: 'flex', gap: 18, flexWrap: 'wrap' }}>
        {series.map(s => (
          <span key={s.label} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontFamily: GE, fontSize: 12, color: TM.text,
          }}>
            <span style={{ width: 8, height: 8, borderRadius: 4, background: s.color }}/>
            {s.label}
          </span>
        ))}
      </div>

      <div style={{ padding: '12px 16px 0' }}>
        <MultiLineChart series={series} height={180}/>
        <div style={{
          marginTop: 10, display: 'flex', justifyContent: 'space-between',
          fontFamily: GM, fontSize: 10, color: TM.muted, letterSpacing: 0.4,
        }}>
          <span>{period === '3m' ? 'FEB 21, 2026' : period === '5y' ? 'MAY 21, 2021' : 'MAY 20, 2025'}</span>
          <span>MAY 21, 2026</span>
        </div>
      </div>

      {/* Council conviction band — TradeXchange-specific spin */}
      <div style={{
        margin: '20px 16px 0', padding: '14px 16px',
        background: TM.cyanSoft, border: `1px solid rgba(35,200,233,0.30)`, borderRadius: 10,
      }}>
        <div style={{
          fontFamily: GM, fontSize: 10, color: TM.cyan, letterSpacing: 1.2, fontWeight: 600,
        }}>COUNCIL CONVICTION · LAST 30 DAYS</div>
        <div style={{
          marginTop: 8, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        }}>
          <span style={{ fontFamily: GM, fontSize: 32, fontWeight: 600, color: TM.text, letterSpacing: -0.8 }}>
            {(tile.up ? 0.84 : 0.62).toFixed(2)}
          </span>
          <span style={{ fontFamily: GE, fontSize: 13, color: TM.muted, letterSpacing: -0.1 }}>
            {tile.up ? '21 of 25 cleared' : '14 of 25 cleared'}
          </span>
        </div>
        <div style={{ marginTop: 10, height: 4, background: 'rgba(244,244,240,0.06)', borderRadius: 2, position: 'relative' }}>
          <div style={{
            position: 'absolute', inset: 0, width: `${(tile.up ? 0.84 : 0.62) * 100}%`,
            background: TM.cyan, borderRadius: 2,
          }}/>
          <div style={{
            position: 'absolute', left: `${(17 / 25) * 100}%`, top: -3, bottom: -3,
            width: 1, background: TM.orange,
          }}/>
        </div>
      </div>

      {/* Description / Disclaimer */}
      <div style={{
        margin: '24px 16px 24px', paddingTop: 18,
        borderTop: `1px solid ${TM.border}`,
        display: 'flex', justifyContent: 'center', gap: 36,
      }}>
        <button style={{ color: TM.cyan, fontFamily: GE, fontSize: 14, fontWeight: 500 }}>Description</button>
        <button style={{ color: TM.cyan, fontFamily: GE, fontSize: 14, fontWeight: 500 }}>Disclaimer</button>
      </div>

      {/* Sticky Trade button */}
      <div style={{
        position: 'sticky', bottom: 0, padding: '12px 16px',
        background: TM.surface, borderTop: `1px solid ${TM.border}`,
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
      }}>
        <button onClick={() => onTrade && onTrade(sym, 'live')} style={{
          padding: '12px 0', background: TM.green, color: TM.ink,
          borderRadius: 8, fontFamily: GE, fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        }}>Buy</button>
        <button onClick={() => onTrade && onTrade(sym, 'live')} style={{
          padding: '12px 0', background: TM.orange, color: TM.ink,
          borderRadius: 8, fontFamily: GE, fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        }}>Sell</button>
        <button onClick={() => onTrade && onTrade(sym, 'shadow')} style={{
          padding: '12px 0', background: 'transparent', color: TM.violet,
          border: `1px solid ${TM.violet}`, borderRadius: 8,
          fontFamily: GE, fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <span style={{ fontFamily: GM, fontWeight: 700 }}>◐</span> Shadow
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { WatchlistsScreen, WatchlistRow, HoldingDetailScreen });
