// Desktop FIRST-RUN onboarding — a two-pane focused setup.
// Left: brand showcase with animated peer constellation.
// Right: 3 steps — Welcome → Profile (name + avatar) → Ready.
// The profile step writes the same localStorage keys the desktop Settings
// identity hero reads (ajna-profile-name / ajna-profile-avatar), so a name
// or color chosen here shows up in Settings → You & Ajna immediately.

const DFR_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)' },
];

// ── Animated brand panel (left) ──────────────────────────────
function DFRBrandPanel({ step }) {
  return (
    <div style={{
      width: 380, flexShrink: 0, position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(160deg, var(--bg-elev) 0%, var(--sidebar-bg) 100%)',
      borderRight: '1px solid var(--border-soft)',
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      padding: '40px 36px',
    }}>
      <style>{`
        @keyframes dfrOrbit { from { transform: rotate(0deg) } to { transform: rotate(360deg) } }
        @keyframes dfrFloat { 0%,100% { transform: translateY(0) } 50% { transform: translateY(-8px) } }
        @keyframes dfrPulse { 0%,100% { opacity: 0.5 } 50% { opacity: 1 } }
      `}</style>

      {/* ambient glow */}
      <div style={{
        position: 'absolute', top: '30%', left: '50%', transform: 'translate(-50%,-50%)',
        width: 360, height: 360, borderRadius: '50%',
        background: 'radial-gradient(circle, oklch(from var(--accent-a) l c h / 0.14), transparent 65%)',
        pointerEvents: 'none',
      }}/>

      {/* brand */}
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 10 }}>
        <AjnaMark size={22}/>
        <span style={{ fontSize: 16, fontFamily: 'Geist, Inter, sans-serif', fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--fg)' }}>Ajna</span>
      </div>

      {/* constellation */}
      <div style={{ position: 'relative', flex: 1, display: 'grid', placeItems: 'center' }}>
        <div style={{ position: 'relative', width: 220, height: 220, animation: 'dfrFloat 6s ease-in-out infinite' }}>
          {[88, 64, 40].map((r, i) => (
            <div key={i} style={{
              position: 'absolute', inset: 110 - r, width: r * 2, height: r * 2,
              borderRadius: '50%', border: '1px solid oklch(from var(--accent-b) l c h / ' + (0.18 - i * 0.04) + ')',
              animation: 'dfrOrbit ' + (26 - i * 6) + 's linear infinite' + (i % 2 ? ' reverse' : ''),
            }}>
              {[0, 1, 2].map(j => {
                const ang = (j / 3) * Math.PI * 2 + i;
                return (
                  <div key={j} style={{
                    position: 'absolute',
                    left: r + Math.cos(ang) * r - 4, top: r + Math.sin(ang) * r - 4,
                    width: 8, height: 8, borderRadius: 4,
                    background: j === 0 ? 'var(--accent-a)' : 'var(--accent-b)',
                    boxShadow: '0 0 10px oklch(from var(--accent-b) l c h / 0.7)',
                    animation: 'dfrPulse ' + (2 + j) + 's ease-in-out infinite',
                  }}/>
                );
              })}
            </div>
          ))}
          {/* center node */}
          <div style={{
            position: 'absolute', inset: 86, width: 48, height: 48, borderRadius: 16,
            background: 'var(--accent-grad)', display: 'grid', placeItems: 'center',
            color: '#0F1114', fontFamily: 'Geist, Inter, sans-serif', fontWeight: 700, fontSize: 22,
            boxShadow: '0 8px 30px oklch(from var(--accent-b) l c h / 0.5)',
          }}>A</div>
        </div>
      </div>

      {/* tagline */}
      <div style={{ position: 'relative' }}>
        <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.55 }}>
          A browser that owns its identity.<br/>Yours — end-to-end, peer-to-peer.
        </div>
        <div style={{ marginTop: 14, fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          Ed25519 · X25519 · DID:KEY
        </div>
      </div>
    </div>
  );
}

