// Tablet — Tab context menu + Move-to-group dialog
// Mirrors the mobile group flows but uses iPad-native patterns:
//   · Context menu = right-click / long-press / "..." popover (not a sheet)
//   · Move-to-group = centered dialog (not a bottom sheet)
//   · Create group = the existing TNewGroupDialog

// ─── Tab context menu (popover anchored to the tab card or its "..." button) ──
function TTabContextMenu({ anchorRect, tab, currentGroupId, onClose, onMoveToGroup, onAction }) {
  // Position popover. Right-align to anchor, drop below by default.
  const w = 240;
  const top = anchorRect ? anchorRect.bottom + 6 : 80;
  const left = anchorRect ? Math.max(8, Math.min(window.innerWidth - w - 8, anchorRect.left)) : 80;

  const groups = (window.TAB_GROUPS || []);

  const items = [
    { id: 'open-new',    icon: <svg width="14" height="14" 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>, label: 'Open in new tab',     short: '⌘ click' },
    { id: 'open-private',icon: <IcMask s={14}/>,                                                                                                                                                                                                                                                                                                          label: 'Open in private tab',  short: '⇧⌘ N',  accent: PRIV_ACCENT_2 },
    { kind: 'divider' },
    { id: 'pin',         icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 17v5"/><path d="M5 12V3h14v9l-3 4H8z"/></svg>,                                                                                                                  label: 'Pin tab' },
    { id: 'mute',        icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5 6 9H2v6h4l5 4z"/><path d="M22 9l-6 6M16 9l6 6"/></svg>,                                                                                                       label: 'Mute site' },
    { id: 'duplicate',   icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>,                                                                                  label: 'Duplicate tab' },
    { kind: 'divider' },
    { kind: 'submenu-trigger', id: 'group',
      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>,
      label: currentGroupId ? 'Move to group' : 'Add to group', accent: M_ACCENT_B },
    { kind: 'divider' },
    { id: 'share',       icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-6"/><path d="m16 6-4-4-4 4"/><path d="M12 2v14"/></svg>,                                                                       label: 'Share…' },
    { id: 'send-peer',   icon: MIc.chat({ s: 14 }),                                                                                                                                                                                                                                                                                                          label: 'Send to peer…',        accent: '#A78BFA' },
    { id: 'copy',        icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>,                                                                                  label: 'Copy URL',             short: '⌘ C' },
    { kind: 'divider' },
    { id: 'close',       icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>,                                                                                                                                       label: 'Close tab',            short: '⌘ W', danger: true },
  ];

  // Hover state for the group submenu
  const [groupOpen, setGroupOpen] = React.useState(false);
  const groupRef = React.useRef(null);

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'transparent' }}/>
      <div style={{
        position: 'fixed', top, left, width: w, zIndex: 1001,
        background: M_SURFACE, border: '1px solid ' + M_BORDER,
        borderRadius: 12, padding: '6px 0', color: M_FG,
        boxShadow: '0 24px 60px -10px rgba(0,0,0,0.55), 0 0 0 1px var(--m-tint)',
        animation: 'tcmFade 160ms ease',
      }}>
        <style>{`@keyframes tcmFade { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }`}</style>

        {/* Tab preview */}
        {tab && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '6px 14px 8px',
            borderBottom: '1px solid ' + M_BORDER_SOFT,
          }}>
            <MTile size={16} bg={tab.bg} color={tab.c || '#fff'} label={tab.fav} radius={4}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tab.title}</div>
              <div style={{ fontSize: 9.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{tab.url}</div>
            </div>
          </div>
        )}

        {items.map((it, i) => {
          if (it.kind === 'divider') return <div key={'d'+i} style={{ height: 1, margin: '4px 8px', background: M_BORDER_SOFT }}/>;

          if (it.kind === 'submenu-trigger') {
            return (
              <div
                key={it.id}
                ref={groupRef}
                onMouseEnter={() => setGroupOpen(true)}
                onMouseLeave={() => setGroupOpen(false)}
                style={{ position: 'relative' }}
              >
                <button
                  onClick={() => onMoveToGroup && onMoveToGroup()}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--m-tint)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                    padding: '8px 14px', background: 'transparent', border: 0,
                    color: M_FG, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 13,
                  }}
                >
                  <span style={{ color: it.accent || M_FG_MUTED, display: 'grid', placeItems: 'center', width: 16, flexShrink: 0 }}>{it.icon}</span>
                  <span style={{ flex: 1, fontWeight: 500 }}>{it.label}</span>
                  <span style={{ color: M_FG_DIM }}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="m9 6 6 6-6 6"/></svg>
                  </span>
                </button>

                {/* Submenu */}
                {groupOpen && (
                  <div style={{
                    position: 'absolute', top: -6, left: w - 4, width: 220,
                    background: M_SURFACE, border: '1px solid ' + M_BORDER,
                    borderRadius: 12, padding: '6px 0',
                    boxShadow: '0 24px 60px -10px rgba(0,0,0,0.55)',
                  }}>
                    <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600, padding: '6px 14px 4px' }}>Groups</div>
                    {groups.map(g => {
                      const c = GROUP_COLORS[g.color];
                      const isCurrent = g.id === currentGroupId;
                      return (
                        <button key={g.id}
                          onClick={() => { if (!isCurrent) { onAction && onAction('move', g.id); onClose(); } }}
                          disabled={isCurrent}
                          onMouseEnter={(e) => { if (!isCurrent) e.currentTarget.style.background = 'var(--m-tint)'; }}
                          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                          style={{
                            width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                            padding: '7px 14px', background: 'transparent', border: 0,
                            color: isCurrent ? M_FG_DIM : M_FG, cursor: isCurrent ? 'default' : 'pointer',
                            textAlign: 'left', fontFamily: 'inherit', fontSize: 12.5,
                            opacity: isCurrent ? 0.6 : 1,
                          }}>
                          <span style={{
                            width: 14, height: 14, borderRadius: 4,
                            background: c.bg, border: '1.5px solid ' + c.dot, flexShrink: 0,
                          }}/>
                          <span style={{ flex: 1, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.name}</span>
                          {isCurrent && <span style={{ fontSize: 9, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Current</span>}
                        </button>
                      );
                    })}
                    <div style={{ height: 1, margin: '4px 8px', background: M_BORDER_SOFT }}/>
                    <button
                      onClick={() => { onAction && onAction('new-group'); onClose(); }}
                      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--m-tint)'}
                      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                      style={{
                        width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                        padding: '8px 14px', background: 'transparent', border: 0,
                        color: M_ACCENT_B, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 12.5,
                      }}>
                      <span style={{ display: 'grid', placeItems: 'center', width: 14, flexShrink: 0 }}>{MIc.plus({ s: 13 })}</span>
                      New group…
                    </button>
                    {currentGroupId && (
                      <>
                        <div style={{ height: 1, margin: '4px 8px', background: M_BORDER_SOFT }}/>
                        <button
                          onClick={() => { onAction && onAction('remove'); onClose(); }}
                          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--m-tint)'}
                          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                          style={{
                            width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                            padding: '8px 14px', background: 'transparent', border: 0,
                            color: M_FG_MUTED, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 12.5,
                          }}>
                          <span style={{ display: 'grid', placeItems: 'center', width: 14, flexShrink: 0, color: M_FG_DIM }}>{MIc.close({ s: 13 })}</span>
                          Remove from group
                        </button>
                      </>
                    )}
                  </div>
                )}
              </div>
            );
          }

          return (
            <button
              key={it.id}
              onClick={() => { onAction && onAction(it.id); onClose(); }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--m-tint)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 14px', background: 'transparent', border: 0,
                color: it.danger ? '#F87171' : M_FG,
                cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 13,
              }}
            >
              <span style={{ color: it.accent || (it.danger ? '#F87171' : M_FG_MUTED), display: 'grid', placeItems: 'center', width: 16, flexShrink: 0 }}>{it.icon}</span>
              <span style={{ flex: 1, fontWeight: 500 }}>{it.label}</span>
              {it.short && <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.02em' }}>{it.short}</span>}
            </button>
          );
        })}
      </div>
    </>
  );
}

