// Mobile "Add Connection" bottom sheet — replacement for the cramped legacy modal.
// Three methods behind tabs: Share (QR primary), Scan (camera), Connect (handle).
//
// Design intent vs. legacy:
//  · One method visible at a time → progressive disclosure
//  · QR is the hero artifact for sharing — not a wall of base64 URL text
//  · Buttons match the Ajna gradient/dark system instead of inert lavender
//  · Sheet has a real grabber, sticky header, safe-area aware footer
//  · Each path tells you WHO you are (your handle + transport status)

const MAC_TABS = [
  { id: 'handle', label: 'Connect', icon: (s) => MIc.ai({ s }) },
  { id: 'share',  label: 'Share',   icon: (s) => MIc.bolt({ s }) },
  { id: 'scan',   label: 'Scan',    icon: (s) => MIc.scan({ s }) },
];

// ─── Decorative QR placeholder (no real encoding — pattern only) ──
function MQRPattern({ size = 188, dark = '#ECECEE', light = 'transparent', logoLabel = 'A' }) {
  // deterministic pseudo-random pattern
  const N = 21;
  const cells = React.useMemo(() => {
    const arr = [];
    let seed = 1337;
    const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
    for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) arr.push(rnd() > 0.55 ? 1 : 0);
    return arr;
  }, []);
  const cell = size / N;
  const Finder = ({ x, y }) => (
    <g>
      <rect x={x*cell} y={y*cell} width={cell*7} height={cell*7} fill={dark} rx={cell*1.4}/>
      <rect x={(x+1)*cell} y={(y+1)*cell} width={cell*5} height={cell*5} fill={light === 'transparent' ? '#FFFFFF' : light} rx={cell*0.9}/>
      <rect x={(x+2)*cell} y={(y+2)*cell} width={cell*3} height={cell*3} fill={dark} rx={cell*0.6}/>
    </g>
  );
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      <rect width={size} height={size} fill={light === 'transparent' ? '#FFFFFF' : light} rx={size*0.07}/>
      {cells.map((v, i) => {
        if (!v) return null;
        const r = Math.floor(i / N), c = i % N;
        // skip finder zones
        if ((r < 7 && c < 7) || (r < 7 && c > N-8) || (r > N-8 && c < 7)) return null;
        return <rect key={i} x={c*cell + cell*0.12} y={r*cell + cell*0.12} width={cell*0.76} height={cell*0.76} fill={dark} rx={cell*0.18}/>;
      })}
      <Finder x={0} y={0}/>
      <Finder x={N-7} y={0}/>
      <Finder x={0} y={N-7}/>
      {/* center logo */}
      <rect x={size/2 - cell*2.2} y={size/2 - cell*2.2} width={cell*4.4} height={cell*4.4} fill="#FFFFFF" rx={cell*1.1}/>
      <rect x={size/2 - cell*1.9} y={size/2 - cell*1.9} width={cell*3.8} height={cell*3.8} fill="url(#qrGrad)" rx={cell*0.9}/>
      <text x={size/2} y={size/2 + cell*1.1} textAnchor="middle" fontFamily="Geist, Inter, sans-serif" fontWeight="700" fontSize={cell*3.2} fill="#0B0C0F">{logoLabel}</text>
      <defs>
        <linearGradient id="qrGrad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={M_ACCENT}/>
          <stop offset="100%" stopColor={M_ACCENT_B}/>
        </linearGradient>
      </defs>
    </svg>
  );
}

// ─── Tab strip ──
function MACTabs({ tab, setTab }) {
  return (
    <div style={{
      display: 'flex', padding: 4, gap: 4,
      background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
      borderRadius: 12, margin: '4px 18px 14px',
    }}>
      {MAC_TABS.map(t => {
        const active = tab === t.id;
        return (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
            padding: '9px 6px', borderRadius: 9, border: 0,
            background: active ? M_SURFACE_2 : 'transparent',
            color: active ? M_FG : M_FG_MUTED,
            fontSize: 12.5, fontWeight: active ? 600 : 500, fontFamily: 'inherit', cursor: 'pointer',
            boxShadow: active ? '0 1px 0 var(--m-tint) inset, 0 4px 14px -4px rgba(0,0,0,0.6)' : 'none',
            transition: 'background 160ms, color 160ms',
          }}>
            <span style={{ color: active ? M_ACCENT_B : M_FG_DIM, display: 'grid', placeItems: 'center' }}>{t.icon(14)}</span>
            {t.label}
          </button>
        );
      })}
    </div>
  );
}

