// Mobile — Create new tab group + Add tab to existing group
// Two bottom sheets that handle the most common tab-group creation flows.
//
// Create-flow: tap "New group" in the Groups mode of the Tabs page.
// Add-flow:    long-press (or "···") any tab card → "Move to group" sheet.

// ─── Bottom sheet shell ─────────────────────────────────────
function MGroupSheet({ children, onClose, title, subtitle, accent }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 80 }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(7,8,10,0.72)', backdropFilter: 'blur(10px)',
        animation: 'mgFade 200ms ease',
      }}/>
      <style>{`
        @keyframes mgFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes mgSlide { from { transform: translateY(100%); } to { transform: translateY(0); } }
      `}</style>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: M_SURFACE, borderTop: '1px solid ' + M_BORDER,
        borderRadius: '22px 22px 0 0',
        animation: 'mgSlide 260ms cubic-bezier(0.2,0.85,0.3,1)',
        maxHeight: '88%', display: 'flex', flexDirection: 'column',
        boxShadow: '0 -20px 60px -10px rgba(0,0,0,0.7)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
          <div style={{ width: 38, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.18)' }}/>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 18px 14px' }}>
          {accent && (
            <div style={{
              width: 34, height: 34, borderRadius: 10,
              background: accent.bg, border: '1.5px solid ' + accent.dot,
              color: accent.fg, display: 'grid', placeItems: 'center', flexShrink: 0,
              transition: 'background 200ms, border 200ms, color 200ms',
            }}>
              <svg width="16" height="16" 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' }}>{title}</div>
            {subtitle && <div style={{ fontSize: 11.5, color: M_FG_MUTED, marginTop: 2 }}>{subtitle}</div>}
          </div>
          <button onClick={onClose} aria-label="Close" 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, overflowY: 'auto', minHeight: 0 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

// ─── CREATE: New tab group sheet ────────────────────────────
function MNewGroupSheet({ onClose, onCreate, prefilledTabs = [] }) {
  const [name, setName] = React.useState('');
  const [color, setColor] = React.useState('blue');
  const [shared, setShared] = React.useState(false);

  const colors = ['cyan', 'blue', 'green', 'yellow', 'pink', 'violet', 'red', 'graphite'];
  const c = GROUP_COLORS[color];
  const canCreate = name.trim().length > 0;

  return (
    <MGroupSheet
      onClose={onClose}
      title="New tab group"
      subtitle={prefilledTabs.length ? `${prefilledTabs.length} tab will join this group` : 'Group tabs by project, topic, or trip.'}
      accent={c}
    >
      <div style={{ padding: '0 18px 18px' }}>
        {/* Name */}
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>Name</div>
          <input
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="e.g. iPad launch"
            autoFocus
            style={{
              width: '100%', padding: '12px 14px', boxSizing: 'border-box',
              background: M_BG, border: '1px solid ' + (name ? c.border : M_BORDER_SOFT),
              borderRadius: 12, color: M_FG, fontSize: 16,
              fontFamily: 'inherit', outline: 0, transition: 'border 160ms',
            }}
          />
        </div>

        {/* Color */}
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>Color</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {colors.map(k => {
              const cc = GROUP_COLORS[k];
              const active = color === k;
              return (
                <button key={k} onClick={() => setColor(k)} style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: cc.bg,
                  border: '1.5px solid ' + (active ? '#fff' : cc.dot),
                  boxShadow: active ? '0 0 0 3px ' + cc.border : 'none',
                  cursor: 'pointer', padding: 0, position: 'relative',
                }} aria-label={k}>
                  <span style={{
                    position: 'absolute', inset: 6, borderRadius: 6, background: cc.dot,
                    opacity: active ? 1 : 0.5,
                  }}/>
                </button>
              );
            })}
          </div>
        </div>

        {/* Prefilled tabs preview */}
        {prefilledTabs.length > 0 && (
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>
              Starting with
            </div>
            <div style={{ background: M_BG, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, padding: '4px 0' }}>
              {prefilledTabs.map((t, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px' }}>
                  <MTile size={20} bg={t.bg} color={t.c || '#fff'} label={t.fav} radius={4}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 500, color: M_FG, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.title}</div>
                    <div style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{t.url}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Share toggle row */}
        <button onClick={() => setShared(s => !s)} style={{
          display: 'flex', alignItems: 'center', gap: 12, width: '100%',
          padding: '12px 14px', borderRadius: 12, marginBottom: 16,
          background: shared ? 'rgba(167,139,250,0.08)' : M_BG,
          border: '1px solid ' + (shared ? 'rgba(167,139,250,0.32)' : M_BORDER_SOFT),
          color: M_FG, fontFamily: 'inherit', cursor: 'pointer', textAlign: 'left',
        }}>
          <span style={{
            width: 32, height: 32, borderRadius: 8, flexShrink: 0,
            background: shared ? 'rgba(167,139,250,0.18)' : M_SURFACE_2,
            color: shared ? '#C4B5FD' : M_FG_MUTED,
            display: 'grid', placeItems: 'center',
          }}>{MIc.mesh({ s: 16 })}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>Share with others</div>
            <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2 }}>Sync this group over DIDComm with peers you invite.</div>
          </div>
          <div style={{
            width: 38, height: 22, borderRadius: 12,
            background: shared ? 'linear-gradient(135deg, #A78BFA, #7C3AED)' : M_BG,
            border: '1px solid ' + (shared ? 'transparent' : M_BORDER),
            position: 'relative', flexShrink: 0,
          }}>
            <div style={{
              position: 'absolute', top: 2, left: shared ? 18 : 2,
              width: 16, height: 16, borderRadius: 8,
              background: '#fff', transition: 'left 200ms',
            }}/>
          </div>
        </button>

        {/* Sticky-feeling actions */}
        <div style={{ display: 'flex', gap: 10, paddingBottom: 14 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: '13px 16px', borderRadius: 12,
            background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
            color: M_FG, fontSize: 14, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          }}>Cancel</button>
          <button
            onClick={() => canCreate && onCreate && onCreate({ name: name.trim(), color, shared, tabs: prefilledTabs })}
            disabled={!canCreate}
            style={{
              flex: 1.4, padding: '13px 16px', borderRadius: 12, border: 0,
              background: canCreate ? 'linear-gradient(135deg,' + M_ACCENT + ',' + M_ACCENT_B + ')' : M_SURFACE_2,
              color: canCreate ? '#0B0C0F' : M_FG_DIM,
              fontSize: 14, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif',
              cursor: canCreate ? 'pointer' : 'default',
              boxShadow: canCreate ? '0 8px 24px -10px rgba(96,165,250,0.5)' : 'none',
            }}>Create group</button>
        </div>
      </div>
    </MGroupSheet>
  );
}

// ─── ADD: Move tab to existing group sheet ──────────────────
// Shown when a user picks "Move to group…" on a tab.
function MMoveToGroupSheet({ onClose, tab, onPick, onCreateNew, currentGroupId }) {
  return (
    <MGroupSheet
      onClose={onClose}
      title="Move to group"
      subtitle={tab ? tab.title : 'Pick a group for this tab.'}
    >
      <div style={{ padding: '0 18px 22px' }}>
        {/* Tab preview chip */}
        {tab && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 12px', marginBottom: 14,
            background: M_BG, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 10,
          }}>
            <MTile size={22} bg={tab.bg} color={tab.c || '#fff'} label={tab.fav} radius={5}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tab.title}</div>
              <div style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{tab.url}</div>
            </div>
          </div>
        )}

        {/* Existing groups list */}
        <div style={{
          background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
          borderRadius: 12, overflow: 'hidden', marginBottom: 14,
        }}>
          {TAB_GROUPS.map((g, i) => {
            const c = GROUP_COLORS[g.color];
            const isCurrent = g.id === currentGroupId;
            return (
              <button
                key={g.id}
                onClick={() => onPick && onPick(g.id)}
                disabled={isCurrent}
                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',
                  textAlign: 'left', cursor: isCurrent ? 'default' : 'pointer',
                  opacity: isCurrent ? 0.5 : 1, color: M_FG, 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: 8.5, fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: '0.06em',
                      }}>{MIc.mesh({ s: 9 })} {g.members}</span>
                    )}
                  </div>
                  <div style={{ fontSize: 10.5, 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>

        {/* Create new */}
        <button onClick={onCreateNew} style={{
          display: 'flex', alignItems: 'center', gap: 12, width: '100%',
          padding: '12px 14px', borderRadius: 12,
          background: M_BG, border: '1px dashed ' + M_BORDER,
          color: M_FG, fontFamily: 'inherit', textAlign: 'left', cursor: 'pointer',
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 8,
            background: M_SURFACE_2, 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>

        {/* Remove from current group, if any */}
        {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',
          }}>Remove from group</button>
        )}
      </div>
    </MGroupSheet>
  );
}

