// merged-filter-demo.jsx — funnel + editor merged into ONE page.
// Each condition row shows its value AND the remaining-count (the funnel's
// narrowing effect) inline; tap a row to edit, ✕ to remove, origin row on top,
// 查看 N 筆 CTA at the bottom. Reuses CenterDialogConfig + CatalogScreen.

const { useState: mS } = React;
const MT = () => window.flutterTokens;

// applied conditions (real filter ids) with display value + remaining count.
// Exchange (交易所) is itself a normal criterion — the origin is the database/universe.
const SEED = [
  { key: 'a0', filterId: 'board',        label: '交易所',     value: '包含 上市、上櫃',       n: 1750 },
  { key: 'a1', filterId: 'sector',       label: '產業',       value: '包含 半導體、電子零組件', n: 420 },
  { key: 'a2', filterId: 'price',        label: '股價',       value: '20 ~ 80 元',          n: 180 },
  { key: 'a3', filterId: 'volume',       label: '成交量',     value: '≥ 5,000 張',          n: 64 },
  { key: 'a4', filterId: 'foreign_flow', label: '外資買賣超', value: '連 5 日買超 ≥ 3,000', n: 23 },
];
const ORIGIN = { label: '全市場', value: '', n: 2000 };
const GCOL = '84px minmax(0, 1fr) 52px 22px';
const GGAP = 10;
const mFmt = (x) => x.toLocaleString('en-US');

function MergedFilterPage() {
  const t = MT();
  const [applied, setApplied] = mS(SEED);
  const [editKey, setEditKey] = mS(null);
  const [adding, setAdding] = mS(false);

  const editItem = applied.find(x => x.key === editKey) || null;
  const editFilter = editItem ? window.FILTER_BY_ID[editItem.filterId] : null;
  const resultN = applied.length ? applied[applied.length - 1].n : ORIGIN.n;

  if (adding) {
    return (
      <window.CatalogScreen accordion={true} mode="dialog"
        onBack={() => setAdding(false)}
        onAddFilter={(filterId) => {
          const f = window.FILTER_BY_ID[filterId];
          setApplied(a => [...a, { key: 'k' + Date.now(), filterId, label: f.label, value: '已設定', n: Math.max(1, Math.round((a.length ? a[a.length-1].n : 6500) * 0.7)) }]);
          setAdding(false);
        }}/>
    );
  }

  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column', position: 'relative' }}>
      {/* header */}
      <div style={{ background: t.surface, borderBottom: `1px solid ${t.hairline}`, flexShrink: 0 }}>
        <div style={{ padding: '56px 12px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <button style={{ width: 32, flexShrink: 0, background: 'none', border: 'none', cursor: 'pointer', padding: 6, color: t.ink, display: 'flex', marginLeft: -2 }}>
            <window.Icon name="back" size={22}/>
          </button>
          <div style={{ flex: 1, minWidth: 0, textAlign: 'center', fontFamily: '"Plus Jakarta Sans","Noto Sans TC",sans-serif', fontSize: 17, fontWeight: 700, color: t.ink, letterSpacing: -0.3 }}>篩選條件 <span style={{ fontFamily: '"Plus Jakarta Sans",monospace', color: t.ink3 }}>({applied.length})</span></div>
          <div style={{ width: 32, flexShrink: 0 }}/>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {/* column header — Criteria | Values | Remaining */}
        <div style={{ display: 'grid', gridTemplateColumns: GCOL, gap: GGAP, alignItems: 'center', padding: '9px 16px', borderBottom: `1px solid ${t.hairline}` }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: t.ink3, letterSpacing: 0.3 }}>名稱</span>
          <span style={{ fontSize: 11, fontWeight: 700, color: t.ink3, letterSpacing: 0.3, textAlign: 'left' }}>設定</span>
          <span style={{ fontSize: 11, fontWeight: 700, color: t.ink3, letterSpacing: 0.3, textAlign: 'right' }}>剩餘</span>
          <span/>
        </div>

        {/* origin row — read-only: the database / universe being screened */}
        <div style={{ display: 'grid', gridTemplateColumns: GCOL, gap: GGAP, alignItems: 'center', padding: '12px 16px', borderBottom: `1px solid ${t.hairline}` }}>
          <span style={{ fontSize: 14.5, fontWeight: 700, color: t.ink, letterSpacing: -0.2 }}>{ORIGIN.label}</span>
          <span style={{ fontSize: 12.5, color: 'oklch(0.50 0.12 245)', fontWeight: 600, textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ORIGIN.value}</span>
          <span style={{ fontFamily: '"Plus Jakarta Sans",monospace', fontVariantNumeric: 'tabular-nums', fontSize: 14.5, fontWeight: 700, color: t.ink, textAlign: 'right' }}>{mFmt(ORIGIN.n)}</span>
          <span/>
        </div>

        {/* condition rows — editable AND show remaining count (the funnel) */}
        {applied.map((item, i) => {
          const prev = i === 0 ? ORIGIN.n : applied[i - 1].n;
          const cut = prev - item.n;
          return (
            <div key={item.key} onClick={() => setEditKey(item.key)} style={{ display: 'grid', gridTemplateColumns: GCOL, gap: GGAP, alignItems: 'center', padding: '13px 16px', borderBottom: `1px solid ${t.hairline}`, cursor: 'pointer' }}>
              <span style={{ fontSize: 14.5, fontWeight: 700, color: 'oklch(0.50 0.12 245)', letterSpacing: -0.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.label}</span>
              <span style={{ fontSize: 12.5, color: t.ink2, fontWeight: 500, textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.value}</span>
              <span style={{ textAlign: 'right' }}>
                <span style={{ fontFamily: '"Plus Jakarta Sans",monospace', fontVariantNumeric: 'tabular-nums', fontSize: 14.5, fontWeight: 700, color: t.ink }}>{mFmt(item.n)}</span>
              </span>
              <button onClick={(e) => { e.stopPropagation(); setApplied(a => a.filter(x => x.key !== item.key)); }} title="移除" style={{ width: 26, height: 26, borderRadius: 999, background: 'transparent', border: 'none', cursor: 'pointer', color: t.ink3, display: 'flex', alignItems: 'center', justifyContent: 'center', justifySelf: 'end' }}>
                <window.Icon name="x" size={15} color={t.ink3}/>
              </button>
            </div>
          );
        })}
        <div style={{ height: 12 }}/>
      </div>

      {/* footer */}
      <div style={{ flexShrink: 0, borderTop: `1px solid ${t.hairline}`, background: t.surface, padding: '12px 16px 22px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <button onClick={() => setAdding(true)} style={{ width: '100%', background: t.surfaceAlt, color: t.ink, border: `1px solid ${t.hairline}`, borderRadius: 12, padding: '14px', fontSize: 14.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>新增條件</button>
        <button style={{ width: '100%', background: t.ink, color: t.bg, border: 'none', borderRadius: 12, padding: '14px', fontSize: 14.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>查看 <span style={{ fontFamily: '"Plus Jakarta Sans",monospace' }}>{mFmt(resultN)}</span> 筆結果</button>
      </div>

      {editFilter && (
        <window.CenterDialogConfig filter={editFilter} initial={window.defaultsFor(editFilter)} addLabel="完成"
          onClose={() => setEditKey(null)}
          onAdd={() => setEditKey(null)}/>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <div style={{ minHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, boxSizing: 'border-box' }}>
    <window.IOSDevice width={402} height={874}><MergedFilterPage/></window.IOSDevice>
  </div>
);