// ─── Primary CTA (Ajna gradient) ──
function MACPrimary({ children, icon, onClick, disabled, style = {} }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: '100%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      padding: '14px 18px', borderRadius: 14, border: 0,
      background: disabled ? M_SURFACE_2 : 'linear-gradient(135deg, ' + M_ACCENT + ', ' + M_ACCENT_B + ')',
      color: disabled ? M_FG_DIM : '#0B0C0F',
      fontSize: 14.5, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.005em',
      cursor: disabled ? 'default' : 'pointer',
      boxShadow: disabled ? 'none' : '0 8px 28px -10px rgba(96,165,250,0.55), 0 1px 0 rgba(255,255,255,0.18) inset',
      ...style,
    }}>
      {icon}
      {children}
    </button>
  );
}

// ─── Secondary button ──
function MACSecondary({ children, icon, onClick, style = {} }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      padding: '13px 16px', borderRadius: 14,
      background: M_SURFACE_2, border: '1px solid ' + M_BORDER_SOFT,
      color: M_FG, fontSize: 13.5, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
      ...style,
    }}>
      {icon}
      {children}
    </button>
  );
}

// ─── SHARE TAB — your invitation as QR + actions ──
function MACShareTab({ onCopied }) {
  const [transport, setTransport] = React.useState('internet');
  const [copied, setCopied] = React.useState(false);
  const [refreshTick, setRefreshTick] = React.useState(0);
  const handle = 'noah-okafor';

  const transportMeta = {
    internet: { label: 'Internet', sub: 'via mediator.ajna.dev', icon: MIc.globe({ s: 13 }), color: '#60A5FA' },
    ble:      { label: 'Bluetooth', sub: 'nearby devices only',   icon: MIc.bluetooth({ s: 13 }), color: '#22D3EE' },
    mesh:     { label: 'Ajna mesh', sub: 'peer-to-peer routing',  icon: MIc.mesh({ s: 13 }), color: '#A78BFA' },
  }[transport];

  const copy = () => {
    setCopied(true);
    onCopied && onCopied();
    setTimeout(() => setCopied(false), 1600);
  };

  return (
    <div style={{ padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* QR card */}
      <div style={{
        position: 'relative',
        background: 'radial-gradient(120% 80% at 50% 0%, rgba(110,231,183,0.08), transparent 70%), ' + M_SURFACE,
        border: '1px solid ' + M_BORDER, borderRadius: 18,
        padding: '20px 16px 16px',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14,
      }}>
        <div style={{ position: 'absolute', top: 12, right: 12, display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 8px', background: 'rgba(34,210,122,0.14)', border: '1px solid rgba(34,210,122,0.26)', borderRadius: 999 }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: '#22D27A', boxShadow: '0 0 8px #22D27A' }}/>
          <span style={{ fontSize: 9.5, color: '#22D27A', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.06em', fontWeight: 600 }}>READY</span>
        </div>
        <div style={{
          padding: 12, background: '#FFFFFF', borderRadius: 14,
          boxShadow: '0 14px 40px -16px rgba(0,0,0,0.6), 0 0 0 1px var(--m-tint)',
        }} key={refreshTick}>
          <MQRPattern size={188} logoLabel="A"/>
        </div>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 11, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>Your handle</div>
          <div style={{ fontSize: 17, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em', marginTop: 3, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ color: M_ACCENT_B }}>@</span>{handle}
          </div>
          <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 4, fontFamily: 'JetBrains Mono, monospace' }}>did:key:z6Mk…3F8w</div>
        </div>
      </div>

      {/* transport segmented */}
      <div>
        <div style={{ fontSize: 10, fontWeight: 600, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span>Transport</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: transportMeta.color, textTransform: 'none', letterSpacing: 0, fontFamily: 'JetBrains Mono, monospace', fontSize: 10 }}>
            {transportMeta.icon}{transportMeta.sub}
          </span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, padding: 4, background: M_BG, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12 }}>
          {[
            { id: 'internet', label: 'Internet', icon: MIc.globe },
            { id: 'ble',      label: 'Bluetooth', icon: MIc.bluetooth },
            { id: 'mesh',     label: 'Mesh',      icon: MIc.mesh },
          ].map(o => {
            const active = transport === o.id;
            return (
              <button key={o.id} onClick={() => setTransport(o.id)} style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                padding: '8px 4px', borderRadius: 9, border: 0,
                background: active ? M_SURFACE_2 : 'transparent',
                color: active ? M_FG : M_FG_MUTED, fontSize: 12, fontWeight: active ? 600 : 500,
                fontFamily: 'inherit', cursor: 'pointer',
              }}>
                <span style={{ color: active ? M_ACCENT_B : M_FG_DIM }}>{o.icon({ s: 13 })}</span>
                {o.label}
              </button>
            );
          })}
        </div>
      </div>

      {/* actions */}
      <div style={{ display: 'flex', gap: 8 }}>
        <MACPrimary onClick={copy} icon={
          copied
            ? <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5 10 17 19 7"/></svg>
            : <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" 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>
        }>{copied ? 'Copied' : 'Copy invite link'}</MACPrimary>
        <button onClick={() => setRefreshTick(t => t + 1)} style={{
          width: 50, flexShrink: 0, borderRadius: 14,
          background: M_SURFACE_2, border: '1px solid ' + M_BORDER_SOFT, color: M_FG_MUTED,
          display: 'grid', placeItems: 'center', cursor: 'pointer',
        }} aria-label="New code">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7L21 8M21 3v5h-5"/></svg>
        </button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 12px', background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12 }}>
        <span style={{ color: M_FG_DIM }}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v4l3 2"/></svg></span>
        <span style={{ flex: 1, fontSize: 11.5, color: M_FG_MUTED }}>Invite expires in 24h · single use</span>
        <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>23h 58m</span>
      </div>
    </div>
  );
}

// ─── SCAN TAB — camera viewfinder with reticle + paste fallback ──
function MACScanTab({ onAccept }) {
  const [pasted, setPasted] = React.useState('');
  return (
    <div style={{ padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{
        position: 'relative',
        aspectRatio: '1 / 1', borderRadius: 18,
        background: 'radial-gradient(120% 80% at 50% 30%, #1a1d24 0%, #0a0b0d 80%)',
        border: '1px solid ' + M_BORDER, overflow: 'hidden',
      }}>
        {/* simulated camera scanlines */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'repeating-linear-gradient(0deg, rgba(255,255,255,0.02) 0 1px, transparent 1px 5px)',
          pointerEvents: 'none',
        }}/>
        {/* corner reticle */}
        <div style={{ position: 'absolute', inset: 36 }}>
          {[
            { top: 0, left: 0, br: '0 0 0 0', borders: 'top left' },
            { top: 0, right: 0, br: '0 0 0 0', borders: 'top right' },
            { bottom: 0, left: 0, br: '0 0 0 0', borders: 'bottom left' },
            { bottom: 0, right: 0, br: '0 0 0 0', borders: 'bottom right' },
          ].map((c, i) => (
            <div key={i} style={{
              position: 'absolute',
              ...(c.top !== undefined ? { top: c.top } : {}),
              ...(c.bottom !== undefined ? { bottom: c.bottom } : {}),
              ...(c.left !== undefined ? { left: c.left } : {}),
              ...(c.right !== undefined ? { right: c.right } : {}),
              width: 32, height: 32,
              borderTop: c.borders.includes('top') ? `2.5px solid ${M_ACCENT}` : 0,
              borderBottom: c.borders.includes('bottom') ? `2.5px solid ${M_ACCENT_B}` : 0,
              borderLeft: c.borders.includes('left') ? `2.5px solid ${c.borders.includes('top') ? M_ACCENT : M_ACCENT_B}` : 0,
              borderRight: c.borders.includes('right') ? `2.5px solid ${c.borders.includes('top') ? M_ACCENT : M_ACCENT_B}` : 0,
              borderTopLeftRadius: c.borders === 'top left' ? 12 : 0,
              borderTopRightRadius: c.borders === 'top right' ? 12 : 0,
              borderBottomLeftRadius: c.borders === 'bottom left' ? 12 : 0,
              borderBottomRightRadius: c.borders === 'bottom right' ? 12 : 0,
            }}/>
          ))}
          {/* scan line */}
          <div style={{
            position: 'absolute', left: 0, right: 0, height: 2,
            background: 'linear-gradient(90deg, transparent, ' + M_ACCENT + ', transparent)',
            boxShadow: '0 0 14px ' + M_ACCENT,
            animation: 'macScanline 2.4s ease-in-out infinite',
          }}/>
          <style>{`@keyframes macScanline { 0% { top: 6%; } 50% { top: 92%; } 100% { top: 6%; } }`}</style>
        </div>
        {/* hint */}
        <div style={{ position: 'absolute', bottom: 14, left: 14, right: 14, textAlign: 'center', fontSize: 11.5, color: M_FG_MUTED, letterSpacing: '0.04em' }}>
          Point camera at an Ajna invite QR
        </div>
        {/* flash toggle */}
        <button style={{
          position: 'absolute', top: 12, right: 12, width: 32, height: 32, borderRadius: 16,
          background: 'rgba(0,0,0,0.5)', border: '1px solid ' + M_BORDER_SOFT, color: M_FG,
          display: 'grid', placeItems: 'center', cursor: 'pointer',
        }} aria-label="Flashlight">{MIc.bolt({ s: 14 })}</button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ height: 1, flex: 1, background: M_BORDER_SOFT }}/>
        <span style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>Or paste</span>
        <div style={{ height: 1, flex: 1, background: M_BORDER_SOFT }}/>
      </div>

      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '12px 14px', background: M_SURFACE,
        border: '1px solid ' + (pasted ? 'rgba(96,165,250,0.5)' : M_BORDER_SOFT), borderRadius: 14,
        transition: 'border 160ms',
      }}>
        <span style={{ color: M_FG_DIM, flexShrink: 0 }}>{MIc.globe({ s: 14 })}</span>
        <input
          value={pasted}
          onChange={(e) => setPasted(e.target.value)}
          placeholder="https://mediator.ajna.dev?oob=…"
          style={{
            flex: 1, background: 'transparent', border: 0, outline: 0,
            color: M_FG, fontSize: 13, fontFamily: 'JetBrains Mono, monospace',
            minWidth: 0,
          }}
        />
        {pasted && (
          <button onClick={() => setPasted('')} style={{ background: 'transparent', border: 0, color: M_FG_DIM, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>{MIc.close({ s: 14 })}</button>
        )}
      </div>

      <MACPrimary disabled={!pasted} onClick={onAccept} icon={
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      }>Accept invitation</MACPrimary>
    </div>
  );
}

