// edit-modes.jsx — common "enter edit mode → batch 收藏 / 加入提醒" patterns
// for the screener result list. Five mainstream styles, each a full phone screen.

const { useState: eS } = React;

// ── sample screener result rows ──────────────────────────────────
const STOCKS = [
  { sym: '2330', name: '台積電',     price: '1,045', chg: +1.8 },
  { sym: '2454', name: '聯發科',     price: '1,280', chg: +2.4 },
  { sym: '2317', name: '鴻海',       price: '208.5', chg: -0.7 },
  { sym: '3034', name: '聯詠',       price: '498.0', chg: +3.1 },
  { sym: '2308', name: '台達電',     price: '415.5', chg: -1.2 },
  { sym: '3008', name: '大立光',     price: '2,615', chg: +0.5 },
  { sym: '2382', name: '廣達',       price: '312.0', chg: +4.2 },
  { sym: '1301', name: '台塑',       price: '46.85', chg: -0.3 },
];

// star glyph (no star in the shared Icon set)
function Star({ filled, color, size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? color : 'none'} stroke={color} strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3.2l2.6 5.27 5.82.85-4.21 4.1.99 5.79L12 16.98l-5.2 2.73.99-5.79-4.21-4.1 5.82-.85z"/>
    </svg>
  );
}

const T = () => window.flutterTokens;
const tickerBlue = 'oklch(0.42 0.10 245)';

