// Tablet — All Tabs page (replaces older TScreenTabs)
// Three modes only: Tabs / Private / Groups. Larger animated selector.

function TScreenTabs({ landscape = true, onOpenPrivate, onOpenGroup, onNewGroup }) {
  const [mode, setMode] = React.useState('tabs');

  const tabs = [
    { title: 'Linear — Inbox',            fav: 'L', bg: '#5E6AD2',          url: 'linear.app/ajna-inc/inbox',     hint: 'Active · 18m' },
    { title: 'Figma — Ajna iPad explor.', fav: 'F', bg: '#000',             url: 'figma.com/file/ajna-ipad',     hint: 'Edited 2h ago' },
    { title: 'GitHub · ajna-inc/browser', fav: 'G', bg: '#24292F',          url: 'github.com/ajna-inc/browser',  hint: 'PR #284 · 3 reviews' },
    { title: 'Notion · P2P Sync RFC',     fav: 'N', bg: '#FFF', c: '#000',  url: 'notion.so/p2p-sync',           hint: '5 comments' },
    { title: 'HN — News',                 fav: 'Y', bg: '#FF6600',          url: 'news.ycombinator.com',         hint: 'Updated' },
    { title: 'arXiv · DIDComm v2',        fav: 'A', bg: '#B31B1B',          url: 'arxiv.org/abs/2402.…',         hint: 'PDF' },
  ];
  const privateTabs = [
    { title: 'DuckDuckGo · search',     fav: 'D', bg: '#7C3AED',         url: 'duckduckgo.com/?q=DIDComm',  hint: 'No history' },
    { title: 'Wikipedia · Ajna chakra', fav: 'W', bg: '#000',            url: 'en.wikipedia.org/wiki/…',     hint: 'Reading' },
    { title: 'Airline · MUC → SFO',     fav: 'A', bg: '#0EA5E9',         url: 'lh.com/booking',              hint: 'Private booking' },
  ];

  const modes = [
    { id: 'tabs',    label: 'Tabs',    icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="4" width="13" height="13" rx="2"/><rect x="7" y="7" width="13" height="13" rx="2"/></svg>, count: tabs.length },
    { id: 'private', label: 'Private', icon: <IcMask s={14}/>, count: privateTabs.length, accent: '#C4B5FD' },
    { id: 'groups',  label: 'Groups',  icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="8" height="7" rx="1.5"/><rect x="13" y="4" width="8" height="7" rx="1.5"/><rect x="3" y="13" width="8" height="7" rx="1.5"/><rect x="13" y="13" width="8" height="7" rx="1.5"/></svg>, count: TAB_GROUPS.length },
  ];

  return (
    <div style={{ flex: 1, overflow: 'auto', padding: landscape ? '24px 40px 80px' : '20px 24px 80px' }}>
      <TTabsModeSwitcher modes={modes} mode={mode} onPick={(id) => setMode(id)}/>

      {mode === 'tabs' && <TTabsGrid tabs={tabs} landscape={landscape}/>}
      {mode === 'private' && <TPrivateTabsInline tabs={privateTabs} landscape={landscape} onOpenPrivate={onOpenPrivate}/>}
      {mode === 'groups' && <TGroupsInline landscape={landscape} onOpen={onOpenGroup} onNewGroup={onNewGroup}/>}
    </div>
  );
}