// ── Step dots ────────────────────────────────────────────────
function DFRDots({ step, total }) {
  return (
    <div style={{ display: 'flex', gap: 6 }}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} style={{
          width: i === step ? 20 : 6, height: 6, borderRadius: 3,
          background: i === step ? 'var(--accent-grad)' : 'var(--border)',
          transition: 'width 220ms, background 220ms',
        }}/>
      ))}
    </div>
  );
}

// ── Step 1: Welcome ──────────────────────────────────────────
function DFRWelcome({ onNext, onSkip }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 420 }}>
      <div style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 16 }}>Welcome</div>
      <div style={{ fontSize: 34, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.035em', lineHeight: 1.1, color: 'var(--fg)' }}>
        Let's set up <span style={{ background: 'var(--accent-grad)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>your Ajna</span>
      </div>
      <div style={{ fontSize: 14.5, color: 'var(--fg-muted)', lineHeight: 1.6, marginTop: 16 }}>
        No account, no email, no cloud. Your identity lives on this device and syncs privately to your others. Takes about a minute.
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 28 }}>
        {[
          { icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/></svg>, t: 'Create your profile', s: 'A name and avatar others see' },
          { 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 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5z"/></svg>, t: 'Generate your identity', s: 'A device-bound DID — never leaves you' },
          { icon: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="5" r="2"/><circle cx="5" cy="18" r="2"/><circle cx="19" cy="18" r="2"/><path d="M12 7v4M12 11 6 16M12 11l6 5"/></svg>, t: 'Connect your mesh', s: 'Optional — pair devices any time' },
        ].map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '13px 15px', background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12 }}>
            <span style={{ width: 32, height: 32, borderRadius: 9, background: 'oklch(from var(--accent-b) l c h / 0.14)', color: 'var(--accent-b)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>{r.icon}</span>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--fg)', fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em' }}>{r.t}</div>
              <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 1 }}>{r.s}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 32 }}>
        <button onClick={onNext} style={dfrPrimaryStyle}>Get started</button>
        <button onClick={onSkip} style={dfrGhostStyle}>Skip for now</button>
      </div>
    </div>
  );
}

