/* Company Stock Price — Stock Screener (live NSE quotes, API fields only) */
const SCREENER_FILTERS = ['All', 'Gainers', 'Losers', 'Unchanged'];
const SORT_OPTS = [
  { key: 'price', label: 'Price' },
  { key: 'chg', label: 'Change %' },
  { key: 'vol', label: 'Volume' },
  { key: 'hi52', label: '52W High' },
  { key: 'lo52', label: '52W Low' },
];
const SCREENER_PAGE = 25;

const COLS = [
  { key: 'rank', label: '#', cls: 'col-rank', sortable: false },
  { key: 'company', label: 'Company', cls: 'col-company', sortable: false },
  { key: 'price', label: 'Price', sortable: true },
  { key: 'chg', label: 'Chg %', sortable: true },
  { key: 'vol', label: 'Volume', sortable: true },
  { key: 'hi52', label: '52W High', sortable: true },
  { key: 'lo52', label: '52W Low', sortable: true },
  { key: 'action', label: '', sortable: false },
];

const QB_FIELDS = [
  { key: 'price', label: 'Price', unit: '₹', fmt: (v) => '₹' + fmt.price(v) },
  { key: 'chg', label: '1-Day Change', unit: '%', fmt: (v) => fmt.pct(v) },
  { key: 'vol', label: 'Volume', unit: 'sh', fmt: (v) => (v != null ? fmt.vol(v) : '—') },
  { key: 'fromHi', label: '% below 52W High', unit: '%', derive: (s) => s.hi52 ? +((1 - s.price / s.hi52) * 100).toFixed(2) : null, fmt: (v) => v != null ? v.toFixed(1) + '%' : '—' },
  { key: 'fromLo', label: '% above 52W Low', unit: '%', derive: (s) => s.lo52 ? +((s.price / s.lo52 - 1) * 100).toFixed(2) : null, fmt: (v) => v != null ? v.toFixed(1) + '%' : '—' },
];
const QB_OPS = [
  { key: 'gt', label: '>', test: (a, b) => a > b },
  { key: 'lt', label: '<', test: (a, b) => a < b },
  { key: 'gte', label: '≥', test: (a, b) => a >= b },
  { key: 'lte', label: '≤', test: (a, b) => a <= b },
];
const QB_PRESETS = [
  { name: 'Momentum movers', conds: [{ field: 'chg', op: 'gt', val: 1 }, { field: 'fromHi', op: 'lt', val: 8 }] },
  { name: 'Near 52W low', conds: [{ field: 'fromLo', op: 'lt', val: 15 }] },
  { name: 'High volume', conds: [{ field: 'vol', op: 'gt', val: 1000000 }] },
  { name: 'Pullback', conds: [{ field: 'fromHi', op: 'gt', val: 10 }, { field: 'chg', op: 'lt', val: 0 }] },
];

function fieldVal(field, s) {
  const def = QB_FIELDS.find((f) => f.key === field);
  return def.derive ? def.derive(s) : s[field];
}