// Larger segmented selector with animated indicator
function TTabsModeSwitcher({ modes, mode, onPick }) {
  const itemRefs = React.useRef({});
  const containerRef = React.useRef(null);
  const [indicator, setIndicator] = React.useState({ left: 0, width: 0, ready: false });

  React.useLayoutEffect(() => {
    const el = itemRefs.current[mode];
    const c  = containerRef.current;
    if (!el || !c) return;
    const er = el.getBoundingClientRect();
    const cr = c.getBoundingClientRect();
    setIndicator({ left: er.left - cr.left, width: er.width, ready: true });
  }, [mode]);

  const activeAccent = modes.find(m => m.id === mode)?.accent;

  return (
    <div ref={containerRef} style={{
      position: 'relative',
      display: 'inline-flex', alignItems: 'center',
      padding: 4, background: M_SURFACE, border: '1px solid ' + M_BORDER,
      borderRadius: 14, marginBottom: 22,
      boxShadow: '0 4px 16px -8px rgba(0,0,0,0.4)',
    }}>
      <div style={{
        position: 'absolute',
        top: 4, bottom: 4, left: indicator.left, width: indicator.width,
        background: activeAccent ? 'rgba(167,139,250,0.16)' : M_BG,
        border: '1px solid ' + (activeAccent ? 'rgba(167,139,250,0.34)' : M_BORDER_SOFT),
        borderRadius: 10,
        transition: indicator.ready ? 'left 280ms cubic-bezier(0.2,0.85,0.3,1), width 280ms cubic-bezier(0.2,0.85,0.3,1), background 200ms, border 200ms' : 'none',
        pointerEvents: 'none',
        boxShadow: '0 2px 6px rgba(0,0,0,0.25)',
      }}/>
      {modes.map(m => {
        const active = m.id === mode;
        return (
          <button
            key={m.id}
            ref={el => itemRefs.current[m.id] = el}
            onClick={() => onPick(m.id)}
            style={{
              position: 'relative', zIndex: 1,
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '9px 16px', borderRadius: 10,
              background: 'transparent', border: 0,
              color: active ? (m.accent || M_FG) : M_FG_MUTED,
              cursor: 'pointer', fontFamily: 'inherit',
              fontSize: 13, fontWeight: active ? 600 : 500,
              letterSpacing: '-0.005em',
              transition: 'color 200ms',
            }}
          >
            <span style={{ display: 'grid', placeItems: 'center', opacity: active ? 1 : 0.7 }}>{m.icon}</span>
            {m.label}
            <span style={{
              fontSize: 10.5, fontFamily: 'JetBrains Mono, monospace',
              padding: '1px 6px', borderRadius: 5,
              background: active
                ? (m.accent ? 'rgba(167,139,250,0.16)' : 'var(--m-tint)')
                : 'var(--m-tint)',
              color: active ? (m.accent || M_FG_MUTED) : M_FG_DIM,
              transition: 'background 200ms, color 200ms',
            }}>{m.count}</span>
          </button>
        );
      })}
    </div>
  );
}

function TTabsGrid({ tabs, landscape }) {
  // anchor + tab for the context menu; null when closed
  const [menu, setMenu] = React.useState(null);
  // 'move-dialog' | 'new-group' | null
  const [dialog, setDialog] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const [selectedTab, setSelectedTab] = React.useState(null);

  const openMenu = (e, t) => {
    e.preventDefault();
    setSelectedTab(t);
    setMenu({ rect: e.currentTarget.getBoundingClientRect(), tab: t });
  };
  const handleAction = (action, payload) => {
    if (action === 'move') {
      const g = TAB_GROUPS.find(x => x.id === payload);
      setToast('Moved to "' + (g?.name || 'group') + '"');
    } else if (action === 'remove') {
      setToast('Removed from group');
    } else if (action === 'new-group') {
      setDialog('new-group');
    } else if (action === 'close') {
      setToast('Tab closed');
    } else if (action === 'copy') {
      setToast('URL copied');
    } else if (action === 'open-private') {
      setToast('Opened in private');
    }
  };

  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ fontSize: 22, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em', color: M_FG }}>
          All tabs
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{ ...tIconBtn(false), width: 'auto', padding: '0 12px', height: 32, gap: 6, display: 'inline-flex', fontSize: 12, fontFamily: 'inherit' }}>
            <span style={{ display: 'grid', placeItems: 'center' }}>{MIc.plus({ s: 14 })}</span> New tab
          </button>
          <button style={{ ...tIconBtn(false), width: 'auto', padding: '0 12px', height: 32, fontSize: 12, fontFamily: 'inherit' }}>Close all</button>
        </div>
      </div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: landscape ? 'repeat(3, 1fr)' : 'repeat(2, 1fr)',
        gap: 16,
      }}>
        {tabs.map((t, i) => (
          <div
            key={i}
            onContextMenu={(e) => openMenu(e, t)}
            style={{
              aspectRatio: landscape ? '4/3' : '3/4',
              background: M_SURFACE, border: '1px solid ' + M_BORDER,
              borderRadius: 14, overflow: 'hidden', display: 'flex', flexDirection: 'column',
              cursor: 'pointer', position: 'relative',
            }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderBottom: '1px solid ' + M_BORDER_SOFT }}>
              <MTile size={18} bg={t.bg} color={t.c||'#fff'} label={t.fav} radius={4}/>
              <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>{t.url}</div>
              <button
                onClick={(e) => { e.stopPropagation(); openMenu(e, t); }}
                style={{ background: 'transparent', border: 0, color: M_FG_DIM, padding: 2, display: 'grid', placeItems: 'center', cursor: 'pointer', borderRadius: 4 }}
                aria-label="Tab actions"
              >{MIc.more({ s: 14 })}</button>
              <span style={{ color: M_FG_DIM, opacity: 0.6 }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
              </span>
            </div>
            <div style={{ flex: 1, padding: 16, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 14, fontWeight: 500, color: M_FG, lineHeight: 1.3 }}>{t.title}</div>
              <div style={{ fontSize: 11, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace' }}>{t.hint}</div>
            </div>
          </div>
        ))}
      </div>

      {menu && (
        <TTabContextMenu
          anchorRect={menu.rect}
          tab={menu.tab}
          currentGroupId={null}
          onClose={() => setMenu(null)}
          onMoveToGroup={() => { setMenu(null); setDialog('move-dialog'); }}
          onAction={handleAction}
        />
      )}
      {dialog === 'move-dialog' && (
        <TMoveToGroupDialog
          tab={selectedTab}
          currentGroupId={null}
          onClose={() => setDialog(null)}
          onPick={(gid) => {
            setDialog(null);
            if (gid === null) setToast('Removed from group');
            else setToast('Moved to "' + (TAB_GROUPS.find(g => g.id === gid)?.name) + '"');
          }}
          onCreateNew={() => setDialog('new-group')}
        />
      )}
      {dialog === 'new-group' && (
        <TNewGroupDialog
          onClose={() => setDialog(null)}
          onCreate={({ name }) => { setDialog(null); setToast('Created "' + name + '"'); }}
        />
      )}
      {toast && <TToast message={toast} onDone={() => setToast(null)}/>}
    </>
  );
}

