// Tablet "Add connection" — iPad-native pattern.
// Unlike mobile's bottom-sheet, iPad uses a centered floating dialog that
// can show methods SIDE-BY-SIDE in landscape (Share + Scan) or stacked in
// portrait. The Connect-by-handle path opens as its own focused panel.

function TScreenAddConnection({ onClose, mode: initialMode = 'overview', landscape = true }) {
  // overview | share | scan | handle
  const [mode, setMode] = React.useState(initialMode);
  const [toast, setToast] = React.useState(null);
  React.useEffect(() => { setMode(initialMode); }, [initialMode]);

  const showToast = (t) => {
    setToast(t);
    setTimeout(() => setToast(null), 1800);
  };

  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: 'tFade 220ms ease',
      }}/>
      <style>{`
        @keyframes tFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes tPop { from { opacity: 0; transform: translate(-50%, calc(-50% + 18px)) scale(0.98); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
      `}</style>

      {/* dialog — centered */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: mode === 'overview' && landscape ? 760 : 480,
        maxWidth: '92%',
        maxHeight: '88%',
        background: M_SURFACE, border: '1px solid ' + M_BORDER,
        borderRadius: 22,
        boxShadow: '0 40px 100px -20px rgba(0,0,0,0.7), 0 0 0 1px var(--m-tint)',
        animation: 'tPop 260ms cubic-bezier(0.2,0.8,0.2,1)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        {/* header */}
        <DialogHeader mode={mode} onClose={onClose} onBack={mode !== 'overview' ? () => setMode('overview') : null}/>

        {/* body */}
        <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
          {mode === 'overview' && (
            <OverviewBody landscape={landscape} onPick={setMode}/>
          )}
          {mode === 'share' && (
            <MACShareTab onCopied={() => showToast('Invite link copied to clipboard')}/>
          )}
          {mode === 'scan' && (
            <MACScanTab onAccept={() => showToast('Accepting invitation…')}/>
          )}
          {mode === 'handle' && (
            <MACHandleTab onConnect={() => showToast('Connection request sent')}/>
          )}
        </div>

        {/* toast */}
        {toast && (
          <div style={{
            position: 'absolute', left: 20, right: 20, bottom: 20,
            padding: '10px 14px', borderRadius: 12,
            background: 'rgba(11,12,15,0.95)', border: '1px solid ' + M_BORDER,
            color: M_FG, fontSize: 13, textAlign: 'center',
            backdropFilter: 'blur(8px)',
            animation: 'tFade 180ms ease',
          }}>{toast}</div>
        )}
      </div>
    </div>
  );
}

function DialogHeader({ mode, onClose, onBack }) {
  const meta = {
    overview: { title: 'Add a connection', sub: 'Pick how you want to connect with someone new.' },
    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];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '18px 20px 16px', borderBottom: '1px solid ' + M_BORDER_SOFT,
    }}>
      {onBack && (
        <button onClick={onBack} style={{
          width: 32, height: 32, borderRadius: 10,
          background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
          color: M_FG_MUTED, display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0,
        }} aria-label="Back">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
        </button>
      )}
      {meta.icon && (
        <div style={{
          width: 38, height: 38, borderRadius: 11,
          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: 18, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em' }}>{meta.title}</div>
        <div style={{ fontSize: 12, color: M_FG_MUTED, marginTop: 2 }}>{meta.sub}</div>
      </div>
      <button onClick={onClose} style={{
        width: 32, height: 32, borderRadius: 10,
        background: M_BG, border: '1px solid ' + M_BORDER_SOFT,
        color: M_FG_MUTED, display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0,
      }} aria-label="Close">{MIc.close({ s: 14 })}</button>
    </div>
  );
}

// Overview — 3 method cards. In landscape: 3-up. Portrait: stacked rows.
function OverviewBody({ landscape, onPick }) {
  const methods = [
    { id: 'handle', icon: MIc.search,    color: M_ACCENT_B,  title: 'Find by handle',  sub: 'Search the directory or pick from your network. Best when you know who you want to add.', cta: 'Search' },
    { id: 'share',  icon: MIc.bolt,      color: M_ACCENT,    title: 'Share my code',   sub: 'Let someone scan your QR or copy your invite link. Expires in 24 hours.',                cta: 'Show QR' },
    { id: 'scan',   icon: MIc.scan,      color: '#22D3EE',   title: 'Scan a code',     sub: 'Use the camera to read an invite QR you’ve received from someone in person.',           cta: 'Open camera' },
  ];
  return (
    <div style={{ padding: '20px 20px 16px' }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: landscape ? 'repeat(3, 1fr)' : '1fr',
        gap: 14,
      }}>
        {methods.map(m => (
          <button key={m.id} onClick={() => onPick(m.id)} style={{
            display: 'flex', flexDirection: 'column', gap: 12,
            padding: '18px 16px',
            background: M_BG, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 16,
            cursor: 'pointer', color: M_FG, fontFamily: 'inherit', textAlign: 'left',
            transition: 'border 160ms, background 160ms',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = m.color + '55'; e.currentTarget.style.background = m.color + '0A'; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = M_BORDER_SOFT; e.currentTarget.style.background = M_BG; }}
          >
            <div style={{
              width: 40, height: 40, borderRadius: 12,
              background: m.color + '1F', color: m.color,
              display: 'grid', placeItems: 'center',
            }}>{m.icon({ s: 20 })}</div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em' }}>{m.title}</div>
              <div style={{ fontSize: 12, color: M_FG_MUTED, marginTop: 5, lineHeight: 1.45 }}>{m.sub}</div>
            </div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: m.color, marginTop: 'auto' }}>
              {m.cta}
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </div>
          </button>
        ))}
      </div>

      {/* identity footer */}
      <div style={{
        marginTop: 18, padding: '12px 14px',
        background: 'rgba(110,231,183,0.05)', border: '1px solid rgba(110,231,183,0.14)',
        borderRadius: 12, display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ color: M_ACCENT }}>{MIc.shield({ s: 14 })}</span>
        <div style={{ flex: 1, fontSize: 11.5, color: M_FG_MUTED, lineHeight: 1.4 }}>
          You're connecting as <b style={{ color: M_FG, fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>@noah-okafor</b> · <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>did:key:z6Mk…3F8w</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TScreenAddConnection });