// shared status-bar gap + screen header
function ScreenHead({ left, title, right, dark }) {
  const t = T();
  return (
    <div style={{
      padding: '56px 8px 12px', display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0,
      background: dark ? t.ink : t.surface, borderBottom: `1px solid ${dark ? 'transparent' : t.hairline}`,
      transition: 'background 180ms ease',
    }}>
      <div style={{ width: 76, display: 'flex', justifyContent: 'flex-start' }}>{left}</div>
      <div style={{ flex: 1, textAlign: 'center', fontSize: 16, fontWeight: 700, color: dark ? t.bg : t.ink, letterSpacing: -0.3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
      <div style={{ width: 76, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>{right}</div>
    </div>
  );
}

function Ticker({ sym }) {
  const t = T();
  return (
    <div style={{
      width: 40, height: 40, borderRadius: 11, flexShrink: 0, background: t.surfaceAlt,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: '"Plus Jakarta Sans", monospace', fontSize: 13, fontWeight: 700, color: tickerBlue, letterSpacing: -0.3,
    }}>{sym}</div>
  );
}

function PriceCell({ s }) {
  const t = T();
  const up = s.chg >= 0;
  return (
    <div style={{ textAlign: 'right', flexShrink: 0 }}>
      <div style={{ fontFamily: '"Plus Jakarta Sans", monospace', fontVariantNumeric: 'tabular-nums', fontSize: 14.5, fontWeight: 700, color: t.ink }}>{s.price}</div>
      <div style={{ fontFamily: '"Plus Jakarta Sans", monospace', fontVariantNumeric: 'tabular-nums', fontSize: 12, fontWeight: 600, color: up ? t.up : t.down, marginTop: 1 }}>{up ? '+' : ''}{s.chg.toFixed(1)}%</div>
    </div>
  );
}

function NameCell({ s }) {
  const t = T();
  return (
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 15, fontWeight: 700, color: t.ink, letterSpacing: -0.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
      <div style={{ fontSize: 11.5, color: t.ink3, fontFamily: '"Plus Jakarta Sans", monospace', marginTop: 1 }}>{s.sym}.TW</div>
    </div>
  );
}

function Checkbox({ on }) {
  const t = T();
  return (
    <span style={{
      width: 22, height: 22, borderRadius: 11, flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      border: `2px solid ${on ? t.ink : t.ink3}`, background: on ? t.ink : 'transparent', transition: 'all 140ms ease',
    }}>{on && <window.Icon name="check" size={13} color={t.bg}/>}</span>
  );
}

// segmented count + label pill used in toolbars
function ActBtn({ icon, label, onClick, disabled, primary }) {
  const t = T();
  return (
    <button onClick={onClick} disabled={disabled} style={{
      flex: 1, display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3,
      background: 'transparent', border: 'none', cursor: disabled ? 'default' : 'pointer', fontFamily: 'inherit',
      padding: '4px 0', opacity: disabled ? 0.4 : 1,
    }}>
      {icon}
      <span style={{ fontSize: 11, fontWeight: 600, color: t.ink2 }}>{label}</span>
    </button>
  );
}

// ════════════════════════════════════════════════════════════════
// A · iOS 編輯模式：左側勾選 + 底部工具列
// ════════════════════════════════════════════════════════════════
function PatternEditBar() {
  const t = T();
  const [on, setOn] = eS(true);
  const [sel, setSel] = eS(() => new Set(['2454', '3034', '2382']));
  const toggle = (s) => setSel(p => { const n = new Set(p); n.has(s) ? n.delete(s) : n.add(s); return n; });
  const n = sel.size;
  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column' }}>
      <ScreenHead
        title={on ? `已選 ${n} 項` : '台積電供應鏈'}
        left={<button onClick={() => setOn(false)} style={navTxt(t, !on)}>{''}</button>}
        right={<button onClick={() => setOn(v => !v)} style={navTxt(t, true)}>{on ? '完成' : '編輯'}</button>}/>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {STOCKS.map((s, i) => (
          <button key={s.sym} onClick={() => on && toggle(s.sym)} style={{
            width: '100%', textAlign: 'left', background: on && sel.has(s.sym) ? t.surfaceAlt : 'transparent', border: 'none',
            cursor: on ? 'pointer' : 'default', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 12,
            padding: '11px 16px', borderBottom: `1px solid ${t.hairline}`,
          }}>
            {on && <Checkbox on={sel.has(s.sym)}/>}
            <Ticker sym={s.sym}/>
            <NameCell s={s}/>
            <PriceCell s={s}/>
          </button>
        ))}
      </div>
      {on && (
        <div style={{ flexShrink: 0, borderTop: `1px solid ${t.hairline}`, background: t.surface, padding: '8px 12px 24px', display: 'flex', gap: 4 }}>
          <ActBtn disabled={!n} icon={<Star filled color={n ? t.butterDk : t.ink3} size={21}/>} label="收藏"/>
          <ActBtn disabled={!n} icon={<window.Icon name="bell" size={21} color={n ? t.ink : t.ink3}/>} label="加入提醒"/>
          <ActBtn disabled={!n} icon={<window.Icon name="trash" size={21} color={n ? t.coralDk : t.ink3}/>} label="移除"/>
        </div>
      )}
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// B · Android 情境頂欄 (CAB)：深色頂欄 + 右上動作圖示
// ════════════════════════════════════════════════════════════════
function PatternCAB() {
  const t = T();
  const [sel, setSel] = eS(() => new Set(['2330', '2317']));
  const toggle = (s) => setSel(p => { const n = new Set(p); n.has(s) ? n.delete(s) : n.add(s); return n; });
  const active = sel.size > 0;
  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column' }}>
      <ScreenHead dark={active}
        title={active ? `${sel.size}` : '台積電供應鏈'}
        left={active
          ? <button onClick={() => setSel(new Set())} style={{ ...iconRound(t, true) }}><window.Icon name="x" size={19} color={t.bg}/></button>
          : null}
        right={active
          ? <div style={{ display: 'flex', gap: 2 }}>
              <button style={iconRound(t, true)}><Star filled={false} color={t.bg} size={20}/></button>
              <button style={iconRound(t, true)}><window.Icon name="bell" size={20} color={t.bg}/></button>
            </div>
          : <button style={iconRound(t)}><window.Icon name="more" size={18} color={t.ink}/></button>}/>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {STOCKS.map((s) => {
          const chk = sel.has(s.sym);
          return (
            <button key={s.sym} onClick={() => toggle(s.sym)} style={{
              width: '100%', textAlign: 'left', background: chk ? t.surfaceAlt : 'transparent', border: 'none',
              cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 12,
              padding: '11px 16px', borderBottom: `1px solid ${t.hairline}`,
            }}>
              <div style={{ position: 'relative' }}>
                <Ticker sym={s.sym}/>
                {chk && <span style={{ position: 'absolute', inset: 0, borderRadius: 11, background: t.ink, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon name="check" size={18} color={t.bg}/></span>}
              </div>
              <NameCell s={s}/>
              <PriceCell s={s}/>
            </button>
          );
        })}
      </div>
      <div style={{ flexShrink: 0, padding: '10px 16px 22px', textAlign: 'center', fontSize: 11.5, color: t.ink3 }}>長按任一列進入多選</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// C · 逐列滑動操作 (swipe actions)：免進模式，單列快捷
// ════════════════════════════════════════════════════════════════
function SwipeRow({ s, openId, setOpenId }) {
  const t = T();
  const ACT = 78, MAX = ACT * 2;
  const drag = React.useRef(null);
  const [dx, setDx] = eS(0);
  const open = openId === s.sym;
  React.useEffect(() => { if (!drag.current) setDx(open ? -MAX : 0); }, [open]);
  const down = (e) => { e.currentTarget.setPointerCapture(e.pointerId); drag.current = { x: e.clientX, base: open ? -MAX : 0 }; };
  const move = (e) => { if (!drag.current) return; const d = e.clientX - drag.current.x; setDx(Math.max(-MAX - 16, Math.min(0, drag.current.base + d))); };
  const up = () => { if (!drag.current) return; const o = dx < -MAX / 2; drag.current = null; setDx(o ? -MAX : 0); setOpenId(o ? s.sym : null); };
  return (
    <div style={{ position: 'relative', overflow: 'hidden', borderBottom: `1px solid ${t.hairline}` }}>
      <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, display: 'flex' }}>
        <div style={{ width: ACT, background: t.butterDk, color: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
          <Star filled color="#fff" size={20}/><span style={{ fontSize: 11, fontWeight: 700 }}>收藏</span>
        </div>
        <div style={{ width: ACT, background: tickerBlue, color: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
          <window.Icon name="bell" size={20} color="#fff"/><span style={{ fontSize: 11, fontWeight: 700 }}>提醒</span>
        </div>
      </div>
      <div onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up}
        style={{ position: 'relative', background: t.bg, transform: `translateX(${dx}px)`, transition: drag.current ? 'none' : 'transform 220ms cubic-bezier(.2,.7,.2,1)', touchAction: 'pan-y',
          display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px' }}>
        <Ticker sym={s.sym}/><NameCell s={s}/><PriceCell s={s}/>
      </div>
    </div>
  );
}
function PatternSwipe() {
  const t = T();
  const [openId, setOpenId] = eS('2454');
  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column' }}>
      <ScreenHead title="台積電供應鏈" right={<button style={iconRound(t)}><window.Icon name="more" size={18} color={t.ink}/></button>}/>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {STOCKS.map((s) => <SwipeRow key={s.sym} s={s} openId={openId} setOpenId={setOpenId}/>)}
      </div>
      <div style={{ flexShrink: 0, padding: '10px 16px 22px', textAlign: 'center', fontSize: 11.5, color: t.ink3 }}>向左滑動單列 → 收藏 / 提醒</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// D · 逐列常駐快捷鈕：每列尾端固定 star + bell
// ════════════════════════════════════════════════════════════════
function PatternInline() {
  const t = T();
  const [favs, setFavs] = eS(() => new Set(['2330', '3034']));
  const [alerts, setAlerts] = eS(() => new Set(['2454']));
  const tf = (set, setSet, s) => setSet(p => { const n = new Set(p); n.has(s) ? n.delete(s) : n.add(s); return n; });
  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column' }}>
      <ScreenHead title="台積電供應鏈" right={<button style={iconRound(t)}><window.Icon name="more" size={18} color={t.ink}/></button>}/>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {STOCKS.map((s) => {
          const fav = favs.has(s.sym), al = alerts.has(s.sym);
          return (
            <div key={s.sym} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px 11px 16px', borderBottom: `1px solid ${t.hairline}` }}>
              <Ticker sym={s.sym}/>
              <NameCell s={s}/>
              <PriceCell s={s}/>
              <div style={{ display: 'flex', gap: 2, flexShrink: 0, marginLeft: 4 }}>
                <button onClick={() => tf(favs, setFavs, s.sym)} style={quickBtn(t, fav, t.butterDk)}><Star filled={fav} color={fav ? t.butterDk : t.ink3} size={19}/></button>
                <button onClick={() => tf(alerts, setAlerts, s.sym)} style={quickBtn(t, al, tickerBlue)}><window.Icon name="bell" size={19} color={al ? tickerBlue : t.ink3}/></button>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ flexShrink: 0, padding: '10px 16px 22px', textAlign: 'center', fontSize: 11.5, color: t.ink3 }}>每列尾端常駐 收藏 / 提醒</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════
// E · 長按多選 + 底部浮動膠囊列
// ════════════════════════════════════════════════════════════════
function PatternFloatingPill() {
  const t = T();
  const [sel, setSel] = eS(() => new Set(['2330', '2454', '2382', '3034']));
  const toggle = (s) => setSel(p => { const n = new Set(p); n.has(s) ? n.delete(s) : n.add(s); return n; });
  const n = sel.size;
  return (
    <div style={{ height: '100%', background: t.bg, display: 'flex', flexDirection: 'column', position: 'relative' }}>
      <ScreenHead title="台積電供應鏈" right={<button style={iconRound(t)}><window.Icon name="more" size={18} color={t.ink}/></button>}/>
      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 88 }}>
        {STOCKS.map((s) => {
          const chk = sel.has(s.sym);
          return (
            <button key={s.sym} onClick={() => toggle(s.sym)} style={{
              width: '100%', textAlign: 'left', background: chk ? t.surfaceAlt : 'transparent', border: 'none',
              cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 12,
              padding: '11px 16px', borderBottom: `1px solid ${t.hairline}`,
            }}>
              <Checkbox on={chk}/>
              <Ticker sym={s.sym}/>
              <NameCell s={s}/>
              <PriceCell s={s}/>
            </button>
          );
        })}
      </div>
      {/* floating pill */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 22, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
        <div style={{
          pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 4,
          background: t.ink, borderRadius: 999, padding: '7px 8px 7px 16px',
          boxShadow: '0 12px 30px -8px rgba(31,27,22,0.5)',
        }}>
          <span style={{ fontSize: 13.5, fontWeight: 700, color: t.bg, marginRight: 6 }}>已選 {n}</span>
          <button style={pillBtn()}><Star filled color={t.bg} size={20}/></button>
          <button style={pillBtn()}><window.Icon name="bell" size={20} color={t.bg}/></button>
          <button style={pillBtn()}><window.Icon name="x" size={19} color={t.bg}/></button>
        </div>
      </div>
    </div>
  );
}

// ── shared style helpers ─────────────────────────────────────────
function navTxt(t, strong) { return { background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 15, fontWeight: strong ? 700 : 500, color: t.ink, padding: '6px 4px', minWidth: 20 }; }
function iconRound(t, dark) { return { width: 34, height: 34, borderRadius: 17, background: dark ? 'rgba(255,255,255,0.14)' : 'transparent', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }; }
function quickBtn(t, on, c) { return { width: 36, height: 36, borderRadius: 10, background: on ? t.surfaceAlt : 'transparent', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }; }
function pillBtn() { return { width: 38, height: 38, borderRadius: 19, background: 'rgba(255,255,255,0.14)', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }; }

Object.assign(window, { PatternEditBar, PatternCAB, PatternSwipe, PatternInline, PatternFloatingPill });
// shared bits reused by edit-pill-variants.jsx
Object.assign(window, {
  EM_STOCKS: STOCKS, EMStar: Star, EMTicker: Ticker, EMNameCell: NameCell,
  EMPriceCell: PriceCell, EMCheckbox: Checkbox, EMScreenHead: ScreenHead, emIconRound: iconRound,
});
