// Artist profile setup. Two modes:
//   • onboarding — shown the first time a creator lands on submit
//                  without an existing profile. Big intro text.
//   • settings   — reachable later from the profile screen. Same
//                  form, less hand-holding copy.
//
// Form fields: stage name (required, 2-40 chars) + optional avatar
// image. Avatar runs through the cropper modal so the server gets a
// square WebP and the cover-fitting on a 256×256 circle is clean.

function ArtistProfileForm({ me, mode, onSaved }) {
  const existing = me.artistProfile;
  const [name, setName] = React.useState(existing?.name || '');
  const [avatarFile, setAvatarFile] = React.useState(null);
  const [rawAvatarFile, setRawAvatarFile] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const previewUrl = React.useMemo(
    () => avatarFile ? URL.createObjectURL(avatarFile) : null,
    [avatarFile],
  );
  React.useEffect(() => () => previewUrl && URL.revokeObjectURL(previewUrl), [previewUrl]);

  const currentAvatar = previewUrl || existing?.avatarUrl;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) return;
    setBusy(true); setErr('');
    try {
      const form = new FormData();
      form.append('name', name.trim());
      if (avatarFile) form.append('avatar', avatarFile);
      const { profile } = await Api.artist.putMe(form);
      Store.set({ me: { ...Store.get().me, artistProfile: profile, name: profile.name } });
      toast.success(mode === 'onboarding' ? 'Künstlerprofil angelegt!' : 'Profil aktualisiert.');
      onSaved && onSaved(profile);
    } catch (ex) {
      const msg = ex.message || 'Speichern fehlgeschlagen.';
      setErr(msg);
      toast.error(msg);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ padding: '40px 32px 140px', maxWidth: 560, margin: '0 auto' }}>
      {mode === 'onboarding' && (
        <div style={{ marginBottom: 24 }}>
          <Eyebrow style={{ marginBottom: 6 }}>Schritt 1 von 1</Eyebrow>
          <h1 style={{ fontWeight: 800, fontSize: 36, lineHeight: 1.05, letterSpacing: '-0.02em', margin: 0 }}>
            Wähle deinen Künstlernamen
          </h1>
          <p style={{ fontSize: 14.5, color: 'var(--fg-2)', marginTop: 8, lineHeight: 1.55, opacity: 0.85 }}>
            Unter diesem Namen erscheinen deine Tracks ingame. Such dir was Schickes aus —
            kannst du später jederzeit ändern.
          </p>
        </div>
      )}
      {mode === 'settings' && (
        <h1 style={{ fontWeight: 800, fontSize: 32, lineHeight: 1.05, letterSpacing: '-0.02em', margin: '0 0 22px' }}>
          Künstlerprofil
        </h1>
      )}

      <form onSubmit={handleSubmit}>
        <Glass radius={20} padding={28}>

          {/* Avatar uploader — click the circle to pick an image. */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 22 }}>
            <label style={{
              width: 96, height: 96, borderRadius: '50%', flexShrink: 0,
              cursor: 'pointer', position: 'relative', overflow: 'hidden',
              background: currentAvatar
                ? `url(${currentAvatar}) center/cover`
                : `linear-gradient(135deg, ${fallbackAvatar(me.identifier).join(', ')})`,
              border: '2px solid var(--border-medium)',
              boxShadow: '0 8px 24px rgba(20,8,40,0.45)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <input type="file" accept="image/*" hidden onChange={e => {
                const f = e.target.files?.[0];
                if (f) setRawAvatarFile(f);
                e.target.value = '';
              }}/>
              {!currentAvatar && (
                <span style={{ fontSize: 32, fontWeight: 800, color: 'var(--foam)' }}>
                  {(name || me.name || '?').slice(0, 1).toUpperCase()}
                </span>
              )}
              <div style={{
                position: 'absolute', inset: 0,
                background: 'linear-gradient(180deg, transparent 60%, rgba(17,7,36,0.7))',
                display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
                paddingBottom: 8, fontSize: 10, color: 'var(--foam)', fontWeight: 700,
                letterSpacing: '0.18em', textTransform: 'uppercase',
              }}>
                Ändern
              </div>
            </label>
            <div style={{ flex: 1, minWidth: 0 }}>
              <Eyebrow style={{ marginBottom: 6 }}>Profilbild</Eyebrow>
              <div style={{ fontSize: 12.5, color: 'var(--fg-3)', lineHeight: 1.45 }}>
                Optional. Wird automatisch auf 256×256 quadratisch zugeschnitten und als WebP gespeichert.
              </div>
              {avatarFile && (
                <button type="button" onClick={() => setAvatarFile(null)}
                  style={{
                    background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
                    color: 'var(--danger)', fontSize: 12, fontWeight: 600, marginTop: 6,
                  }}>
                  Auswahl verwerfen
                </button>
              )}
            </div>
          </div>

          {/* Stage name */}
          <div style={{ marginBottom: 18 }}>
            <Label hint="2-40 Zeichen. Erscheint überall, wo deine Tracks angezeigt werden.">
              Künstlername
            </Label>
            <TextInput value={name} onChange={e => setName(e.target.value)}
              placeholder="z. B. Cinder Bloom" maxLength={40}/>
          </div>

          {err && (
            <div style={{
              color: 'var(--danger)', fontSize: 13, marginBottom: 12,
              padding: '8px 12px', borderRadius: 10,
              background: 'rgba(255,110,138,0.10)',
              border: '1px solid rgba(255,110,138,0.45)',
            }}>{err}</div>
          )}

          <Button type="submit" variant="primary" size="lg"
            style={{ width: '100%' }}
            disabled={busy || !name.trim() || name.trim().length < 2}>
            {busy ? 'Speichere…' : (mode === 'onboarding' ? 'Profil anlegen & weiter' : 'Speichern')}
          </Button>
        </Glass>
      </form>

      {rawAvatarFile && (
        <ImageCropper
          file={rawAvatarFile}
          onCancel={() => setRawAvatarFile(null)}
          onCrop={(cropped) => {
            setAvatarFile(cropped);
            setRawAvatarFile(null);
          }}
        />
      )}
    </div>
  );
}

window.ArtistProfileForm = ArtistProfileForm;
