// onboarding.jsx — 3-step welcome flow
// Shows on first launch; persists completion via window.parent edit-mode protocol
// + localStorage fallback so it doesn't re-show after restart.

function Onboarding({ theme, family, onAddFamily, onDone }) {
  const [step, setStep] = React.useState(0);
  const [mood, setMood] = React.useState('bien');
  const [stage, setStage] = React.useState('escolar');
  const [memberName, setMemberName] = React.useState('');
  const [addedMembers, setAddedMembers] = React.useState([]);
  const [chosenPillars, setChosenPillars] = React.useState(
    Object.keys(PILLARS).slice(0, 4)
  );

  const finish = () => {
    try { localStorage.setItem('mamaflow.onboarded', '1'); } catch (e) {}
    onDone({ mood, stage, pillars: chosenPillars });
  };

  const togglePillar = (id) => {
    setChosenPillars(arr =>
      arr.includes(id) ? arr.filter(x => x !== id) : [...arr, id]
    );
  };

  const submitMember = () => {
    const v = memberName.trim();
    if (!v) return;
    onAddFamily(v);
    setAddedMembers(a => [...a, v]);
    setMemberName('');
  };

  const steps = [
    { title: '¿Cómo te sientes hoy?', sub: 'MamaFlow no te empuja a hacer más. Se ajusta a cómo amaneciste.' },
    { title: '¿Qué etapa estás viviendo?', sub: 'Cambia cómo te hablo y qué te sugiero. Puedes mezclar después.' },
    { title: '¿Quién más está en tu día?', sub: 'Pareja, hijas/os, quien comparte la carga. Puedes saltar este paso.' },
    { title: 'Tus áreas importantes', sub: '“Tú” es sagrado. Si lo eliges, te aviso cuando lleva días en cero.' },
  ];

  const cur = steps[step];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200,
      background: 'linear-gradient(180deg, #FFE9DC 0%, #FBD5D5 60%, #F5C3CB 100%)',
      display: 'flex', flexDirection: 'column',
      padding: '60px 20px 28px',
      fontFamily: 'inherit',
    }}>
      {/* Progress dots */}
      <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginBottom: 22 }}>
        {steps.map((_, i) => (
          <div key={i} style={{
            width: i === step ? 24 : 6, height: 6, borderRadius: 3,
            background: i <= step ? '#C9626B' : 'rgba(201,98,107,0.25)',
            transition: 'width .3s ease, background .3s ease',
          }} />
        ))}
      </div>

      {/* Logo wordmark */}
      <div style={{
        fontSize: 12, fontWeight: 700, letterSpacing: 2,
        color: '#8E4E5B', textAlign: 'center', marginBottom: 6,
      }}>🌸 MAMAFLOW</div>
      <div style={{
        fontSize: 10, fontWeight: 600, letterSpacing: 2.5,
        color: 'rgba(142,78,91,0.6)', textAlign: 'center', marginBottom: 22,
      }}>· MENOS, SIN CULPA ·</div>

      {/* Step header */}
      <div style={{
        fontSize: 24, fontWeight: 700, color: '#2A1818',
        letterSpacing: -0.4, lineHeight: 1.2, marginBottom: 8,
        textWrap: 'pretty',
      }}>{cur.title}</div>
      <div style={{
        fontSize: 14, color: '#6B4B4B', marginBottom: 24, lineHeight: 1.45,
      }}>{cur.sub}</div>

      {/* Step body */}
      <div style={{ flex: 1, overflow: 'auto' }}>
        {step === 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
            {MOODS.map(m => {
              const active = m.id === mood;
              return (
                <button key={m.id} onClick={() => setMood(m.id)}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    background: active ? 'white' : 'rgba(255,255,255,0.55)',
                    border: `1.5px solid ${active ? '#C9626B' : 'rgba(255,255,255,0.6)'}`,
                    borderRadius: 16, padding: '16px 12px',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                    fontFamily: 'inherit',
                    boxShadow: active ? '0 4px 14px rgba(201,98,107,0.18)' : 'none',
                    transition: 'all .2s ease',
                  }}>
                  <span style={{ fontSize: 30 }}>{m.emoji}</span>
                  <span style={{
                    fontSize: 13, fontWeight: 600, color: '#2A1818',
                    letterSpacing: -0.05,
                  }}>{m.label}</span>
                </button>
              );
            })}
          </div>
        )}

        {step === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {STAGES.map(s => {
              const active = s.id === stage;
              return (
                <button key={s.id} onClick={() => setStage(s.id)}
                  style={{
                    appearance: 'none', cursor: 'pointer', textAlign: 'left',
                    background: active ? 'white' : 'rgba(255,255,255,0.55)',
                    border: `1.5px solid ${active ? '#C9626B' : 'rgba(255,255,255,0.6)'}`,
                    borderRadius: 14, padding: '12px 14px',
                    display: 'flex', alignItems: 'center', gap: 12,
                    fontFamily: 'inherit',
                    boxShadow: active ? '0 4px 14px rgba(201,98,107,0.18)' : 'none',
                  }}>
                  <span style={{ fontSize: 24 }}>{s.emoji}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: '#2A1818' }}>{s.label}</div>
                    <div style={{ fontSize: 11.5, color: '#6B4B4B', marginTop: 1 }}>{s.sub}</div>
                  </div>
                </button>
              );
            })}
          </div>
        )}

        {step === 2 && (
          <div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
              <input value={memberName} onChange={(e) => setMemberName(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && submitMember()}
                placeholder="Ej. Mateo, Mamá, Pareja…"
                style={{
                  flex: 1, padding: '13px 14px',
                  background: 'white', border: '1.5px solid rgba(255,255,255,0.8)',
                  borderRadius: 12,
                  fontSize: 14, fontFamily: 'inherit',
                  outline: 'none', color: '#2A1818',
                }} />
              <button onClick={submitMember} disabled={!memberName.trim()}
                style={{
                  appearance: 'none', cursor: memberName.trim() ? 'pointer' : 'default',
                  background: '#C9626B', color: 'white',
                  border: 'none', borderRadius: 12,
                  padding: '0 18px', fontSize: 14, fontWeight: 600,
                  opacity: memberName.trim() ? 1 : 0.5,
                  fontFamily: 'inherit',
                }}>Añadir</button>
            </div>

            <div style={{
              fontSize: 11, fontWeight: 700, letterSpacing: 1.2,
              color: '#8E4E5B', marginBottom: 10,
            }}>YA EN TU FAMILIA</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
              {family.map(m => (
                <div key={m.id} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  background: 'white', borderRadius: 999,
                  padding: '6px 12px 6px 6px',
                  fontSize: 13, fontWeight: 600, color: '#2A1818',
                  boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
                }}>
                  <Avatar member={m} size={22} />
                  {m.name}
                </div>
              ))}
            </div>
          </div>
        )}

        {step === 3 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {Object.keys(PILLARS).map(pid => {
              const p = PILLARS[pid];
              const active = chosenPillars.includes(pid);
              return (
                <button key={pid} onClick={() => togglePillar(pid)}
                  style={{
                    appearance: 'none', cursor: 'pointer',
                    background: active ? p.bg : 'rgba(255,255,255,0.55)',
                    border: `1.5px solid ${active ? p.border : 'rgba(255,255,255,0.6)'}`,
                    borderRadius: 14, padding: '11px 14px',
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    fontFamily: 'inherit',
                    transition: 'all .15s ease',
                  }}>
                  <span style={{ fontSize: 18 }}>{p.emoji}</span>
                  <span style={{
                    fontSize: 14, fontWeight: 600, color: active ? p.text : '#6B4B4B',
                    letterSpacing: -0.1,
                  }}>{p.label}</span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Footer */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingTop: 16 }}>
        {step > 0 && (
          <button onClick={() => setStep(step - 1)}
            style={{
              appearance: 'none', cursor: 'pointer',
              background: 'transparent', border: 'none',
              color: '#6B4B4B', fontSize: 14, fontWeight: 600,
              padding: '14px 8px', fontFamily: 'inherit',
            }}>← Atrás</button>
        )}
        <div style={{ flex: 1 }} />
        <button onClick={step === steps.length - 1 ? finish : () => setStep(step + 1)}
          style={{
            appearance: 'none', cursor: 'pointer',
            background: '#C9626B', color: 'white',
            border: 'none', borderRadius: 14,
            padding: '14px 22px', fontSize: 14.5, fontWeight: 700,
            letterSpacing: -0.1, fontFamily: 'inherit',
            boxShadow: '0 4px 14px rgba(201,98,107,0.3)',
          }}>{step === steps.length - 1 ? 'Empezar 🌸' : 'Siguiente →'}</button>
      </div>
    </div>
  );
}

Object.assign(window, { Onboarding });
