// Screen: You & Ajna (ajna://settings/people) — identity + P2P sync entry

function ScreenYouAndAjna({ go }) {
  const [name, setName] = React.useState(() => {
    try { return localStorage.getItem('ajna-profile-name') || 'Ajna Member'; } catch { return 'Ajna Member'; }
  });
  const [editing, setEditing] = React.useState(false);
  const [avatarIdx, setAvatarIdx] = React.useState(() => {
    try { return parseInt(localStorage.getItem('ajna-profile-avatar') || '0', 10) || 0; } catch { return 0; }
  });
  const [picking, setPicking] = React.useState(false);
  const inputRef = React.useRef(null);

  const AVATARS = [
    { grad: 'var(--accent-grad)' },
    { grad: 'linear-gradient(135deg,#C4B5FD,#818CF8)' },
    { grad: 'linear-gradient(135deg,#FDE68A,#F472B6)' },
    { grad: 'linear-gradient(135deg,#6EE7B7,#22D3EE)' },
    { grad: 'linear-gradient(135deg,#FCA5A5,#F59E0B)' },
    { grad: 'linear-gradient(135deg,#D1D5DB,#6B7280)' },
  ];
  const initials = name.trim().split(/\s+/).slice(0, 2).map(s => s[0] || '').join('').toUpperCase() || 'A';
  const grad = AVATARS[avatarIdx].grad;

  React.useEffect(() => { if (editing) setTimeout(() => inputRef.current?.focus(), 0); }, [editing]);
  React.useEffect(() => { try { localStorage.setItem('ajna-profile-name', name); } catch {} }, [name]);
  React.useEffect(() => { try { localStorage.setItem('ajna-profile-avatar', String(avatarIdx)); } catch {} }, [avatarIdx]);

  const Lock = ({ title }) => (
    <span title={title} style={{ color: 'var(--fg-dim)', display: 'inline-flex', verticalAlign: 'middle', marginLeft: 6 }}>
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
    </span>
  );

  return (
    <>
      <PageHeader route={SETTING_ROUTES.you} title="You & Ajna" subtitle="Your identity, synced across your own devices. No cloud sign-in — Ajna uses end-to-end encrypted peer-to-peer sync via DIDComm."/>

      {/* Identity hero — name and avatar editable; handle and DID are permanent */}
      <div style={{
        background: 'var(--bg-elev)',
        border: '1px solid var(--border-soft)',
        borderRadius: 14, padding: 20,
        display: 'flex', alignItems: 'center', gap: 18,
        flexWrap: 'wrap',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(600px 200px at 0% 0%, oklch(from var(--accent-a) l c h / 0.08), transparent 60%)',
          pointerEvents: 'none',
        }}/>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: grad,
            display: 'grid', placeItems: 'center',
            color: '#0F1114', fontWeight: 700, fontSize: 20,
            fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em',
            boxShadow: '0 4px 20px oklch(from var(--accent-b) l c h / 0.35)',
          }}>{initials}</div>
          <button
            onClick={() => setPicking(p => !p)}
            aria-label="Change photo"
            style={{
              position: 'absolute', right: -3, bottom: -3,
              width: 24, height: 24, borderRadius: 12,
              background: 'var(--fg)', color: 'var(--bg-elev)',
              border: '2px solid var(--bg-elev)',
              display: 'grid', placeItems: 'center', cursor: 'pointer', padding: 0,
            }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7h4l2-3h6l2 3h4v12H3z"/><circle cx="12" cy="13" r="4"/></svg>
          </button>
        </div>
        <div style={{ flex: '1 1 220px', minWidth: 0, position: 'relative' }}>
          {editing ? (
            <input
              ref={inputRef}
              value={name}
              onChange={(e) => setName(e.target.value)}
              onBlur={() => setEditing(false)}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === 'Escape') setEditing(false); }}
              maxLength={40}
              style={{
                width: '100%', maxWidth: 280, background: 'var(--bg-elev-2)',
                border: '1px solid oklch(from var(--accent-b) l c h / 0.5)',
                borderRadius: 8, padding: '5px 10px',
                color: 'var(--fg)', fontSize: 16, fontWeight: 500,
                fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em', outline: 0,
              }}
            />
          ) : (
            <button
              onClick={() => setEditing(true)}
              aria-label="Edit name"
              style={{
                background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
                fontSize: 16, fontWeight: 500, color: 'var(--fg)',
                fontFamily: 'inherit', textAlign: 'left',
                display: 'inline-flex', alignItems: 'center', gap: 7,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%',
              }}>
              {name}
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--fg-dim)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4z"/></svg>
            </button>
          )}
          <div style={{
            fontSize: 11, color: 'var(--fg-muted)', marginTop: 4,
            fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.02em',
            display: 'flex', alignItems: 'center',
          }}>
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>@noah-okafor · did:key:z6Mkh…9kTp</span>
            <Lock title="Handle and DID are permanent"/>
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
            <Chip color="green">P2P sync on</Chip>
            <Chip>3 paired devices</Chip>
          </div>
        </div>
        <TextBtn>Export identity</TextBtn>

        {picking && (
          <div style={{
            flexBasis: '100%', position: 'relative',
            marginTop: 4, paddingTop: 16, borderTop: '1px solid var(--border-soft)',
          }}>
            <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', color: 'var(--fg-dim)', textTransform: 'uppercase', marginBottom: 12 }}>Pick a color or upload</div>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              {AVATARS.map((a, i) => (
                <button key={i} onClick={() => { setAvatarIdx(i); setPicking(false); }}
                  aria-label={'Avatar ' + (i + 1)}
                  style={{
                    width: 38, height: 38, borderRadius: 19, padding: 0,
                    background: a.grad, color: '#0F1114',
                    border: avatarIdx === i ? '2px solid var(--fg)' : '2px solid transparent',
                    boxShadow: avatarIdx === i ? '0 0 0 2px oklch(from var(--accent-b) l c h / 0.5)' : 'none',
                    fontFamily: 'Geist, Inter, sans-serif', fontWeight: 700, fontSize: 13, letterSpacing: '-0.02em',
                    cursor: 'pointer', display: 'grid', placeItems: 'center',
                  }}>{initials}</button>
              ))}
              <button onClick={() => setPicking(false)} aria-label="Upload photo"
                style={{
                  width: 38, height: 38, borderRadius: 19, padding: 0,
                  background: 'var(--bg-elev-2)', color: 'var(--fg-muted)',
                  border: '1px dashed var(--border)', cursor: 'pointer',
                  display: 'grid', placeItems: 'center',
                }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 4v12m0 0-4-4m4 4 4-4M4 20h16"/></svg>
              </button>
            </div>
          </div>
        )}
      </div>

      <SectionTitle sub="Peer-to-peer. End-to-end encrypted. No server.">Sync &amp; devices</SectionTitle>
      <Stack>
        <SettingRow title="Sync devices" subtitle="Pair this browser with your other devices using a DIDComm invitation." onClick={() => go('sync')}/>
        <SettingRow title="Customize profile" subtitle="Name, avatar, and theme for this browser profile." onClick={() => setEditing(true)}/>
        <SettingRow title="Import bookmarks & settings" subtitle="From Chrome, Safari, Firefox, Edge, or an HTML bookmark file." onClick={() => {}}/>
      </Stack>
    </>
  );
}