function TGroupsInline({ landscape, onOpen, onNewGroup }) {
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ fontSize: 22, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em', color: M_FG }}>
          Tab groups
        </div>
        <button onClick={onNewGroup} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '7px 13px', borderRadius: 999,
          background: 'linear-gradient(135deg, ' + M_ACCENT + ', ' + M_ACCENT_B + ')',
          color: '#0B0C0F', fontSize: 12.5, fontWeight: 600,
          fontFamily: 'inherit', border: 0, cursor: 'pointer',
        }}>{MIc.plus({ s: 13 })} New group</button>
      </div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: landscape ? 'repeat(3, 1fr)' : 'repeat(2, 1fr)',
        gap: 16,
      }}>
        {TAB_GROUPS.map(g => {
          const c = GROUP_COLORS[g.color];
          return (
            <div key={g.id} onClick={() => onOpen && onOpen(g.id)} style={{
              padding: 16, background: M_SURFACE,
              border: '1px solid ' + M_BORDER, borderRadius: 14,
              cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 12,
              transition: 'border 160ms, background 160ms',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = c.border; e.currentTarget.style.background = c.bg.replace('0.14', '0.06'); }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = M_BORDER; e.currentTarget.style.background = M_SURFACE; }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 22, height: 22, borderRadius: 6, background: c.bg, border: '1.5px solid ' + c.dot, flexShrink: 0 }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.name}</div>
                  <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2, fontFamily: 'JetBrains Mono, monospace' }}>{g.tabs.length} tabs</div>
                </div>
                {g.shared && (
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    padding: '2px 7px', borderRadius: 5,
                    background: 'rgba(167,139,250,0.16)', color: '#C4B5FD',
                    fontSize: 9.5, fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: '0.06em',
                  }}>
                    {MIc.mesh({ s: 10 })} SHARED · {g.members}
                  </span>
                )}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: -8, height: 24 }}>
                {g.tabs.slice(0, 5).map((t, i) => (
                  <div key={i} style={{
                    width: 24, height: 24, borderRadius: 6, background: t.bg, color: t.c || '#fff',
                    display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700, fontFamily: 'Geist',
                    marginLeft: i === 0 ? 0 : -6, border: '2px solid ' + M_SURFACE, flexShrink: 0,
                  }}>{t.fav}</div>
                ))}
                {g.tabs.length > 5 && (
                  <div style={{
                    width: 24, height: 24, borderRadius: 6, background: M_SURFACE_2, color: M_FG_MUTED,
                    marginLeft: -6, border: '2px solid ' + M_SURFACE, display: 'grid', placeItems: 'center',
                    fontSize: 9, fontWeight: 600, fontFamily: 'JetBrains Mono, monospace',
                  }}>+{g.tabs.length - 5}</div>
                )}
              </div>
              <div style={{
                fontSize: 11.5, color: M_FG_MUTED, lineHeight: 1.4,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                paddingTop: 8, borderTop: '1px solid ' + M_BORDER_SOFT,
              }}>Latest: {g.tabs[0].title}</div>
            </div>
          );
        })}
        <div onClick={onNewGroup} style={{
          padding: 16, background: 'transparent',
          border: '1px dashed ' + M_BORDER, borderRadius: 14,
          cursor: 'pointer', display: 'grid', placeItems: 'center',
          color: M_FG_MUTED, fontSize: 13, fontFamily: 'inherit', minHeight: 140,
        }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ width: 36, height: 36, borderRadius: 18, background: M_SURFACE, color: M_FG_MUTED, display: 'grid', placeItems: 'center', margin: '0 auto 10px' }}>
              {MIc.plus({ s: 18 })}
            </div>
            <div style={{ fontWeight: 500, color: M_FG }}>New tab group</div>
            <div style={{ fontSize: 11, color: M_FG_DIM, marginTop: 4 }}>Pick a name, color, and tabs</div>
          </div>
        </div>
      </div>
    </>
  );
}