// ─── Move-to-group centered dialog (used as a fallback when context menu isn't appropriate) ──
function TMoveToGroupDialog({ tab, currentGroupId, onClose, onPick, onCreateNew }) {
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 1000 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(7,8,10,0.72)', backdropFilter: 'blur(10px)', animation: 'tFade 200ms ease' }}/>
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)', width: 460, maxWidth: '92%',
        maxHeight: '82%',
        background: M_SURFACE, border: '1px solid ' + M_BORDER,
        borderRadius: 18,
        boxShadow: '0 40px 100px -20px rgba(0,0,0,0.7), 0 0 0 1px var(--m-tint)',
        animation: 'tPop 240ms cubic-bezier(0.2,0.85,0.3,1)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '18px 20px 14px', borderBottom: '1px solid ' + M_BORDER_SOFT }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'rgba(96,165,250,0.14)', color: M_ACCENT_B,
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>
            <svg width="18" height="18" 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>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em' }}>Move to group</div>
            {tab && <div style={{ fontSize: 12, color: M_FG_MUTED, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tab.title}</div>}
          </div>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 8, background: M_BG,
            border: '1px solid ' + M_BORDER_SOFT, color: M_FG_MUTED,
            display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0,
          }}>{MIc.close({ s: 13 })}</button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '14px 20px 20px' }}>
          <div style={{ background: M_BG, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, overflow: 'hidden', marginBottom: 12 }}>
            {TAB_GROUPS.map((g, i) => {
              const c = GROUP_COLORS[g.color];
              const isCurrent = g.id === currentGroupId;
              return (
                <button key={g.id}
                  onClick={() => !isCurrent && onPick && onPick(g.id)}
                  disabled={isCurrent}
                  onMouseEnter={(e) => { if (!isCurrent) e.currentTarget.style.background = 'var(--m-tint)'; }}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    width: '100%', padding: '12px 14px',
                    background: 'transparent', border: 0,
                    borderBottom: i < TAB_GROUPS.length - 1 ? '1px solid ' + M_BORDER_SOFT : 'none',
                    color: M_FG, cursor: isCurrent ? 'default' : 'pointer',
                    opacity: isCurrent ? 0.55 : 1, textAlign: 'left', fontFamily: 'inherit',
                  }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: c.bg, border: '1.5px solid ' + c.dot, flexShrink: 0 }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.name}</span>
                      {g.shared && (
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 3,
                          padding: '1px 5px', borderRadius: 4,
                          background: 'rgba(167,139,250,0.16)', color: '#C4B5FD',
                          fontSize: 9, fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: '0.06em',
                        }}>{MIc.mesh({ s: 9 })} {g.members}</span>
                      )}
                    </div>
                    <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2, fontFamily: 'JetBrains Mono, monospace' }}>{g.tabs.length} tabs</div>
                  </div>
                  {isCurrent
                    ? <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>Current</span>
                    : <span style={{ color: M_FG_DIM }}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 6 6 6-6 6"/></svg>
                      </span>
                  }
                </button>
              );
            })}
          </div>

          <button onClick={onCreateNew} style={{
            display: 'flex', alignItems: 'center', gap: 12, width: '100%',
            padding: '12px 14px', borderRadius: 12,
            background: 'transparent', border: '1px dashed ' + M_BORDER,
            color: M_FG, fontFamily: 'inherit', textAlign: 'left', cursor: 'pointer',
          }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: M_BG, color: M_ACCENT_B, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{MIc.plus({ s: 14 })}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>New group…</div>
              <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2 }}>This tab will be its first member</div>
            </div>
          </button>

          {currentGroupId && (
            <button onClick={() => onPick && onPick(null)} style={{
              display: 'block', width: '100%',
              padding: '13px 16px', marginTop: 12,
              background: 'transparent', border: 0,
              color: M_FG_MUTED, fontSize: 13, fontFamily: 'inherit',
              cursor: 'pointer', textAlign: 'center',
            }}>Remove from group</button>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Confirmation toast for iPad ───────────────────────────
function TToast({ message, onDone }) {
  React.useEffect(() => {
    const id = setTimeout(() => onDone && onDone(), 1800);
    return () => clearTimeout(id);
  }, [message, onDone]);
  return (
    <div style={{
      position: 'fixed', top: 76, left: '50%', transform: 'translateX(-50%)',
      padding: '10px 18px 10px 14px', borderRadius: 12,
      background: 'rgba(11,12,15,0.94)', border: '1px solid ' + M_BORDER,
      color: M_FG, fontSize: 13, fontFamily: 'inherit',
      backdropFilter: 'blur(10px)', zIndex: 1100,
      boxShadow: '0 12px 36px rgba(0,0,0,0.4)',
      animation: 'tFade 180ms ease',
      display: 'inline-flex', alignItems: 'center', gap: 8,
    }}>
      <span style={{ color: M_ACCENT, display: 'grid', placeItems: 'center' }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
      </span>
      {message}
    </div>
  );
}

Object.assign(window, { TTabContextMenu, TMoveToGroupDialog, TToast });