// ─── ACTIONS: Long-press / "···" action sheet for a tab ─────
// Surfaces Move-to-group, Share, Close, etc. Long-press on a tab card opens this.
function MTabActionsSheet({ tab, onClose, onMoveToGroup, onClosedTab }) {
  const actions = [
    { id: 'group',     icon: <svg width="16" height="16" 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: 'Move to group…', color: M_ACCENT_B },
    { id: 'pin',       icon: <svg width="16" height="16" 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',         color: M_ACCENT },
    { id: 'share',     icon: <svg width="16" height="16" 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 tab…',     color: '#22D3EE' },
    { id: 'send-peer', icon: MIc.chat({ s: 16 }),                                                                                                                                                                                                                                                                                                                                                                       label: 'Send to peer…',  color: '#A78BFA' },
    { id: 'copy',      icon: <svg width="16" height="16" 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',       color: M_FG_MUTED },
    { id: 'close',     icon: <svg width="16" height="16" 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',      color: '#F87171', danger: true },
  ];

  return (
    <MGroupSheet
      onClose={onClose}
      title={tab ? tab.title : 'Tab'}
      subtitle={tab ? tab.url : ''}
    >
      <div style={{ padding: '0 14px 22px' }}>
        <div style={{ background: M_BG, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, overflow: 'hidden' }}>
          {actions.map((a, i) => (
            <button key={a.id} onClick={() => {
              if (a.id === 'group') onMoveToGroup && onMoveToGroup();
              else if (a.id === 'close') { onClosedTab && onClosedTab(); onClose(); }
              else onClose();
            }} style={{
              display: 'flex', alignItems: 'center', gap: 14, width: '100%',
              padding: '13px 14px', background: 'transparent', border: 0,
              borderBottom: i < actions.length - 1 ? '1px solid ' + M_BORDER_SOFT : 'none',
              color: a.danger ? '#F87171' : M_FG, textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
            }}>
              <span style={{
                width: 28, height: 28, borderRadius: 8,
                background: (a.color || M_FG_MUTED) + '1F',
                color: a.color, display: 'grid', placeItems: 'center', flexShrink: 0,
              }}>{a.icon}</span>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{a.label}</span>
              <span style={{ color: M_FG_DIM, flexShrink: 0 }}>
                <svg width="13" height="13" 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>
      </div>
    </MGroupSheet>
  );
}

Object.assign(window, { MGroupSheet, MNewGroupSheet, MMoveToGroupSheet, MTabActionsSheet });