// Screen: Sync Devices — P2P DIDComm invitation flow
function ScreenSync({ go }) {
  const [invite, setInvite] = React.useState('');
  const [generating, setGenerating] = React.useState(false);
  const [pasted, setPasted] = React.useState('');
  const [existing, setExisting] = React.useState('none');
  const [dataTypes, setDataTypes] = React.useState({
    bookmarks: true, history: true, tabs: false, settings: false, passwords: true, extensions: false,
  });
  const t = (k, v) => setDataTypes(s => ({ ...s, [k]: v }));

  function generateInvite() {
    setGenerating(true);
    setInvite('');
    setTimeout(() => {
      // Simulated DIDComm out-of-band invitation URL
      const id = [...crypto.getRandomValues(new Uint8Array(12))].map(b => b.toString(16).padStart(2,'0')).join('');
      setInvite(`didcomm://ajna.invite?oob=${id}&label=Ajna%20Desktop`);
      setGenerating(false);
    }, 900);
  }
  React.useEffect(() => { generateInvite(); }, []);

  return (
    <>
      <PageHeader
        route={SETTING_ROUTES.sync}
        title="Sync devices"
        subtitle="Ajna syncs peer-to-peer using DIDComm out-of-band invitations. Your data never touches a central server."
        back={{ label: 'You & Ajna', onClick: () => go('you') }}/>

      <SectionTitle sub="Active peer connections on this identity.">Paired devices</SectionTitle>
      <Stack>
        <SettingCard
          title="iPhone 15 · Ajna Mobile"
          subtitle="Last sync 2m ago · Bookmarks, History, Passwords"
          right={<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Chip color="green">Online</Chip><TextBtn>Manage</TextBtn></div>}/>
        <SettingCard
          title="MacBook Pro · Ajna Desktop"
          subtitle="Last sync 14m ago · Bookmarks, History, Passwords"
          right={<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Chip color="green">Online</Chip><TextBtn>Manage</TextBtn></div>}/>
        <SettingCard
          title="Work Laptop"
          subtitle="Last sync 3 days ago · Bookmarks only"
          right={<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><Chip>Idle</Chip><TextBtn>Manage</TextBtn></div>}/>
      </Stack>

      <SectionTitle sub="Share this invitation on the other device to pair.">Add a new device</SectionTitle>
      <div style={{
        padding: 18, background: 'var(--bg-elev)',
        border: '1px solid var(--border-soft)', borderRadius: 12,
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <Field label="Your invitation" hint={generating ? 'Generating a fresh invitation…' : 'Single-use · expires in 10 minutes'}>
          <div style={{ display: 'flex', gap: 8 }}>
            <Input value={generating ? 'Generating…' : invite} readOnly mono/>
            <TextBtn primary onClick={() => navigator.clipboard && navigator.clipboard.writeText(invite)} disabled={generating}>Copy</TextBtn>
            <TextBtn onClick={generateInvite}>↻</TextBtn>
          </div>
        </Field>

        <div style={{
          display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 14, alignItems: 'center',
          padding: '8px 0',
        }}>
          <div style={{ height: 1, background: 'var(--border-soft)' }}/>
          <span style={{ fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.1em' }}>OR PAIR WITH EXISTING</span>
          <div style={{ height: 1, background: 'var(--border-soft)' }}/>
        </div>

        <Field label="Paste an invitation from another device">
          <div style={{ display: 'flex', gap: 8 }}>
            <Input value={pasted} onChange={setPasted} placeholder="didcomm://ajna.invite?oob=…" mono/>
            <TextBtn primary disabled={!pasted}>Pair</TextBtn>
          </div>
        </Field>

        <Field label="Use an existing DIDComm connection">
          <div style={{ display: 'flex', gap: 8 }}>
            <Select value={existing} options={[
              { value: 'none', label: 'Choose a connection…' },
              { value: 'team', label: 'Team Workspace · did:peer:…ab14' },
            ]} onChange={setExisting}/>
            <TextBtn disabled={existing === 'none'}>Send request</TextBtn>
            <TextBtn>Refresh</TextBtn>
          </div>
        </Field>
      </div>

      <SectionTitle sub="Choose what syncs across all paired devices.">Data types</SectionTitle>
      <Stack>
        <SettingCard title="Bookmarks"   subtitle="Sync bookmarks and folders across devices." right={<Toggle on={dataTypes.bookmarks} onChange={v => t('bookmarks', v)}/>}/>
        <SettingCard title="History"     subtitle="Sync browsing history across devices." right={<Toggle on={dataTypes.history} onChange={v => t('history', v)}/>}/>
        <SettingCard title="Open tabs"   subtitle="See tabs open on other devices." right={<Toggle on={dataTypes.tabs} onChange={v => t('tabs', v)}/>}/>
        <SettingCard title="Passwords"   subtitle="Sync saved passwords and passkeys (end-to-end encrypted)." right={<Toggle on={dataTypes.passwords} onChange={v => t('passwords', v)}/>}/>
        <SettingCard title="Extensions"  subtitle="Keep the same extensions installed everywhere." right={<Toggle on={dataTypes.extensions} onChange={v => t('extensions', v)}/>}/>
        <SettingCard title="Settings"    subtitle="Sync browser settings across devices." right={<Toggle on={dataTypes.settings} onChange={v => t('settings', v)}/>}/>
      </Stack>

      <SectionTitle sub="All sync traffic is encrypted with keys derived from your device's DID.">Encryption</SectionTitle>
      <Stack>
        <SettingCard title="Device key" subtitle="did:key:z6Mkh…9kTp" right={<TextBtn>Rotate</TextBtn>}/>
        <SettingCard title="Recovery phrase" subtitle="A 24-word seed you can use to recover your identity on a new device." right={<TextBtn>Show</TextBtn>}/>
      </Stack>
    </>
  );
}

Object.assign(window, { ScreenYouAndAjna, ScreenSync });