// Override the older versions (load order makes this win)
Object.assign(window, { TScreenTabs, TTabsModeSwitcher, TTabsGrid, TGroupsInline });

// ─── Private tabs grid, shown inline in the All Tabs page ───
// Violet-themed cards with the mask glyph; small info row up top reminds the
// user these are isolated, with a CTA to jump into the dedicated private window
// for a fully private browsing context.
function TPrivateTabsInline({ tabs, landscape, onOpenPrivate }) {
  return (
    <>
      {/* Header row: title + actions + isolation hint */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 26, height: 26, borderRadius: 8, background: 'rgba(167,139,250,0.16)', border: '1px solid rgba(167,139,250,0.32)', color: '#C4B5FD', display: 'grid', placeItems: 'center' }}>
            <IcMask s={14}/>
          </div>
          <div style={{ fontSize: 22, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em', color: M_FG }}>
            Private tabs
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{ ...tIconBtn(false), width: 'auto', padding: '0 12px', height: 32, gap: 6, display: 'inline-flex', fontSize: 12, fontFamily: 'inherit' }}>
            <span style={{ display: 'grid', placeItems: 'center' }}>{MIc.plus({ s: 14 })}</span> New private tab
          </button>
          <button onClick={onOpenPrivate} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '0 12px', height: 32, borderRadius: 8,
            background: 'rgba(167,139,250,0.14)', border: '1px solid rgba(167,139,250,0.32)',
            color: '#C4B5FD', fontSize: 12, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5"/></svg>
            Open private window
          </button>
        </div>
      </div>

      <div style={{
        padding: '10px 14px', marginBottom: 18,
        background: 'rgba(167,139,250,0.06)', border: '1px solid rgba(167,139,250,0.18)',
        borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ color: '#C4B5FD' }}><IcMask s={13}/></span>
        <span style={{ flex: 1, fontSize: 11.5, color: M_FG_MUTED, lineHeight: 1.4 }}>
          These tabs don't save history, share cookies, or sync. Close the window to discard them.
        </span>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: landscape ? 'repeat(3, 1fr)' : 'repeat(2, 1fr)',
        gap: 16,
      }}>
        {tabs.map((t, i) => (
          <div key={i} style={{
            aspectRatio: landscape ? '4/3' : '3/4',
            background: 'linear-gradient(180deg, rgba(167,139,250,0.05), rgba(167,139,250,0.02)), ' + M_SURFACE,
            backgroundColor: M_SURFACE,
            border: '1px solid rgba(167,139,250,0.22)',
            borderRadius: 14, overflow: 'hidden', display: 'flex', flexDirection: 'column',
            cursor: 'pointer', position: 'relative',
          }}>
            {/* violet spine */}
            <div style={{
              position: 'absolute', top: 0, left: 0, bottom: 0, width: 3,
              background: '#A78BFA', opacity: 0.55,
            }}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px 10px 14px', borderBottom: '1px solid ' + M_BORDER_SOFT }}>
              <MTile size={18} bg={t.bg} color={t.c||'#fff'} label={t.fav} radius={4}/>
              <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>{t.url}</div>
              <span style={{ color: '#C4B5FD' }}><IcMask s={11}/></span>
              <span style={{ color: M_FG_DIM, opacity: 0.6 }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
              </span>
            </div>
            <div style={{ flex: 1, padding: '14px 14px 14px 17px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 14, fontWeight: 500, color: M_FG, lineHeight: 1.3 }}>{t.title}</div>
              <div style={{ fontSize: 11, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace' }}>{t.hint}</div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

Object.assign(window, { TPrivateTabsInline });