function QueryBuilder({ stocks, conds, setConds, onOpenStock }) {
  function addCond() { setConds([...conds, { field: 'chg', op: 'gt', val: 0.5 }]); }
  function update(i, patch) { setConds(conds.map((c, j) => (j === i ? { ...c, ...patch } : c))); }
  function remove(i) { setConds(conds.filter((_, j) => j !== i)); }

  let results = stocks.filter((s) => conds.every((c) => {
    const op = QB_OPS.find((o) => o.key === c.op);
    const val = fieldVal(c.field, s);
    if (val == null) return false;
    return op.test(val, Number(c.val));
  }));
  results = [...results].sort((a, b) => b.chg - a.chg);

  return (
    <div>
      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-head" style={{ marginBottom: 12 }}>
          <div>
            <h3 className="h3">Build your screen</h3>
            <div className="muted">Stack conditions — all must match (AND). Live Yahoo NSE data.</div>
          </div>
          <span className="qb-count">{results.length} match{results.length === 1 ? '' : 'es'}</span>
        </div>
        <div className="pill-row" style={{ marginBottom: 14 }}>
          {QB_PRESETS.map((p) => (
            <button key={p.name} className="pill" onClick={() => setConds(p.conds)}>{p.name}</button>
          ))}
          <button className="pill" onClick={() => setConds([])}>Clear all</button>
        </div>
        {conds.map((c, i) => {
          const f = QB_FIELDS.find((x) => x.key === c.field) || QB_FIELDS[0];
          return (
            <div key={i} className="qb-row">
              <span className="qb-logic">{i === 0 ? 'WHERE' : 'AND'}</span>
              <select className="select" value={c.field} onChange={(e) => update(i, { field: e.target.value })}>
                {QB_FIELDS.map((fd) => <option key={fd.key} value={fd.key}>{fd.label}</option>)}
              </select>
              <select className="select" style={{ width: 72 }} value={c.op} onChange={(e) => update(i, { op: e.target.value })}>
                {QB_OPS.map((o) => <option key={o.key} value={o.key}>{o.label}</option>)}
              </select>
              <input className="qb-val" type="number" value={c.val} onChange={(e) => update(i, { val: e.target.value })} />
              <span className="muted">{f.unit}</span>
              <button className="icon-btn" onClick={() => remove(i)}><Icon name="x" size={16} /></button>
            </div>
          );
        })}
        <div style={{ display: 'flex', gap: 10, marginTop: 12, flexWrap: 'wrap' }}>
          <button className="pill active" style={{ height: 36 }} onClick={addCond}>+ Add condition</button>
        </div>
      </div>
      {results.length ? <ScreenerResults rows={results} onOpenStock={onOpenStock} />
        : <EmptyState icon="screener" title="No stocks match" sub="Loosen a condition or remove a filter to see results." />}
    </div>
  );
}