// ─── HANDLE TAB — primary path. Spotlight + live preview + nearby + suggested ──
function MACHandleTab({ onConnect }) {
  const [q, setQ] = React.useState('');
  const [discoverable, setDiscoverable] = React.useState(false);
  const inputRef = React.useRef(null);

  const directory = [
    { handle: 'alice-karamada', name: 'Alice Karamada', bg: '#F472B6', online: true,  conn: 'internet', mutuals: 4, did: 'z6Mk…7Hp2' },
    { handle: 'rohan-sharma',   name: 'Rohan Sharma',   bg: '#22D3EE', online: true,  conn: 'mesh',     mutuals: 2, did: 'z6Mk…F1aQ' },
    { handle: 'priya-nair',     name: 'Priya Nair',     bg: '#6EE7B7', online: false, conn: 'internet', mutuals: 7, did: 'z6Mk…9Lvb' },
    { handle: 'arjun-mehta',    name: 'Arjun Mehta',    bg: '#A78BFA', online: true,  conn: 'ble',      mutuals: 1, did: 'z6Mk…22dE' },
    { handle: 'mei-tanaka',     name: 'Mei Tanaka',     bg: '#FBBF24', online: false, conn: 'internet', mutuals: 3, did: 'z6Mk…kP7s' },
  ];
  const nearby = [
    { handle: 'arjun-mehta',  name: 'Arjun Mehta',  bg: '#A78BFA', rssi: 92, transport: 'ble' },
    { handle: 'liang-chen',   name: 'Liang Chen',   bg: '#F87171', rssi: 71, transport: 'ble' },
    { handle: 'omar-hassan',  name: 'Omar Hassan',  bg: '#60A5FA', rssi: 48, transport: 'ble' },
  ];
  const suggested = [
    { handle: 'priya-nair',     name: 'Priya Nair',     bg: '#6EE7B7', via: 'Alice & 6 others' },
    { handle: 'dimitri-volkov', name: 'Dimitri Volkov', bg: '#F472B6', via: 'Rohan & 1 other' },
    { handle: 'mei-tanaka',     name: 'Mei Tanaka',     bg: '#FBBF24', via: 'Arjun' },
  ];
  const recent = ['alice-karamada', 'rohan-sharma', 'priya-nair'];

  const norm = q.trim().toLowerCase().replace(/^@/, '');
  const exactMatch = directory.find(d => d.handle === norm);
  const fuzzy = norm
    ? directory.filter(d => !exactMatch && (d.handle.includes(norm) || d.name.toLowerCase().includes(norm)))
    : [];
  const noMatchSendable = norm.length >= 3 && !exactMatch && fuzzy.length === 0;

  const initials = (n) => n.split(' ').map(x => x[0]).join('').slice(0, 2);

  return (
    <div style={{ padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Spotlight handle input */}
      <div style={{
        position: 'relative',
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '14px 16px',
        background: 'radial-gradient(120% 200% at 0% 50%, rgba(96,165,250,0.10), transparent 60%), ' + M_SURFACE,
        border: '1px solid ' + (q ? 'rgba(96,165,250,0.55)' : M_BORDER),
        borderRadius: 16,
        boxShadow: q ? '0 0 0 4px rgba(96,165,250,0.10)' : 'none',
        transition: 'border 160ms, box-shadow 160ms',
      }}>
        <span style={{
          fontSize: 22, fontWeight: 700, color: q ? M_ACCENT_B : M_FG_DIM,
          fontFamily: 'Geist, Inter, sans-serif', lineHeight: 1, transition: 'color 160ms',
        }}>@</span>
        <input
          ref={inputRef}
          value={q}
          onChange={(e) => setQ(e.target.value.replace(/^@/, ''))}
          placeholder="handle"
          autoFocus
          style={{
            flex: 1, background: 'transparent', border: 0, outline: 0,
            color: M_FG, fontSize: 17, fontWeight: 500,
            fontFamily: 'JetBrains Mono, monospace', letterSpacing: '-0.01em',
            minWidth: 0,
          }}
        />
        {q ? (
          <button onClick={() => { setQ(''); inputRef.current && inputRef.current.focus(); }} style={{
            width: 26, height: 26, borderRadius: 13,
            background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
            color: M_FG_MUTED, cursor: 'pointer', display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>{MIc.close({ s: 12 })}</button>
        ) : (
          <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>e.g. alice-karamada</span>
        )}
      </div>

      {/* Live preview card — exact match */}
      {exactMatch && (
        <div style={{
          background: 'linear-gradient(135deg, rgba(110,231,183,0.10), rgba(96,165,250,0.10)), ' + M_SURFACE,
          border: '1px solid rgba(96,165,250,0.35)', borderRadius: 16,
          padding: 16, animation: 'macFade 200ms ease',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ position: 'relative' }}>
              <MTile size={48} bg={exactMatch.bg} color="#0B0C0F" label={initials(exactMatch.name)} radius={24}/>
              {exactMatch.online && <div style={{ position: 'absolute', bottom: 0, right: 0, width: 12, height: 12, borderRadius: 6, background: '#22D27A', border: '2px solid ' + M_SURFACE, boxShadow: '0 0 8px #22D27A' }}/>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 16, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em' }}>{exactMatch.name}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 11.5, color: M_ACCENT_B, fontFamily: 'JetBrains Mono, monospace' }}>@{exactMatch.handle}</span>
                <span style={{ width: 3, height: 3, borderRadius: 2, background: M_FG_DIM }}/>
                <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>did:key:{exactMatch.did}</span>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 12, paddingTop: 12, borderTop: '1px solid ' + M_BORDER_SOFT }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: M_FG_MUTED }}>
              <span style={{ display: 'inline-flex' }}>
                {[0,1,2].map(i => (
                  <div key={i} style={{
                    width: 16, height: 16, borderRadius: 8, marginLeft: i === 0 ? 0 : -5,
                    background: ['#F472B6','#22D3EE','#FBBF24'][i],
                    border: '1.5px solid ' + M_SURFACE,
                  }}/>
                ))}
              </span>
              <span><b style={{ color: M_FG, fontWeight: 600 }}>{exactMatch.mutuals}</b> mutual{exactMatch.mutuals === 1 ? '' : 's'}</span>
            </div>
            <div style={{ flex: 1 }}/>
            <MConnChip type={exactMatch.conn}/>
          </div>
          <button onClick={onConnect} style={{
            width: '100%', marginTop: 14, padding: '12px 16px', borderRadius: 12, border: 0,
            background: 'linear-gradient(135deg, ' + M_ACCENT + ', ' + M_ACCENT_B + ')',
            color: '#0B0C0F', fontSize: 14, fontWeight: 600,
            fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.005em',
            cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
            boxShadow: '0 8px 24px -10px rgba(96,165,250,0.55), 0 1px 0 rgba(255,255,255,0.18) inset',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg>
            Send connection request
          </button>
        </div>
      )}

      {/* Send-to-unknown CTA */}
      {noMatchSendable && (
        <button onClick={onConnect} style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px',
          background: M_SURFACE, border: '1px dashed ' + M_BORDER, borderRadius: 14,
          cursor: 'pointer', color: M_FG, fontFamily: 'inherit', textAlign: 'left',
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 19, background: M_BG,
            border: '1px solid ' + M_BORDER_SOFT, color: M_ACCENT_B,
            display: 'grid', placeItems: 'center',
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>Request <span style={{ fontFamily: 'JetBrains Mono, monospace', color: M_ACCENT_B }}>@{norm}</span></div>
            <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2 }}>Not in your directory yet · they'll need to accept</div>
          </div>
          <span style={{ color: M_FG_DIM }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg></span>
        </button>
      )}

      {/* Fuzzy matches */}
      {fuzzy.length > 0 && (
        <Section label={`Matches · ${fuzzy.length}`}>
          {fuzzy.map((m, i, a) => (
            <DirRow key={m.handle} m={m} initials={initials} last={i === a.length - 1} onClick={onConnect}/>
          ))}
        </Section>
      )}

      {/* When no query: show Nearby + Suggested + Recent */}
      {!q && (
        <>
          <Section
            label="Nearby"
            right={discoverable
              ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10, color: '#22D3EE', fontFamily: 'JetBrains Mono, monospace', textTransform: 'none', letterSpacing: 0 }}>
                  <span style={{ width: 5, height: 5, borderRadius: 3, background: '#22D3EE', boxShadow: '0 0 6px #22D3EE', animation: 'macPulse 1.6s ease-in-out infinite' }}/>BLE scanning · {nearby.length}
                </span>
              : <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', textTransform: 'none', letterSpacing: 0 }}>off</span>
            }
          >
            <style>{`@keyframes macPulse { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }`}</style>
            {!discoverable ? (
              <div style={{ padding: '18px 16px', display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 22,
                  background: 'rgba(34,211,238,0.10)', border: '1px solid rgba(34,211,238,0.22)',
                  color: '#22D3EE', display: 'grid', placeItems: 'center', flexShrink: 0,
                }}>{MIc.bluetooth({ s: 20 })}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif' }}>Make me discoverable</div>
                  <div style={{ fontSize: 11.5, color: M_FG_MUTED, marginTop: 3, lineHeight: 1.4 }}>
                    Off by default for privacy. When on, you can see and be seen by nearby Ajna users via Bluetooth.
                  </div>
                </div>
                <button
                  onClick={() => setDiscoverable(true)}
                  role="switch"
                  aria-checked={false}
                  style={{
                    width: 42, height: 24, borderRadius: 14,
                    background: M_BG, border: '1px solid ' + M_BORDER,
                    position: 'relative', cursor: 'pointer', flexShrink: 0, padding: 0,
                  }}
                >
                  <div style={{
                    position: 'absolute', top: 2, left: 2, width: 18, height: 18, borderRadius: 9,
                    background: M_FG_DIM, transition: 'left 200ms, background 200ms',
                  }}/>
                </button>
              </div>
            ) : (
              <>
                {/* discovery banner */}
                <div style={{
                  padding: '9px 12px', borderBottom: '1px solid ' + M_BORDER_SOFT,
                  background: 'linear-gradient(90deg, rgba(34,211,238,0.10), rgba(34,211,238,0.02))',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                  <span style={{ color: '#22D3EE', display: 'grid', placeItems: 'center' }}>{MIc.bluetooth({ s: 13 })}</span>
                  <span style={{ flex: 1, fontSize: 11.5, color: M_FG_MUTED }}>You're discoverable as <b style={{ color: M_FG, fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>@noah-okafor</b></span>
                  <button
                    onClick={() => setDiscoverable(false)}
                    role="switch"
                    aria-checked={true}
                    style={{
                      width: 36, height: 20, borderRadius: 12,
                      background: 'linear-gradient(135deg, #22D3EE, #60A5FA)',
                      border: 0, position: 'relative', cursor: 'pointer', flexShrink: 0, padding: 0,
                    }}
                  >
                    <div style={{
                      position: 'absolute', top: 2, left: 18, width: 16, height: 16, borderRadius: 8,
                      background: '#fff', transition: 'left 200ms',
                    }}/>
                  </button>
                </div>
                {nearby.map((p, i, a) => (
                  <div key={p.handle} onClick={onConnect} style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px',
                    borderBottom: i < a.length - 1 ? '1px solid ' + M_BORDER_SOFT : 'none',
                    cursor: 'pointer',
                  }}>
                    <MTile size={36} bg={p.bg} color="#0B0C0F" label={initials(p.name)} radius={18}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600 }}>{p.name}</div>
                      <div style={{ fontSize: 11, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>@{p.handle}</div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2, marginRight: 4 }}>
                      {[1,2,3,4].map(b => {
                        const filled = (p.rssi / 100) * 4 >= b - 0.5;
                        return <div key={b} style={{ width: 3, height: 4 + b*2, borderRadius: 1, background: filled ? '#22D3EE' : 'rgba(34,211,238,0.18)' }}/>;
                      })}
                    </div>
                    <span style={{
                      fontSize: 11.5, fontWeight: 600, color: '#22D3EE',
                      padding: '5px 10px', borderRadius: 999,
                      background: 'rgba(34,211,238,0.12)', border: '1px solid rgba(34,211,238,0.28)',
                    }}>Connect</span>
                  </div>
                ))}
              </>
            )}
          </Section>

          <Section label="Suggested · from your network">
            {suggested.map((m, i, a) => (
              <div key={m.handle} onClick={onConnect} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px',
                borderBottom: i < a.length - 1 ? '1px solid ' + M_BORDER_SOFT : 'none',
                cursor: 'pointer',
              }}>
                <MTile size={36} bg={m.bg} color="#0B0C0F" label={initials(m.name)} radius={18}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{m.name}</div>
                  <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2 }}>via {m.via}</div>
                </div>
                <span style={{
                  fontSize: 11.5, fontWeight: 600, color: M_ACCENT_B,
                  padding: '5px 11px', borderRadius: 999,
                  background: 'rgba(96,165,250,0.14)', border: '1px solid rgba(96,165,250,0.28)',
                }}>Connect</span>
              </div>
            ))}
          </Section>

          <div>
            <div style={{ fontSize: 10, fontWeight: 600, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8, paddingLeft: 2 }}>Recent</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {recent.map(h => (
                <button key={h} onClick={() => setQ(h)} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  padding: '6px 10px', borderRadius: 999,
                  background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
                  color: M_FG_MUTED, fontSize: 11.5, fontFamily: 'JetBrains Mono, monospace', cursor: 'pointer',
                }}>
                  <span style={{ color: M_FG_DIM }}>@</span>{h}
                </button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

// Tiny helpers used by the Connect tab
function Section({ label, right, children }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8, paddingLeft: 2 }}>
        <div style={{ fontSize: 10, fontWeight: 600, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase' }}>{label}</div>
        {right}
      </div>
      <div style={{ background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 14, overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}
function DirRow({ m, initials, last, onClick }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px',
      borderBottom: last ? 'none' : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
    }}>
      <div style={{ position: 'relative' }}>
        <MTile size={36} bg={m.bg} color="#0B0C0F" label={initials(m.name)} radius={18}/>
        {m.online && <div style={{ position: 'absolute', bottom: 0, right: 0, width: 10, height: 10, borderRadius: 5, background: '#22D27A', border: '2px solid ' + M_SURFACE }}/>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{m.name}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
          <span style={{ fontSize: 11, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace' }}>@{m.handle}</span>
          <MConnChip type={m.conn}/>
        </div>
      </div>
      <span style={{
        fontSize: 11.5, fontWeight: 600, color: M_ACCENT_B,
        padding: '5px 11px', borderRadius: 999,
        background: 'rgba(96,165,250,0.14)', border: '1px solid rgba(96,165,250,0.28)',
      }}>Connect</span>
    </div>
  );
}

// ─── Container — focused per-mode bottom sheet ──
// `mode` is one of 'handle' | 'share' | 'scan'. Each opens its own dedicated
// sheet shape; a quiet "Or…" footer lets the user pivot to another method.
function MScreenAddConnection({ onClose, mode: initialMode = 'handle' }) {
  const [mode, setMode] = React.useState(initialMode);
  const [toast, setToast] = React.useState(null);
  React.useEffect(() => { setMode(initialMode); }, [initialMode]);

  const meta = {
    handle: { title: 'Find someone',  sub: "Search by handle, or pick from your network.",   accent: M_ACCENT_B, icon: MIc.search({ s: 16 }) },
    share:  { title: 'Share my code', sub: 'Let someone scan your QR or copy your link.',     accent: M_ACCENT,   icon: MIc.bolt({ s: 16 }) },
    scan:   { title: 'Scan a code',   sub: 'Point your camera at an Ajna invite QR.',         accent: '#22D3EE',  icon: MIc.scan({ s: 16 }) },
  }[mode];

  const others = [
    { id: 'handle', label: 'Find by handle', icon: MIc.search, color: M_ACCENT_B },
    { id: 'share',  label: 'Share my code',  icon: MIc.bolt,   color: M_ACCENT   },
    { id: 'scan',   label: 'Scan QR',        icon: MIc.scan,   color: '#22D3EE'  },
  ].filter(o => o.id !== mode);

  const isCamera = mode === 'scan';

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 80 }}>
      {/* scrim */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(7,8,10,0.72)', backdropFilter: 'blur(10px)',
        animation: 'macFade 220ms ease',
      }}/>
      <style>{`
        @keyframes macFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes macSlideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
      `}</style>

      {/* sheet */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: M_SURFACE,
        borderTop: '1px solid ' + M_BORDER,
        borderRadius: '24px 24px 0 0',
        boxShadow: '0 -22px 60px -10px rgba(0,0,0,0.7)',
        animation: 'macSlideUp 280ms cubic-bezier(0.2,0.8,0.2,1)',
        display: 'flex', flexDirection: 'column',
        maxHeight: isCamera ? '88%' : '92%',
      }}>
        {/* grabber */}
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
          <div style={{ width: 38, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.18)' }}/>
        </div>

        {/* header — mode-specific. Icon + title + close */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '12px 18px 14px',
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: 10,
            background: meta.accent + '1F', color: meta.accent,
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}>{meta.icon}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em' }}>{meta.title}</div>
            <div style={{ fontSize: 11.5, color: M_FG_MUTED, marginTop: 2 }}>{meta.sub}</div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{
            width: 32, height: 32, borderRadius: 16,
            background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
            color: M_FG_MUTED, display: 'grid', placeItems: 'center', cursor: 'pointer',
            flexShrink: 0,
          }}>{MIc.close({ s: 14 })}</button>
        </div>

        {/* body — single dedicated method */}
        <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
          {mode === 'share'  && <MACShareTab onCopied={() => setToast('Invite link copied to clipboard')}/>}
          {mode === 'scan'   && <MACScanTab onAccept={() => setToast('Accepting invitation…')}/>}
          {mode === 'handle' && <MACHandleTab onConnect={() => setToast('Connection request sent')}/>}
        </div>

        {/* mode switcher — quiet footer */}
        <div style={{
          flexShrink: 0, padding: '12px 18px 16px',
          borderTop: '1px solid ' + M_BORDER_SOFT,
          background: M_BG,
        }}>
          <div style={{ fontSize: 9.5, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 8 }}>Or try another way</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {others.map(o => (
              <button key={o.id} onClick={() => setMode(o.id)} style={{
                flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
                padding: '10px 8px', borderRadius: 10,
                background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
                color: M_FG, fontSize: 12, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
              }}>
                <span style={{ color: o.color, display: 'grid', placeItems: 'center' }}>{o.icon({ s: 13 })}</span>
                {o.label}
              </button>
            ))}
          </div>
        </div>

        {toast && (
          <div onAnimationEnd={() => setTimeout(() => setToast(null), 1600)} style={{
            position: 'absolute', left: 18, right: 18, bottom: 110,
            padding: '10px 14px', borderRadius: 12,
            background: 'rgba(11,12,15,0.92)', border: '1px solid ' + M_BORDER,
            color: M_FG, fontSize: 12.5, textAlign: 'center',
            backdropFilter: 'blur(8px)',
            animation: 'macFade 180ms ease',
          }}>{toast}</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MScreenAddConnection, MACShareTab, MACScanTab, MACHandleTab, MQRPattern });