// ── Step 2: Profile ──────────────────────────────────────────
function DFRProfile({ onNext, onBack, value, setValue }) {
  const [name, setName] = React.useState(value.name || '');
  const [handle, setHandle] = React.useState(value.handle || '');
  const [avatarIdx, setAvatarIdx] = React.useState(value.avatarIdx || 0);
  const inputRef = React.useRef(null);
  React.useEffect(() => { setTimeout(() => inputRef.current?.focus(), 100); }, []);

  const initials = name.trim().split(/\s+/).slice(0, 2).map(s => s[0] || '').join('').toUpperCase() || 'A';
  const grad = DFR_AVATARS[avatarIdx].grad;
  const valid = name.trim().length >= 1;
  const submit = () => {
    if (!valid) return;
    setValue({ name, handle, avatarIdx });
    try {
      localStorage.setItem('ajna-profile-name', name.trim());
      localStorage.setItem('ajna-profile-avatar', String(avatarIdx));
    } catch {}
    onNext();
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 440 }}>
      <div style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 14 }}>Step 2 · Profile</div>
      <div style={{ fontSize: 28, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.03em', lineHeight: 1.15, color: 'var(--fg)' }}>How should you appear?</div>
      <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.55, marginTop: 10 }}>Pick a name and avatar. You can change these any time in Settings → You &amp; Ajna.</div>

      {/* Avatar + picker */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginTop: 26 }}>
        <div style={{
          width: 84, height: 84, borderRadius: 42, flexShrink: 0,
          background: grad, display: 'grid', placeItems: 'center',
          color: '#0F1114', fontSize: 34, fontWeight: 600,
          fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em',
          boxShadow: '0 16px 44px -14px oklch(from var(--accent-b) l c h / 0.6)',
        }}>{initials}</div>
        <div>
          <div style={{ fontSize: 10.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 9 }}>Choose a color</div>
          <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap', maxWidth: 240 }}>
            {DFR_AVATARS.map((a, i) => (
              <button key={i} onClick={() => setAvatarIdx(i)} aria-label={'Avatar ' + (i + 1)} style={{
                width: 32, height: 32, borderRadius: 16, padding: 0, background: a.grad,
                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',
                cursor: 'pointer',
              }}/>
            ))}
            <button onClick={() => {}} aria-label="Upload photo" style={{
              width: 32, height: 32, borderRadius: 16, padding: 0,
              background: 'var(--bg-elev-2)', color: 'var(--fg-muted)',
              border: '1px dashed var(--border)', cursor: 'pointer', display: 'grid', placeItems: 'center',
            }}>
              <svg width="13" height="13" 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>

      {/* Fields */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 24 }}>
        <div>
          <label style={dfrLabelStyle}>Name</label>
          <input ref={inputRef} value={name} onChange={(e) => setName(e.target.value)} maxLength={40}
            placeholder="Your name"
            onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
            style={dfrFieldStyle(!!name)}/>
        </div>
        <div>
          <label style={dfrLabelStyle}>Handle <span style={{ color: 'var(--fg-dim)', fontWeight: 400 }}>· optional</span></label>
          <div style={{ position: 'relative' }}>
            <span style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: 'var(--accent-b)', fontFamily: 'JetBrains Mono, monospace', fontSize: 13.5 }}>@</span>
            <input value={handle} onChange={(e) => setHandle(e.target.value.replace(/^@/, '').replace(/[^a-z0-9-]/gi, '').toLowerCase())}
              placeholder="yourname" maxLength={80}
              style={{ ...dfrFieldStyle(!!handle), paddingLeft: 28, fontFamily: 'JetBrains Mono, monospace' }}/>
          </div>
          <div style={{ fontSize: 11, color: 'var(--fg-dim)', marginTop: 6, fontFamily: 'JetBrains Mono, monospace' }}>Others can find you with @your-handle · <span style={{ color: 'var(--fg-muted)' }}>did:key:z6Mkh…9kTp</span></div>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 30 }}>
        <button onClick={onBack} style={dfrGhostStyle}>Back</button>
        <button onClick={submit} disabled={!valid} style={{ ...dfrPrimaryStyle, opacity: valid ? 1 : 0.45, cursor: valid ? 'pointer' : 'default' }}>Continue</button>
      </div>
    </div>
  );
}