function ScreenerResults({ rows, onOpenStock, sortKey, sortDir, onSort }) {
  const [page, setPage] = useState(1);
  const ind = sortDir === 'desc' ? '↓' : '↑';
  const totalPages = Math.max(1, Math.ceil(rows.length / SCREENER_PAGE));
  const pageRows = rows.slice((page - 1) * SCREENER_PAGE, page * SCREENER_PAGE);
  const rankBase = (page - 1) * SCREENER_PAGE;

  useEffect(() => { setPage(1); }, [rows.length, sortKey, sortDir]);

  return (
    <>
      <div className="table-wrap">
        <table className="screener">
          <thead>
            <tr>
              {COLS.map((c) => (
                <th key={c.key} className={`${c.cls || ''} ${c.sortable && onSort ? 'sortable' : ''}`}
                  onClick={c.sortable && onSort ? () => onSort(c.key) : undefined}>
                  {c.label}{c.sortable && onSort && sortKey === c.key && <span className="sort-ind">{ind}</span>}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {pageRows.map((s, i) => (
              <tr key={s.id} onClick={() => onOpenStock(s)} style={{ cursor: 'pointer' }}>
                <td className="col-rank" style={{ color: 'var(--text-muted)' }}>{rankBase + i + 1}</td>
                <td className="col-company">
                  <div className="cc">
                    <StockAvatar stock={s} size={30} />
                    <div><div className="cc-name">{s.name}</div><div className="cc-ticker">{s.ticker}</div></div>
                  </div>
                </td>
                <td><span className="mono-num">₹{fmt.price(s.price)}</span></td>
                <td><ChangeChip value={s.chg} sm showArrow={false} /></td>
                <td><span className="mono-num">{s.vol != null ? fmt.vol(s.vol) : '—'}</span></td>
                <td><span className="mono-num" style={{ color: 'var(--text-secondary)' }}>{s.hi52 != null ? fmt.price(s.hi52) : '—'}</span></td>
                <td><span className="mono-num" style={{ color: 'var(--text-secondary)' }}>{s.lo52 != null ? fmt.price(s.lo52) : '—'}</span></td>
                <td><button className="row-action" onClick={(e) => { e.stopPropagation(); onOpenStock(s); }}>View</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {rows.length > SCREENER_PAGE && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 12, gap: 12, flexWrap: 'wrap' }}>
          <span className="muted" style={{ fontSize: 13 }}>
            Showing {rankBase + 1}–{rankBase + pageRows.length} of {rows.length}
          </span>
          <div className="pill-row">
            <button className="pill" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>Previous</button>
            <span className="muted" style={{ fontSize: 13, padding: '0 8px' }}>Page {page} / {totalPages}</span>
            <button className="pill" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Next</button>
          </div>
        </div>
      )}
    </>
  );
}

function ScreenerScreen({ onOpenStock, mode, onModeChange }) {
  const MD = useMarketData();
  const stocks = MD.stocks;
  const screenMode = mode || 'browse';
  const [filter, setFilter] = useState('All');
  const [q, setQ] = useState('');
  const [sortKey, setSortKey] = useState('chg');
  const [sortDir, setSortDir] = useState('desc');
  const [conds, setConds] = useState([{ field: 'chg', op: 'gt', val: 0 }]);

  if (MD.loading && !MD.ready) return <SkeletonScreener />;
  if (!stocks.length) return <EmptyState icon="screener" title="No stock data" sub={MD.error || 'Could not load quotes.'} action={<button className="pill" onClick={MD.reload}>Retry</button>} />;

  function toggleSort(key) {
    if (key === sortKey) setSortDir((d) => (d === 'desc' ? 'asc' : 'desc'));
    else { setSortKey(key); setSortDir('desc'); }
  }

  let rows = stocks.filter((s) => (s.name + s.ticker).toLowerCase().includes(q.toLowerCase()));
  if (filter === 'Gainers') rows = rows.filter((s) => s.chg > 0);
  else if (filter === 'Losers') rows = rows.filter((s) => s.chg < 0);
  else if (filter === 'Unchanged') rows = rows.filter((s) => s.chg === 0);
  rows = [...rows].sort((a, b) => {
    const av = a[sortKey] == null ? -Infinity : a[sortKey];
    const bv = b[sortKey] == null ? -Infinity : b[sortKey];
    return sortDir === 'desc' ? bv - av : av - bv;
  });

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <h1 className="h1">Stock Screener</h1>
            <LiveBadge live={MD.ready} />
          </div>
          <div className="muted" style={{ marginTop: 2 }}>
            {MD.stocksTotal || stocks.length} NSE stocks · live Yahoo quotes
            {MD.stocksLoadingMore ? ' · loading more…' : ''}
          </div>
        </div>
        <div className="seg">
          <button className={`seg-btn ${screenMode === 'browse' ? 'on' : ''}`} onClick={() => onModeChange && onModeChange('browse')}>Browse</button>
          <button className={`seg-btn ${screenMode === 'build' ? 'on' : ''}`} onClick={() => onModeChange && onModeChange('build')}><Icon name="sliders" size={14} /> Build screen</button>
        </div>
      </div>

      {screenMode === 'build' ? (
        <QueryBuilder stocks={stocks} conds={conds} setConds={setConds} onOpenStock={onOpenStock} />
      ) : (
        <>
          <div className="filter-bar">
            <div className="pill-row">
              {SCREENER_FILTERS.map((f) => (
                <button key={f} className={`pill ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>{f}</button>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 10, marginLeft: 'auto', flexWrap: 'wrap' }}>
              <div className="screener-search">
                <Icon name="search" size={16} />
                <input placeholder="Search stocks…" value={q} onChange={(e) => setQ(e.target.value)} />
              </div>
              <select className="select" value={sortKey} onChange={(e) => setSortKey(e.target.value)}>
                {SORT_OPTS.map((o) => <option key={o.key} value={o.key}>Sort: {o.label}</option>)}
              </select>
            </div>
          </div>
          <ScreenerResults rows={rows} onOpenStock={onOpenStock} sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} />
        </>
      )}
    </div>
  );
}
Object.assign(window, { ScreenerScreen });
