// Artist profile setup. Two modes:
//   - Onboarding: shown the first time a creator lands on the submit screen
//                 without an existing profile. Big intro text, rounded
//                 "fresh start" feel.
//   - Settings:   reachable from the profile screen later. Same form, less
//                 hand-holding copy.
//
// Form fields: artist name (required, 2-40 chars) + optional avatar image.
// Avatar gets cover-cropped to a square on the server (sharp, attention-
// based crop). Live preview here is a simple <img>.

function ArtistProfileForm({ me, dark, mode, onSaved }) {
  const existing = me.artistProfile;
  const [name, setName] = React.useState(existing?.name || '');
  const [avatarFile, setAvatarFile] = React.useState(null);
  // Raw file picked by the user — fed into the cropper modal. After
  // cropping, the result lands in `avatarFile` and gets uploaded.
  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', maxWidth: 560, margin: '0 auto' }}>
      {mode === 'onboarding' && (
        <div style={{ marginBottom: 24 }}>
          <div style={{
            fontSize: 12, opacity: 0.55, letterSpacing: 1.4,
            textTransform: 'uppercase', fontWeight: 700, marginBottom: 6,
          }}>
            Schritt 1 von 1
          </div>
          <h1 style={{ fontSize: 32, fontWeight: 800, letterSpacing: -0.7, margin: 0 }}>
            Wähle deinen Künstlernamen
          </h1>
          <p style={{ fontSize: 14, opacity: 0.65, marginTop: 8, lineHeight: 1.55 }}>
            Unter diesem Namen erscheinen deine Tracks ingame. Such dir was Schickes aus —
            kannst du später jederzeit ändern.
          </p>
        </div>
      )}
      {mode === 'settings' && (
        <h1 style={{ fontSize: 28, fontWeight: 800, letterSpacing: -0.6, margin: '0 0 22px' }}>
          Künstlerprofil
        </h1>
      )}

      <form onSubmit={handleSubmit}>
        <ApGlass dark={dark} radius={20} padding={28}>
          <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: dark ? '2px solid rgba(255,255,255,0.12)' : '2px solid rgba(0,0,0,0.08)',
              boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {/* Pick raw → open cropper. Cropper hands back a square
                  webp via setAvatarFile. */}
              <input type="file" accept="image/*" hidden
                onChange={e => {
                  const f = e.target.files?.[0];
                  if (f) setRawAvatarFile(f);
                  // Reset the input so picking the same file twice still fires.
                  e.target.value = '';
                }}/>
              {!currentAvatar && (
                <span style={{ fontSize: 28, fontWeight: 800, color: '#fff' }}>
                  {(name || me.name || '?').slice(0, 1).toUpperCase()}
                </span>
              )}
              <div style={{
                position: 'absolute', inset: 0,
                background: 'linear-gradient(180deg, transparent 60%, rgba(0,0,0,0.6))',
                display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
                paddingBottom: 8, fontSize: 10, color: '#fff', fontWeight: 700,
                letterSpacing: 0.4, textTransform: 'uppercase',
                opacity: 0.85,
              }}>
                Ändern
              </div>
            </label>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', opacity: 0.7, marginBottom: 6 }}>
                Profilbild
              </div>
              <div style={{ fontSize: 12.5, opacity: 0.6, 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: 'none', border: 'none', cursor: 'pointer', padding: 0,
                    color: '#f87171', fontSize: 12, fontWeight: 600, marginTop: 6,
                  }}
                >
                  Auswahl verwerfen
                </button>
              )}
            </div>
          </div>

          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase', opacity: 0.7, marginBottom: 8 }}>
              Künstlername
            </div>
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="z.B. Cinder Bloom"
              maxLength={40}
              style={{
                width: '100%', padding: '12px 14px', borderRadius: 12,
                background: dark ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.7)',
                border: dark ? '1px solid rgba(255,255,255,0.12)' : '1px solid rgba(0,0,0,0.08)',
                color: 'inherit', fontSize: 15, fontFamily: 'inherit', outline: 'none',
                boxSizing: 'border-box',
              }}
            />
            <div style={{ fontSize: 11.5, opacity: 0.5, marginTop: 6 }}>
              2-40 Zeichen. Erscheint überall, wo deine Tracks angezeigt werden.
            </div>
          </div>

          {err && <div style={{ color: '#f87171', fontSize: 13, marginBottom: 12 }}>{err}</div>}

          <button
            type="submit"
            disabled={busy || !name.trim() || name.trim().length < 2}
            style={{
              width: '100%', padding: '13px 18px', borderRadius: 12,
              border: 'none', cursor: busy ? 'not-allowed' : 'pointer',
              background: name.trim().length >= 2 && !busy
                ? 'linear-gradient(135deg, #ff4d8d, #7c3aed)'
                : (dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)'),
              color: '#fff', fontSize: 14, fontWeight: 700,
              opacity: name.trim().length >= 2 && !busy ? 1 : 0.5,
              boxShadow: name.trim().length >= 2 && !busy
                ? '0 8px 24px rgba(255,77,141,0.35)' : 'none',
            }}
          >
            {busy ? 'Speichere…' : (mode === 'onboarding' ? 'Profil anlegen & weiter' : 'Speichern')}
          </button>
        </ApGlass>
      </form>

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

window.ArtistProfileForm = ArtistProfileForm;