// ── Step 3: Ready ────────────────────────────────────────────
function DFRReady({ value, onDone }) {
  const initials = (value.name || 'A').trim().split(/\s+/).slice(0, 2).map(s => s[0] || '').join('').toUpperCase() || 'A';
  const grad = DFR_AVATARS[value.avatarIdx || 0].grad;
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', maxWidth: 420 }}>
      <div style={{ position: 'relative', width: 92, height: 92, marginBottom: 26 }}>
        <div style={{ position: 'absolute', inset: -10, borderRadius: '50%', background: 'radial-gradient(circle, oklch(from var(--accent-a) l c h / 0.3), transparent 70%)' }}/>
        <div style={{
          position: 'relative', width: 92, height: 92, borderRadius: 46,
          background: grad, display: 'grid', placeItems: 'center',
          color: '#0F1114', fontSize: 38, fontWeight: 600,
          fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em',
          boxShadow: '0 18px 50px -14px oklch(from var(--accent-b) l c h / 0.6)',
        }}>{initials}</div>
        <div style={{
          position: 'absolute', right: -4, bottom: -4, width: 30, height: 30, borderRadius: 15,
          background: 'oklch(0.72 0.15 155)', color: '#0F1114',
          border: '3px solid var(--sidebar-bg)', display: 'grid', placeItems: 'center',
        }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
        </div>
      </div>

      <div style={{ fontSize: 30, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.03em', lineHeight: 1.1, color: 'var(--fg)' }}>
        You're all set{value.name ? ', ' + value.name.trim().split(/\s+/)[0] : ''}.
      </div>
      <div style={{ fontSize: 14.5, color: 'var(--fg-muted)', lineHeight: 1.6, marginTop: 14 }}>
        Your identity is generated and stored on this device. Sync your other devices any time from Settings.
      </div>

      <div style={{ display: 'flex', gap: 8, marginTop: 22, flexWrap: 'wrap' }}>
        <span style={dfrPillStyle('oklch(0.72 0.15 155)')}>● Identity created</span>
        <span style={dfrPillStyle('var(--accent-b)')}>● Profile saved</span>
        <span style={dfrPillStyle('var(--fg-dim)')}>○ Mesh — set up later</span>
      </div>

      <div style={{ marginTop: 32 }}>
        <button onClick={onDone} style={dfrPrimaryStyle}>Start browsing</button>
      </div>
    </div>
  );
}

// shared inline styles
const dfrPrimaryStyle = {
  padding: '11px 22px', borderRadius: 10, border: 0,
  background: 'var(--accent-grad)', color: '#0F1114',
  fontSize: 13.5, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif',
  letterSpacing: '-0.01em', cursor: 'pointer',
};
const dfrGhostStyle = {
  padding: '11px 18px', borderRadius: 10,
  background: 'transparent', border: '1px solid var(--border)',
  color: 'var(--fg-muted)', fontSize: 13, fontFamily: 'inherit', cursor: 'pointer',
};
const dfrLabelStyle = {
  display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)',
  marginBottom: 6, letterSpacing: '0.02em',
};
const dfrFieldStyle = (filled) => ({
  width: '100%', boxSizing: 'border-box',
  padding: '11px 13px', borderRadius: 10,
  background: 'var(--bg-elev)',
  border: '1px solid ' + (filled ? 'oklch(from var(--accent-b) l c h / 0.4)' : 'var(--border-soft)'),
  color: 'var(--fg)', fontSize: 13.5, fontFamily: 'inherit', outline: 0,
});
const dfrPillStyle = (c) => ({
  fontSize: 11, padding: '5px 10px', borderRadius: 999,
  background: 'color-mix(in oklch, ' + c + ' 14%, transparent)',
  color: c, fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: '0.02em',
});

// ── Flow shell ───────────────────────────────────────────────
function DesktopFirstRun({ onComplete }) {
  const [step, setStep] = React.useState(0);
  const [value, setValue] = React.useState({});
  const total = 3;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'var(--sidebar-bg)', color: 'var(--fg)',
      display: 'flex', fontFamily: 'Inter, sans-serif',
    }}>
      <DFRBrandPanel step={step}/>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', padding: '40px clamp(36px, 6vw, 88px)' }}>
        {/* top bar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <DFRDots step={step} total={total}/>
          <button onClick={onComplete} style={{ background: 'transparent', border: 0, color: 'var(--fg-dim)', fontSize: 12.5, fontFamily: 'inherit', cursor: 'pointer' }}>Skip setup</button>
        </div>

        {/* step body */}
        <div key={step} style={{ flex: 1, display: 'flex', animation: 'dfrStepIn 280ms cubic-bezier(0.2,0.85,0.3,1) both' }}>
          <style>{`@keyframes dfrStepIn { from { opacity: 0; transform: translateY(10px) } to { opacity: 1; transform: translateY(0) } }`}</style>
          {step === 0 && <DFRWelcome onNext={() => setStep(1)} onSkip={onComplete}/>}
          {step === 1 && <DFRProfile onNext={() => setStep(2)} onBack={() => setStep(0)} value={value} setValue={setValue}/>}
          {step === 2 && <DFRReady value={value} onDone={onComplete}/>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DesktopFirstRun });
