// ─────────────────────────────────────────────────────────────
// TradeHandlesSheet — the in-person handshake.
//
// Two users next to each other, no forests in common, no way to search
// because handles aren't memorable. The flow:
//
//   1. Your handle is shown big with a glyph (stand-in for QR/NFC) +
//      Copy/Share button so they can pull it from your screen.
//   2. An input field lets you key in their handle (paste, scan, type).
//   3. On confirm, you exchange an acquaintance handshake — both sides
//      get a Sunlight notification, no DM-spam to either party.
//
// This is the prototype's stand-in. Production would use camera+QR or
// proximity tokens, but the UI is the same shape.
// ─────────────────────────────────────────────────────────────

function TradeHandlesSheet({ isOpen, onBack, onClose, onConfirm }) {
  const [theirHandle, setTheirHandle] = React.useState('');
  const [copied,      setCopied]      = React.useState(false);
  const [phase,       setPhase]       = React.useState('input');  // 'input' | 'matched' | 'done'

  React.useEffect(() => {
    if (isOpen) { setTheirHandle(''); setCopied(false); setPhase('input'); }
  }, [isOpen]);

  // Look up the typed handle against the known universes so we can show
  // a live preview card before the user commits.
  const cleaned = theirHandle.trim().replace(/^@/, '').toLowerCase();
  const matchedUser = cleaned ? (
    INITIAL_FOLK.find(f => f.handle.toLowerCase() === cleaned) ||
    FOREST_FOLK.find(f => f.handle.toLowerCase() === cleaned) ||
    ACROSS_CANOPY.find(f => f.handle.toLowerCase() === cleaned)
  ) : null;
  const canConfirm = !!matchedUser;

  function copyHandle() {
    try { navigator.clipboard?.writeText('@' + YOU.handle); } catch {}
    setCopied(true);
    window.setTimeout(() => setCopied(false), 1400);
  }

  function commit() {
    setPhase('done');
    onConfirm?.({ user: matchedUser });
    window.setTimeout(() => onBack(), 1600);
  }

  return (
    <SecondarySheet
      title="Trade handles in person"
      subtitle="Show yours, take theirs. Both sides become Acquaintances."
      isOpen={isOpen}
      onBack={onBack}
      onClose={onClose}
      footer={
        phase === 'done' ? null :
        <button
          disabled={!canConfirm}
          onClick={commit}
          style={{
            width: '100%',
            background: canConfirm ? '#4F8E51' : '#1A2812',
            color: canConfirm ? '#F2EDE4' : '#586552',
            border: 'none', padding: '13px', borderRadius: 12,
            font: '500 14px var(--font-sans)',
            cursor: canConfirm ? 'pointer' : 'default',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
          <PIcons.Handshake size={16} color={canConfirm ? '#F2EDE4' : '#586552'}/>
          {canConfirm ? `Add @${matchedUser.handle} as Acquaintance` : 'Enter their handle'}
        </button>
      }
    >
      {phase === 'done' ? (
        <DoneBeat
          label={`Now Acquaintances`}
          subline={`You and @${matchedUser.handle} can see each other in your folk.`}
        />
      ) : (
        <div style={{ padding: '14px 18px 18px',
                      display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* ── Your handle card ───────────────────────────────────────
              The point of contact. Big mono handle so they can read it
              across a table, glyph as a stand-in for QR/NFC. */}
          <div style={{
            background: '#3A2A07', border: '0.5px solid #6B5018',
            borderRadius: 14, padding: '16px 18px', position: 'relative', overflow: 'hidden',
          }}>
            {/* Decorative ring — leans into Threshold mark */}
            <div style={{
              position: 'absolute', right: -50, top: -50,
              width: 160, height: 160, borderRadius: '50%',
              border: '0.5px solid rgba(212,150,12,0.18)',
            }}/>
            <div style={{
              position: 'absolute', right: -22, top: -22,
              width: 100, height: 100, borderRadius: '50%',
              border: '0.5px solid rgba(212,150,12,0.30)',
            }}/>

            <div style={{
              font: '500 10.5px var(--font-sans)', color: '#F4DCA0',
              letterSpacing: '0.14em', textTransform: 'uppercase',
            }}>You</div>
            <div style={{
              font: '500 28px var(--font-mono)', color: '#F2EDE4', marginTop: 4,
              letterSpacing: '-0.02em',
            }}>@{YOU.handle}</div>

            <div style={{
              marginTop: 12, display: 'flex', alignItems: 'center', gap: 10,
              position: 'relative', zIndex: 1,
            }}>
              {/* Handshake glyph — stand-in for a real QR code */}
              <ProximityGlyph/>

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ font: '500 12px var(--font-sans)', color: '#F4DCA0' }}>
                  Hold near another phone
                </div>
                <div style={{ font: 'italic 400 11px/1.4 var(--font-serif)', color: '#D6BFA8', marginTop: 2 }}>
                  Or read your handle aloud — they'll type it below on their side.
                </div>
              </div>

              <button onClick={copyHandle} aria-label="Copy handle"
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '7px 11px', borderRadius: 999,
                  background: copied ? '#4F8E51' : '#1A2812',
                  border: '0.5px solid ' + (copied ? '#4F8E51' : '#445239'),
                  color: copied ? '#F2EDE4' : '#F4DCA0',
                  font: '500 11.5px var(--font-sans)', cursor: 'pointer',
                  transition: 'background 160ms var(--ease-organic)',
                  flexShrink: 0,
                }}>
                {copied ? <PIcons.Check size={13} color="#F2EDE4"/>
                        : <PIcons.Copy  size={13} color="#F4DCA0"/>}
                {copied ? 'Copied' : 'Copy'}
              </button>
            </div>
          </div>

          {/* ── Their handle input ──────────────────────────────────── */}
          <div>
            <div style={{
              font: '500 10.5px var(--font-sans)', color: '#76AB78',
              letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8,
            }}>Their handle</div>
            <div style={{
              height: 56, padding: '0 14px',
              background: '#0B1306',
              border: `0.5px solid ${matchedUser ? '#4F8E51' : '#2D3A22'}`,
              borderRadius: 12,
              display: 'flex', alignItems: 'center', gap: 10,
              transition: 'border-color 160ms var(--ease-organic)',
            }}>
              <span style={{ font: '500 22px var(--font-mono)', color: '#586552' }}>@</span>
              <input
                value={theirHandle}
                onChange={e => setTheirHandle(e.target.value)}
                placeholder="their-handle"
                autoCapitalize="none"
                autoCorrect="off"
                spellCheck="false"
                style={{
                  flex: 1, background: 'transparent', border: 'none', outline: 'none',
                  font: '500 18px var(--font-mono)', color: '#F2EDE4',
                  letterSpacing: '-0.01em',
                }}/>
              {matchedUser && (
                <span style={{ display: 'flex', alignItems: 'center', gap: 6,
                               color: '#76AB78', flexShrink: 0 }}>
                  <PIcons.Check size={16} color="#76AB78"/>
                  <span style={{ font: '500 11.5px var(--font-sans)' }}>found</span>
                </span>
              )}
            </div>

            {/* Live preview when we match */}
            {matchedUser && (
              <div style={{
                marginTop: 10, padding: '11px 12px',
                background: '#111D0A', border: '0.5px solid #2D3A22', borderRadius: 10,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <FolkAvatar user={matchedUser} size={32}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ font: '500 14px var(--font-mono)', color: '#F2EDE4' }}>{matchedUser.handle}</div>
                  <div style={{ font: 'italic 400 12px var(--font-serif)', color: '#8A9678', marginTop: 2 }}>
                    {matchedUser.whereabouts
                      || (matchedUser.appearsIn ? `seen in ${matchedUser.appearsIn}`
                          : `joined ${matchedUser.joined}`)}
                  </div>
                </div>
              </div>
            )}

            {/* Not-found state */}
            {!matchedUser && cleaned.length > 1 && (
              <div style={{
                marginTop: 10, padding: '10px 12px',
                background: 'transparent', border: '0.5px dashed #2D3A22', borderRadius: 10,
                font: 'italic 400 12.5px/1.5 var(--font-serif)', color: '#8A9678',
              }}>
                No one matches yet — handles are case-insensitive. Try again, or share yours and let them find you.
              </div>
            )}
          </div>

          {/* Fine-print on what happens next */}
          <div style={{
            padding: 12,
            background: '#0B1306', border: '0.5px solid #1F2B16', borderRadius: 10,
            font: 'italic 400 12px/1.55 var(--font-serif)', color: '#8A9678',
          }}>
            Both sides have to confirm. We'll show their handle in your folk under <b>Acquaintances</b> as soon as they tap accept.
          </div>
        </div>
      )}
    </SecondarySheet>
  );
}


// Stand-in for a QR code / proximity beacon. A small ring composition
// with a sunlight nucleus — visually reads as "broadcasting".
function ProximityGlyph() {
  return (
    <div style={{
      width: 46, height: 46, borderRadius: '50%',
      background: '#0B1306', border: '0.5px solid #6B5018',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative', flexShrink: 0,
    }}>
      <span style={{ position: 'absolute', inset: 3, borderRadius: '50%',
                     border: '0.5px solid rgba(212,150,12,0.5)' }}/>
      <span style={{ position: 'absolute', inset: 9, borderRadius: '50%',
                     border: '0.5px solid rgba(212,150,12,0.7)' }}/>
      <span style={{
        position: 'absolute', inset: 17, borderRadius: '50%',
        background: '#D4960C',
        boxShadow: '0 0 12px rgba(212,150,12,0.6)',
        animation: 'sunPulse 1.8s var(--ease-organic) infinite',
      }}/>
    </div>
  );
}


window.TradeHandlesSheet = TradeHandlesSheet;
