// Sisyphus — Onboarding wizard
// Shows on first visit or when user hasn't completed setup.
// 3 steps: Nombre → Sueldo → Tarjetas

const { useState: obS, useEffect: obE } = React;
const obSeed = window.SisyphusSeed;
const ObIcon = window.Icon;

function OnboardingWizard({ onComplete, existingName }) {
  const [step,     setStep]     = obS(0);
  const [name,     setName]     = obS(existingName && existingName !== 'Adolfo' ? existingName : '');
  const [sueldo,      setSueldo]      = obS('');
  const [sueldoCcy,   setSueldoCcy]   = obS('ARS');
  const [sueldoFreq,  setSueldoFreq]  = obS('mensual');
  const [freelance,   setFreelance]   = obS('');
  const [freelanceCcy,setFreelanceCcy]= obS('ARS');
  const [freelanceFreq,setFreelanceFreq]= obS('mensual');
  const [photo,    setPhoto]    = obS(null);
  const [cards,    setCards]    = obS([
    { id:'sant-amex', name:'Santander AMEX', bank:'Santander', network:'AMEX', fechaCierre:15, fechaVencimiento:5,  limite:800000,  acumulado:0, active:true },
    { id:'sant-visa', name:'Santander VISA', bank:'Santander', network:'VISA', fechaCierre:20, fechaVencimiento:10, limite:600000,  acumulado:0, active:true },
    { id:'gal-amex',  name:'Galicia AMEX',  bank:'Galicia',   network:'AMEX', fechaCierre:18, fechaVencimiento:8,  limite:1000000, acumulado:0, active:true },
    { id:'gal-visa',  name:'Galicia VISA',  bank:'Galicia',   network:'VISA', fechaCierre:22, fechaVencimiento:12, limite:500000,  acumulado:0, active:true },
  ]);

  const steps = [
    { icon: 'spark',   color:'#a78bfa', bg:'rgba(167,139,250,0.12)', title: '¡Hola! Bienvenido a Sisyphus', sub: 'Tu app de finanzas personales. Tardás 1 minuto en configurarla.' },
    { icon: 'user',    color:'#f9a8d4', bg:'rgba(249,168,212,0.12)', title: 'Tu perfil',                    sub: 'Ponle cara a tu cuenta. Podés saltearlo y hacerlo después.' },
    { icon: 'wallet',  color:'#34d399', bg:'rgba(52,211,153,0.12)',  title: '¿Cuánto ganás por mes?',       sub: 'Usamos esto para calcular tu presupuesto y proyecciones.' },
    { icon: 'cards',   color:'#818cf8', bg:'rgba(129,140,248,0.12)', title: 'Tus tarjetas de crédito',      sub: 'Activá las que tenés. Podés editar límites y fechas ahora o después.' },
  ];

  const netGrad = {
    VISA:       'linear-gradient(135deg, #1a1a6e, #4c1d95)',
    AMEX:       'linear-gradient(135deg, #0c4a6e, #0369a1)',
    Mastercard: 'linear-gradient(135deg, #7f1d1d, #b91c1c)',
  };

  function finish() {
    const sueldoNum = parseFloat(sueldo.replace(/\./g,'').replace(/,/g,'.')) || 0;
    const freelanceNum = parseFloat(freelance.replace(/\./g,'').replace(/,/g,'.')) || 0;
    onComplete({
      userName: name.trim() || 'Usuario',
      photo,
      sueldo: sueldoNum,
      sueldoCcy,
      sueldoFreq,
      freelance: freelanceNum,
      freelanceCcy,
      freelanceFreq,
      tarjetas: cards.filter(c => c.active),
    });
  }

  const canNext = step === 0 ? name.trim().length > 0 : step === 1 ? true : step === 2 ? (parseFloat(sueldo.replace(/\./g,'').replace(/,/g,'.')) || 0) > 0 : true;

  const inputStyle = {
    width:'100%', padding:'13px 16px', borderRadius:12, boxSizing:'border-box',
    background:'rgba(255,255,255,0.06)', border:'1px solid var(--border-strong)',
    color:'var(--text)', fontFamily:'Space Grotesk, sans-serif',
    fontSize:18, fontWeight:600, outline:'none', transition:'border-color 0.15s',
  };

  return (
    <div style={{
      position:'fixed', inset:0, zIndex:9000,
      background:'rgba(5,3,13,0.95)', backdropFilter:'blur(20px)',
      display:'flex', alignItems:'center', justifyContent:'center', padding:24,
      animation:'fadeIn 0.3s ease',
    }}>
      <div style={{
        width:'100%', maxWidth:480,
        background:'rgba(18,10,36,0.98)', backdropFilter:'blur(40px)',
        border:'1px solid var(--border-strong)', borderRadius:28,
        padding:'36px 32px 32px',
        boxShadow:'0 40px 80px rgba(0,0,0,0.7)',
        animation:'slideUp 0.4s cubic-bezier(0.2,0.8,0.2,1)',
      }}>
        {/* Progress dots */}
        <div style={{ display:'flex', gap:6, marginBottom:32, justifyContent:'center' }}>
          {steps.map((_,i) => (
            <div key={i} style={{
              height:4, borderRadius:999,
              width: i === step ? 28 : 8,
              background: i <= step ? 'var(--accent-bright)' : 'rgba(255,255,255,0.12)',
              transition:'all 0.3s cubic-bezier(0.2,0.8,0.2,1)',
            }} />
          ))}
        </div>

        {/* Step header */}
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <div style={{
            width:64, height:64, borderRadius:20, marginBottom:16,
            background: steps[step].bg,
            border: `1px solid ${steps[step].color}33`,
            display:'flex', alignItems:'center', justifyContent:'center',
            margin:'0 auto 16px',
            boxShadow: `0 8px 24px ${steps[step].color}22`,
          }}>
            <ObIcon name={steps[step].icon} size={28} strokeWidth={1.6} style={{ color: steps[step].color }} />
          </div>
          <div style={{ fontFamily:'Space Grotesk, sans-serif', fontSize:22, fontWeight:700, letterSpacing:'-0.02em', marginBottom:8 }}>{steps[step].title}</div>
          <div style={{ fontSize:14, color:'var(--text-3)', lineHeight:1.5 }}>{steps[step].sub}</div>
        </div>

        {/* Step 0: Nombre */}
        {step === 0 && (
          <div>
            <div style={{ fontSize:11, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.12em', fontWeight:600, marginBottom:8 }}>Tu nombre</div>
            <input
              autoFocus
              value={name}
              onChange={e => setName(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && canNext && setStep(1)}
              placeholder="Adolfo, Juanchi, lo que prefieras..."
              style={inputStyle}
              onFocus={e => e.target.style.borderColor='var(--accent)'}
              onBlur={e => e.target.style.borderColor='var(--border-strong)'}
            />
          </div>
        )}

        {/* Step 1: Foto de perfil */}
        {step === 1 && (
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:16 }}>
            {/* Avatar preview */}
            <div style={{ position:'relative' }}>
              <div style={{ width:96, height:96, borderRadius:'50%', overflow:'hidden', background:'var(--accent-dim)', border:'2px solid var(--border-strong)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                {photo
                  ? <img src={photo} style={{ width:'100%', height:'100%', objectFit:'cover' }} alt="perfil" />
                  : <ObIcon name="user" size={36} strokeWidth={1.4} style={{ color:'var(--accent-bright)' }} />
                }
              </div>
              {photo && (
                <button onClick={() => setPhoto(null)} style={{ position:'absolute', top:-4, right:-4, width:22, height:22, borderRadius:'50%', background:'var(--red)', border:'2px solid rgba(8,5,15,1)', color:'white', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'inherit', fontSize:11, fontWeight:700 }}>✕</button>
              )}
            </div>
            <label style={{ cursor:'pointer', fontSize:13, fontWeight:600, color:'var(--accent-bright)', padding:'10px 22px', borderRadius:12, background:'var(--accent-dim)', border:'1px solid var(--border-strong)', display:'flex', alignItems:'center', gap:8 }}>
              <ObIcon name="user" size={14} strokeWidth={2} />
              {photo ? 'Cambiar foto' : 'Elegir foto'}
              <input type="file" accept="image/*" style={{ display:'none' }} onChange={e => {
                const file = e.target.files?.[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = ev => setPhoto(ev.target.result);
                reader.readAsDataURL(file);
              }} />
            </label>
            <div style={{ fontSize:12, color:'var(--text-3)', textAlign:'center', lineHeight:1.5 }}>
              Podés subir una foto ahora o saltear este paso.<br/>Siempre podés hacerlo desde Configuración.
            </div>
          </div>
        )}

        {/* Step 2: Ingresos */}
        {step === 2 && (
          <div style={{ display:'flex', flexDirection:'column', gap:18 }}>

            {/* Sueldo */}
            <div style={{ padding:'16px', borderRadius:14, background:'rgba(255,255,255,0.03)', border:'1px solid var(--border)' }}>
              <div style={{ fontSize:11, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.12em', fontWeight:600, marginBottom:12 }}>Sueldo / ingreso principal</div>
              <div style={{ display:'flex', gap:8, marginBottom:10 }}>
                {['ARS','USD'].map(c => (
                  <button key={c} onClick={() => setSueldoCcy(c)} style={{
                    flex:1, padding:'9px 0', borderRadius:9, border:`1px solid ${sueldoCcy===c ? 'var(--accent)' : 'var(--border)'}`,
                    background: sueldoCcy===c ? 'var(--accent-dim)' : 'transparent',
                    color: sueldoCcy===c ? 'var(--accent-bright)' : 'var(--text-3)',
                    fontFamily:'inherit', fontSize:13, fontWeight:700, cursor:'pointer', transition:'all 0.14s',
                  }}>{c}</button>
                ))}
              </div>
              <div style={{ position:'relative', marginBottom:10 }}>
                <span style={{ position:'absolute', left:14, top:'50%', transform:'translateY(-50%)', fontSize:16, fontWeight:600, color:'var(--text-3)' }}>{sueldoCcy==='USD' ? 'US$' : '$'}</span>
                <input
                  autoFocus type="text" inputMode="numeric"
                  value={sueldo}
                  onChange={e => setSueldo(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && canNext && setStep(2)}
                  placeholder={sueldoCcy==='USD' ? '3.000' : '1.850.000'}
                  style={{ ...inputStyle, paddingLeft: sueldoCcy==='USD' ? 46 : 32, fontSize:16 }}
                  onFocus={e => e.target.style.borderColor='var(--accent)'}
                  onBlur={e => e.target.style.borderColor='var(--border-strong)'}
                />
              </div>
              <div style={{ display:'flex', gap:6 }}>
                {['mensual','quincenal','semanal'].map(f => (
                  <button key={f} onClick={() => setSueldoFreq(f)} style={{
                    flex:1, padding:'7px 0', borderRadius:8, border:`1px solid ${sueldoFreq===f ? 'var(--accent)' : 'var(--border)'}`,
                    background: sueldoFreq===f ? 'var(--accent-dim)' : 'transparent',
                    color: sueldoFreq===f ? 'var(--accent-bright)' : 'var(--text-3)',
                    fontFamily:'inherit', fontSize:11, fontWeight:600, cursor:'pointer', transition:'all 0.14s', textTransform:'capitalize',
                  }}>{f}</button>
                ))}
              </div>
            </div>

            {/* Freelance */}
            <div style={{ padding:'16px', borderRadius:14, background:'rgba(255,255,255,0.03)', border:'1px solid var(--border)' }}>
              <div style={{ fontSize:11, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.12em', fontWeight:600, marginBottom:4 }}>
                Freelance / otros
                <span style={{ fontWeight:400, textTransform:'none', letterSpacing:0, fontSize:11, marginLeft:6 }}>(opcional)</span>
              </div>
              <div style={{ fontSize:11, color:'var(--text-3)', marginBottom:12 }}>Clientes, bonus, alquileres…</div>
              <div style={{ display:'flex', gap:8, marginBottom:10 }}>
                {['ARS','USD'].map(c => (
                  <button key={c} onClick={() => setFreelanceCcy(c)} style={{
                    flex:1, padding:'9px 0', borderRadius:9, border:`1px solid ${freelanceCcy===c ? 'var(--accent)' : 'var(--border)'}`,
                    background: freelanceCcy===c ? 'var(--accent-dim)' : 'transparent',
                    color: freelanceCcy===c ? 'var(--accent-bright)' : 'var(--text-3)',
                    fontFamily:'inherit', fontSize:13, fontWeight:700, cursor:'pointer', transition:'all 0.14s',
                  }}>{c}</button>
                ))}
              </div>
              <div style={{ position:'relative', marginBottom:10 }}>
                <span style={{ position:'absolute', left:14, top:'50%', transform:'translateY(-50%)', fontSize:16, fontWeight:600, color:'var(--text-3)' }}>{freelanceCcy==='USD' ? 'US$' : '$'}</span>
                <input
                  type="text" inputMode="numeric"
                  value={freelance}
                  onChange={e => setFreelance(e.target.value)}
                  placeholder="0"
                  style={{ ...inputStyle, paddingLeft: freelanceCcy==='USD' ? 46 : 32, fontSize:16 }}
                  onFocus={e => e.target.style.borderColor='var(--accent)'}
                  onBlur={e => e.target.style.borderColor='var(--border-strong)'}
                />
              </div>
              <div style={{ display:'flex', gap:6 }}>
                {['mensual','quincenal','semanal'].map(f => (
                  <button key={f} onClick={() => setFreelanceFreq(f)} style={{
                    flex:1, padding:'7px 0', borderRadius:8, border:`1px solid ${freelanceFreq===f ? 'var(--accent)' : 'var(--border)'}`,
                    background: freelanceFreq===f ? 'var(--accent-dim)' : 'transparent',
                    color: freelanceFreq===f ? 'var(--accent-bright)' : 'var(--text-3)',
                    fontFamily:'inherit', fontSize:11, fontWeight:600, cursor:'pointer', transition:'all 0.14s', textTransform:'capitalize',
                  }}>{f}</button>
                ))}
              </div>
            </div>

          </div>
        )}

        {/* Step 3: Tarjetas */}
        {step === 3 && (
          <div style={{ display:'flex', flexDirection:'column', gap:10, maxHeight:280, overflowY:'auto', paddingRight:4 }}>
            {cards.map((c, i) => (
              <div key={c.id} onClick={() => setCards(prev => prev.map((x,j) => j===i ? {...x, active: !x.active} : x))}
                style={{
                  display:'flex', alignItems:'center', gap:12, padding:'14px 16px', borderRadius:14, cursor:'pointer',
                  background: c.active ? 'rgba(167,139,250,0.08)' : 'rgba(255,255,255,0.03)',
                  border:`1px solid ${c.active ? 'var(--border-strong)' : 'var(--border)'}`,
                  transition:'all 0.15s',
                }}>
                {/* Mini card visual */}
                <div style={{ width:44, height:30, borderRadius:6, background: netGrad[c.network]||netGrad.VISA, display:'flex', alignItems:'center', justifyContent:'flex-end', padding:'0 7px', flexShrink:0 }}>
                  <span style={{ fontSize:7, fontWeight:900, color:'rgba(255,255,255,0.9)', letterSpacing:'0.05em' }}>{c.network}</span>
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:13.5, fontWeight:600 }}>{c.name}</div>
                  <div style={{ fontSize:11, color:'var(--text-3)', marginTop:2 }}>Cierre día {c.fechaCierre} · Vto día {c.fechaVencimiento}</div>
                </div>
                <div style={{ width:22, height:22, borderRadius:6, border:`2px solid ${c.active ? 'var(--accent)' : 'rgba(255,255,255,0.2)'}`, background: c.active ? 'var(--accent)' : 'transparent', display:'flex', alignItems:'center', justifyContent:'center', transition:'all 0.15s', flexShrink:0 }}>
                  {c.active && <ObIcon name="check" size={12} strokeWidth={3} style={{ color:'var(--on-accent)' }} />}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Actions */}
        <div style={{ display:'flex', gap:10, marginTop:28 }}>
          {step > 0 && (
            <button onClick={() => setStep(s => s-1)} style={{ padding:'13px 18px', borderRadius:12, background:'transparent', border:'1px solid var(--border)', color:'var(--text-3)', cursor:'pointer', fontFamily:'inherit', fontSize:14, transition:'all 0.15s' }}>
              Atrás
            </button>
          )}
          <button
            onClick={() => step < steps.length-1 ? setStep(s => s+1) : finish()}
            disabled={!canNext}
            style={{
              flex:1, padding:'13px 0', borderRadius:12, fontSize:14, fontWeight:700,
              background: canNext ? 'linear-gradient(135deg, var(--accent-bright), var(--accent-deep))' : 'rgba(255,255,255,0.06)',
              color: canNext ? 'var(--on-accent)' : 'var(--text-3)',
              border:'none', cursor: canNext ? 'pointer' : 'not-allowed', fontFamily:'inherit',
              boxShadow: canNext ? '0 8px 24px rgba(139,92,246,0.4)' : 'none',
              transition:'all 0.2s',
            }}
          >
            {step < steps.length-1 ? 'Continuar →' : '¡Empezar a usar Sisyphus!'}
          </button>
        </div>

        {step === 2 && (
          <div style={{ textAlign:'center', marginTop:14 }}>
            <button onClick={finish} style={{ background:'none', border:'none', color:'var(--text-3)', fontSize:12, cursor:'pointer', fontFamily:'inherit' }}>
              Saltear — configurar después
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

window.OnboardingWizard = OnboardingWizard;
