/* ============================================================
   CADENCE — Profile editor
   window.ProfilePage — edit display name, @handle, bio, links, avatar color.
   ============================================================ */
(function () {
  const { useState } = React;

  const AVATAR_COLORS = [
    'oklch(0.66 0.155 256)', 'oklch(0.70 0.15 295)', 'oklch(0.755 0.155 158)',
    'oklch(0.80 0.12 88)', 'oklch(0.66 0.19 22)', 'oklch(0.62 0.16 320)',
    'oklch(0.62 0.14 200)', 'oklch(0.62 0.17 28)',
  ];

  const LINK_FIELDS = [
    { key: 'website', label: 'Website', placeholder: 'https://yoursite.com' },
    { key: 'instagram', label: 'Instagram', placeholder: 'https://instagram.com/you' },
    { key: 'x', label: 'X / Twitter', placeholder: 'https://x.com/you' },
    { key: 'youtube', label: 'YouTube', placeholder: 'https://youtube.com/@you' },
  ];

  const ERRORS = {
    invalid_display_name: 'Enter a display name (1–60 characters).',
    invalid_handle: 'Handle must be 2–20 characters: letters, numbers, or underscores.',
  };

  function initials(name) {
    const parts = String(name || 'You').trim().split(/\s+/).filter(Boolean);
    if (parts.length === 0) return 'You';
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }

  const inputStyle = {
    width: '100%', boxSizing: 'border-box', background: 'var(--surface-2)',
    border: '1px solid var(--border-soft)', borderRadius: 10, color: 'var(--text)',
    fontSize: 14, padding: '10px 12px', outline: 'none',
  };
  const labelStyle = { fontSize: 12, color: 'var(--text-mute)', fontWeight: 600, display: 'block', marginBottom: 6 };

  function ProfilePage({ go }) {
    const cad = window.useCad();
    const u = cad.user || window.CAD.currentUser || {};

    const [displayName, setDisplayName] = useState(u.displayName || '');
    const [handle, setHandle] = useState(u.handle || '');
    const [bio, setBio] = useState(u.bio || '');
    const [avatarColor, setAvatarColor] = useState(u.avatarColor || AVATAR_COLORS[0]);
    const [links, setLinks] = useState({ ...(u.links || {}) });
    const [busy, setBusy] = useState(false);

    const setLink = (key, val) => setLinks((prev) => ({ ...prev, [key]: val }));

    const save = async () => {
      if (busy) return;
      if (!displayName.trim()) { window.toast({ kind: 'sell', title: 'Display name required', desc: 'Enter the name shown across the app.' }); return; }
      setBusy(true);
      try {
        const cleanLinks = {};
        Object.entries(links).forEach(([k, v]) => { if (v && String(v).trim()) cleanLinks[k] = String(v).trim(); });
        await cad.saveProfile({ displayName: displayName.trim(), handle, bio, avatarColor, links: cleanLinks });
        window.toast({ title: 'Profile saved', desc: 'Your profile has been updated.' });
        // Reload so the new name/handle propagate everywhere (artist, songs).
        setTimeout(() => window.location.reload(), 600);
      } catch (error) {
        window.toast({ kind: 'sell', title: 'Save failed', desc: ERRORS[error?.message] || 'Your profile could not be saved.' });
        setBusy(false);
      }
    };

    return (
      <div className="page" style={{ maxWidth: 720 }}>
        <div className="row between wrap" style={{ marginBottom: 22, gap: 14 }}>
          <div>
            <h1 className="page-title">Edit profile</h1>
            <div className="page-sub">This is how you appear across SoundExchange — separate from your private login.</div>
          </div>
          <button className="btn btn-ghost" onClick={() => go('discover')}>Back</button>
        </div>

        <div className="panel panel-pad">
          {/* avatar preview */}
          <div className="row gap16" style={{ alignItems: 'center', marginBottom: 20 }}>
            <div className="avatar" style={{ width: 64, height: 64, fontSize: 22, background: avatarColor }}>{initials(displayName)}</div>
            <div>
              <div style={{ fontWeight: 700, fontSize: 16 }}>{displayName || 'Your name'}</div>
              <div className="muted" style={{ fontSize: 13 }}>@{(handle || u.username || '').toLowerCase()}</div>
            </div>
          </div>

          <div className="col gap16">
            <div>
              <label style={labelStyle}>Display name</label>
              <input style={inputStyle} value={displayName} onChange={(e) => setDisplayName(e.target.value)} maxLength={60} placeholder="Your name" />
            </div>

            <div>
              <label style={labelStyle}>Public handle</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 12, top: 10, color: 'var(--text-mute)' }}>@</span>
                <input style={{ ...inputStyle, paddingLeft: 24 }} value={handle} onChange={(e) => setHandle(e.target.value)} placeholder={u.username || 'handle'} />
              </div>
              <div className="muted" style={{ fontSize: 11.5, marginTop: 5 }}>Shown publicly instead of your login username. Leave blank to use “{u.username}”.</div>
            </div>

            <div>
              <label style={labelStyle}>Bio</label>
              <textarea style={{ ...inputStyle, minHeight: 84, resize: 'vertical', fontFamily: 'inherit' }} value={bio} onChange={(e) => setBio(e.target.value)} maxLength={280} placeholder="Tell fans about your music…" />
              <div className="muted" style={{ fontSize: 11.5, marginTop: 5, textAlign: 'right' }}>{bio.length}/280</div>
            </div>

            <div>
              <label style={labelStyle}>Avatar color</label>
              <div className="row gap8 wrap">
                {AVATAR_COLORS.map((c) => (
                  <button key={c} type="button" onClick={() => setAvatarColor(c)} title="Avatar color"
                    style={{ width: 30, height: 30, borderRadius: 8, background: c, cursor: 'pointer',
                      border: avatarColor === c ? '2px solid var(--text)' : '2px solid transparent' }} />
                ))}
              </div>
            </div>

            <div>
              <label style={labelStyle}>Links</label>
              <div className="col gap8">
                {LINK_FIELDS.map((f) => (
                  <div key={f.key} className="row gap8" style={{ alignItems: 'center' }}>
                    <span className="muted" style={{ fontSize: 12.5, width: 92, flex: 'none' }}>{f.label}</span>
                    <input style={inputStyle} value={links[f.key] || ''} onChange={(e) => setLink(f.key, e.target.value)} placeholder={f.placeholder} />
                  </div>
                ))}
              </div>
            </div>

            <button className="btn btn-primary btn-block mt8" disabled={busy} style={{ opacity: busy ? 0.7 : 1 }} onClick={save}>
              {busy ? 'Saving…' : 'Save profile'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  window.ProfilePage = ProfilePage;
})();
