// MChatCallsPager — swipeable Chat ⇆ Calls pager.
// The Chat list and Calls list live as two panes on one horizontal track.
// A segmented "Chat / Calls" control at the top reflects + drives the active
// pane, and a horizontal drag (touch or mouse) swipes between them with the
// usual edge-resistance + flick-to-commit feel. Each pane keeps its own
// vertical scroll; horizontal intent is detected before we hijack the drag so
// vertical scrolling stays smooth.

function MChatCallsPager({ onOpenChat, onAdd, onCall, onIncomingDemo, tab: tabProp, onTabChange, initialTab = 'chat' }) {
  const TABS = ['chat', 'calls'];
  const [tabState, setTabState] = React.useState(initialTab);
  const tab = tabProp != null ? tabProp : tabState;
  const setTab = (t) => { setTabState(t); onTabChange && onTabChange(t); };
  const idx = TABS.indexOf(tab);

  const viewportRef = React.useRef(null);
  const [drag, setDrag] = React.useState(0);
  const [dragging, setDragging] = React.useState(false);
  const start = React.useRef(null);   // {x, y}
  const lock = React.useRef(null);    // 'h' | 'v' | null

  const unread = 5;   // total unread chats (sum of badges)
  const missed = 2;   // missed calls

  const onDown = (e) => {
    start.current = { x: e.clientX, y: e.clientY };
    lock.current = null;
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch {}
  };
  const onMove = (e) => {
    if (!start.current) return;
    let dx = e.clientX - start.current.x;
    const dy = e.clientY - start.current.y;
    if (lock.current === null) {
      if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return;
      lock.current = Math.abs(dx) > Math.abs(dy) ? 'h' : 'v';
      if (lock.current === 'h') setDragging(true);
    }
    if (lock.current !== 'h') return;
    // edge resistance — can't drag past the first/last pane
    if ((idx === 0 && dx > 0) || (idx === TABS.length - 1 && dx < 0)) dx *= 0.32;
    setDrag(dx);
  };
  const onUp = () => {
    if (!start.current) return;
    const w = viewportRef.current ? viewportRef.current.offsetWidth : 320;
    const threshold = w * 0.2;
    if (lock.current === 'h') {
      if (drag < -threshold && idx < TABS.length - 1) setTab(TABS[idx + 1]);
      else if (drag > threshold && idx > 0) setTab(TABS[idx - 1]);
    }
    start.current = null; lock.current = null;
    setDragging(false); setDrag(0);
  };

  const trackTransform = `translateX(calc(${-idx * 50}% + ${drag}px))`;

  const Tab = ({ id, label, icon, badge }) => {
    const active = tab === id;
    return (
      <button onClick={() => setTab(id)} style={{
        flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
        padding: '8px 0', borderRadius: 9, position: 'relative', zIndex: 1,
        background: 'transparent', border: 0, cursor: 'pointer', fontFamily: 'inherit',
        color: active ? M_FG : M_FG_MUTED, transition: 'color 200ms',
      }}>
        <span style={{ display: 'grid', placeItems: 'center', color: active ? M_ACCENT_B : M_FG_MUTED, transition: 'color 200ms' }}>{icon}</span>
        <span style={{ fontSize: 13.5, fontWeight: active ? 600 : 500, letterSpacing: '-0.01em' }}>{label}</span>
        {badge > 0 && (
          <span style={{
            minWidth: 17, height: 17, padding: '0 5px', borderRadius: 9,
            background: id === 'calls' ? '#F87171' : M_ACCENT_B, color: '#0B0C0F',
            fontSize: 9.5, fontWeight: 700, display: 'grid', placeItems: 'center',
            fontFamily: 'JetBrains Mono, monospace',
          }}>{badge}</span>
        )}
      </button>
    );
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: M_BG }}>
      {/* Unified header */}
      <div style={{ padding: '18px 16px 10px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ fontSize: 24, fontWeight: 700, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.025em', color: M_FG }}>
            {tab === 'chat' ? 'Chat' : 'Calls'}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button aria-label="Search" style={{ width: 36, height: 36, borderRadius: 10, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, color: M_FG, display: 'grid', placeItems: 'center', cursor: 'pointer' }}>{MIc.search({ s: 16 })}</button>
            <button
              aria-label={tab === 'chat' ? 'New chat' : 'New call'}
              onClick={() => tab === 'chat' ? (onAdd && onAdd()) : (onCall && onCall(null, 'audio'))}
              style={{ width: 36, height: 36, borderRadius: 10, background: 'linear-gradient(135deg, ' + M_ACCENT + ', ' + M_ACCENT_B + ')', border: 0, color: '#0B0C0F', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
              {MIc.plus({ s: 16 })}
            </button>
          </div>
        </div>

        {/* Segmented control with sliding indicator */}
        <div style={{ position: 'relative', display: 'flex', padding: 4, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 13 }}>
          <div style={{
            position: 'absolute', top: 4, bottom: 4, left: 4, width: 'calc(50% - 4px)',
            borderRadius: 9, background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
            transform: `translateX(${idx * 100}%)`,
            transition: dragging ? 'none' : 'transform 280ms cubic-bezier(0.2,0.85,0.3,1)',
          }}/>
          <Tab id="chat"  label="Chat"  icon={MIc.chat({ s: 16 })}  badge={unread}/>
          <Tab id="calls" label="Calls" icon={MIc.calls({ s: 16 })} badge={missed}/>
        </div>
      </div>

      {/* Swipeable viewport */}
      <div
        ref={viewportRef}
        onPointerDown={onDown}
        onPointerMove={onMove}
        onPointerUp={onUp}
        onPointerCancel={onUp}
        style={{ flex: 1, position: 'relative', overflow: 'hidden', touchAction: 'pan-y' }}
      >
        <div style={{
          display: 'flex', width: '200%', height: '100%',
          transform: trackTransform,
          transition: dragging ? 'none' : 'transform 320ms cubic-bezier(0.2,0.85,0.3,1)',
        }}>
          <div style={{ width: '50%', height: '100%', overflow: 'hidden' }}>
            <MScreenChatList headerless onOpen={onOpenChat} onAdd={onAdd}/>
          </div>
          <div style={{ width: '50%', height: '100%', overflow: 'hidden' }}>
            <MScreenCalls headerless onCall={onCall} onIncomingDemo={onIncomingDemo}/>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MChatCallsPager });
