// Onboarding flow — 3 steps: username → business info → avatar/done
// Progressive; skippable after step 1.

const { useState: useS_onb, useEffect: useE_onb } = React;

function OnboardingFlow({ onComplete }) {
  const [step, setStep] = useS_onb(0);
  const [username, setUsername] = useS_onb('');
  const [businessName, setBusinessName] = useS_onb('');
  const [bio, setBio] = useS_onb('');
  const [whatsapp, setWhatsapp] = useS_onb('+252 ');
  const [avatarColor, setAvatarColor] = useS_onb(0);

  const avatarPalette = [
    'linear-gradient(135deg,#F6A96B 0%,#D96B3A 100%)',
    'linear-gradient(135deg,#8EB8E8 0%,#4A7FBF 100%)',
    'linear-gradient(135deg,#A8D89F 0%,#4F9B5F 100%)',
    'linear-gradient(135deg,#E8A8D4 0%,#B85A9B 100%)',
    'linear-gradient(135deg,#F5D97F 0%,#D4A041 100%)',
    'linear-gradient(135deg,#C8B8E8 0%,#7A5FBF 100%)',
  ];

  const usernameValid = /^[a-z0-9_]{3,20}$/.test(username);
  const step1Valid = businessName.trim().length >= 2 && whatsapp.replace(/\D/g, '').length >= 9;

  const finish = () => {
    onComplete({
      username, businessName, bio: bio || 'Welcome to my shop.',
      whatsapp, avatarBg: avatarPalette[avatarColor],
      avatarInitial: (businessName[0] || username[0] || 'H').toUpperCase(),
      socials: [], links: [], location: 'Somalia',
    });
  };

  // Header
  const Header = ({ back, skip }) => (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '60px 20px 12px', height: 60, boxSizing: 'border-box',
    }}>
      {back ? <IconButton icon={<IconBack size={20}/>} onClick={() => setStep(step - 1)} bg="rgba(0,0,0,0.04)"/> : <div style={{width:36}}/>}
      <div style={{ display: 'flex', gap: 6 }}>
        {[0,1,2].map(i => (
          <div key={i} style={{
            width: i === step ? 22 : 7, height: 7, borderRadius: 4,
            background: i <= step ? HUUL_TOKENS.color.accent : 'rgba(0,0,0,0.12)',
            transition: 'width 240ms, background 240ms',
          }}/>
        ))}
      </div>
      {skip
        ? <button onClick={finish} style={{
            border:'none', background:'transparent', color:HUUL_TOKENS.color.accent,
            fontSize:15, fontWeight:500, fontFamily:HUUL_TOKENS.font.stack, cursor:'pointer',
          }}>Skip</button>
        : <div style={{width:36}}/>}
    </div>
  );

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Header back={step > 0} skip={step === 2}/>

      <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px 40px', position: 'relative' }}>
        {step === 0 && (
          <div style={{ animation: 'fade 320ms ease' }}>
            <div style={{ marginTop: 24 }}>
              <h1 style={{
                fontSize: 34, fontWeight: 700, letterSpacing: -0.8,
                margin: 0, lineHeight: 1.1,
              }}>Pick your username</h1>
              <p style={{
                fontSize: 16, color: HUUL_TOKENS.color.ink3, lineHeight: 1.45,
                margin: '10px 0 28px',
              }}>This is your shop's link. You can share it anywhere.</p>
            </div>

            <TextField
              value={username}
              onChange={(v) => setUsername(v.toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20))}
              placeholder="yourname"
              autoFocus
              prefix="huul.so/"
              suffix={username && (
                usernameValid
                  ? <div style={{ color: HUUL_TOKENS.color.success }}><IconCheck size={20}/></div>
                  : <div style={{ color: HUUL_TOKENS.color.ink4 }}><IconX size={18}/></div>
              )}
            />

            <div style={{
              marginTop: 14, padding: '0 4px',
              fontSize: 13, color: HUUL_TOKENS.color.ink3, lineHeight: 1.5,
            }}>
              {username.length === 0
                ? '3–20 characters. Lowercase letters, numbers, underscore.'
                : usernameValid
                  ? <span style={{color:HUUL_TOKENS.color.success}}>Nice — huul.so/{username} is available.</span>
                  : 'Only lowercase letters, numbers and _. At least 3 characters.'}
            </div>

            <div style={{ marginTop: 'auto' }}/>
          </div>
        )}

        {step === 1 && (
          <div style={{ animation: 'fade 320ms ease' }}>
            <div style={{ marginTop: 24 }}>
              <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: -0.8, margin: 0, lineHeight: 1.1 }}>
                About your shop
              </h1>
              <p style={{ fontSize: 16, color: HUUL_TOKENS.color.ink3, lineHeight: 1.45, margin: '10px 0 28px' }}>
                Buyers will see this on your profile.
              </p>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <Label>Business name</Label>
                <TextField value={businessName} onChange={setBusinessName} placeholder="e.g. Hoodo Goods" autoFocus/>
              </div>
              <div>
                <Label>Short bio</Label>
                <TextField value={bio} onChange={(v) => setBio(v.slice(0,120))} placeholder="What do you sell? Where do you deliver?" multiline rows={3}/>
                <div style={{ textAlign: 'right', fontSize: 12, color: HUUL_TOKENS.color.ink3, marginTop: 4 }}>
                  {bio.length}/120
                </div>
              </div>
              <div>
                <Label>WhatsApp number</Label>
                <TextField value={whatsapp} onChange={setWhatsapp} placeholder="+252 ..."/>
                <div style={{ fontSize: 13, color: HUUL_TOKENS.color.ink3, marginTop: 6, padding: '0 4px' }}>
                  Buyers will use this to contact you about products.
                </div>
              </div>
            </div>
          </div>
        )}

        {step === 2 && (
          <div style={{ animation: 'fade 320ms ease' }}>
            <div style={{ marginTop: 24 }}>
              <h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: -0.8, margin: 0, lineHeight: 1.1 }}>
                Pick a color
              </h1>
              <p style={{ fontSize: 16, color: HUUL_TOKENS.color.ink3, lineHeight: 1.45, margin: '10px 0 28px' }}>
                You can upload a photo later.
              </p>
            </div>

            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 16, marginBottom: 32 }}>
              <div style={{
                width: 128, height: 128, borderRadius: 64,
                background: avatarPalette[avatarColor],
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontSize: 56, fontWeight: 600, letterSpacing: -1,
                boxShadow: '0 8px 24px rgba(0,0,0,0.12), inset 0 0 0 4px rgba(255,255,255,0.9)',
                transition: 'background 300ms',
              }}>{(businessName[0] || username[0] || 'H').toUpperCase()}</div>
            </div>

            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10,
              padding: '0 4px',
            }}>
              {avatarPalette.map((c, i) => (
                <button key={i} onClick={() => setAvatarColor(i)} style={{
                  aspectRatio: '1', border: 'none', borderRadius: 16, background: c,
                  cursor: 'pointer', padding: 0,
                  boxShadow: avatarColor === i
                    ? `0 0 0 3px #fff, 0 0 0 5px ${HUUL_TOKENS.color.accent}`
                    : '0 2px 6px rgba(0,0,0,0.08)',
                  transform: avatarColor === i ? 'scale(1.05)' : 'scale(1)',
                  transition: 'transform 160ms, box-shadow 160ms',
                }}/>
              ))}
            </div>

            <div style={{
              marginTop: 40, padding: 16, background: 'rgba(10,132,255,0.08)',
              borderRadius: 14, display: 'flex', gap: 12, alignItems: 'flex-start',
            }}>
              <div style={{ color: HUUL_TOKENS.color.accent, marginTop: 2 }}><IconSparkle size={20}/></div>
              <div style={{ fontSize: 14, color: HUUL_TOKENS.color.ink2, lineHeight: 1.45 }}>
                You're almost done. After this you can add products and share your shop link.
              </div>
            </div>
          </div>
        )}
      </div>

      <div style={{ padding: '12px 20px 28px', background: 'transparent' }}>
        <PrimaryButton
          onClick={() => {
            if (step === 0 && usernameValid) setStep(1);
            else if (step === 1 && step1Valid) setStep(2);
            else if (step === 2) finish();
          }}
          disabled={(step === 0 && !usernameValid) || (step === 1 && !step1Valid)}
          icon={step === 2 ? null : <IconArrowR size={20}/>}
          style={{ flexDirection: 'row-reverse' }}
        >
          {step === 2 ? 'Open my shop' : 'Continue'}
        </PrimaryButton>
      </div>
    </div>
  );
}

function Label({ children }) {
  return <div style={{
    fontSize: 13, fontWeight: 500, color: HUUL_TOKENS.color.ink3,
    marginBottom: 6, padding: '0 4px', textTransform: 'uppercase', letterSpacing: 0.3,
  }}>{children}</div>;
}

window.OnboardingFlow = OnboardingFlow;
window.HuulLabel = Label;
