import React, { useRef, useState } from 'react';

export default function AvatarUpload({ uploadUrl, initialThumbUrl, initials }) {
  const [thumbUrl, setThumbUrl] = useState(initialThumbUrl || null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current?.click();
  }

  function handleChange(e) {
    const file = e.target.files?.[0];
    if (!file) return;

    const fd = new FormData();
    fd.append('avatar', file);

    setLoading(true);
    setError(null);

    fetch(uploadUrl, { method: 'POST', body: fd })
      .then(r => r.json())
      .then(data => {
        if (data.error) {
          setError(data.error);
          return;
        }
        setThumbUrl(data.thumbUrl);

        const navImg = document.querySelector('.hero-auth-avatar:not(.hero-auth-avatar--initials)');
        const navInitials = document.querySelector('.hero-auth-avatar.hero-auth-avatar--initials');
        if (navImg) {
          navImg.src = data.thumbUrl;
        } else if (navInitials) {
          const img = document.createElement('img');
          img.src = data.thumbUrl;
          img.alt = navInitials.textContent.trim();
          img.className = 'hero-auth-avatar';
          navInitials.replaceWith(img);
        }
      })
      .catch(() => setError('Upload failed. Please try again.'))
      .finally(() => setLoading(false));
  }

  return (
    <div
      className={`profile-avatar${loading ? ' profile-avatar--loading' : ''}`}
      title="Click to change profile picture"
      onClick={handleClick}
    >
      {thumbUrl
        ? <img src={thumbUrl} alt={initials} className="profile-avatar__img" />
        : <span className="profile-avatar__initials">{initials}</span>
      }
      <div className="profile-avatar__overlay">
        <i className="fa fa-camera" />
      </div>
      <input
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/gif,image/webp"
        style={{ display: 'none' }}
        onChange={handleChange}
      />
      {error && <div className="profile-avatar__error">{error}</div>}
    </div>
  );
}
