"use client";

import { useEffect, useRef, useState } from "react";

// The top-of-sidebar mark is now a user avatar. Empty by default; click to
// upload an image. Stored client-side as a data URL (local-first, per browser).
const STORAGE_KEY = "madarx:sidebarAvatar";
const MAX_BYTES = 2 * 1024 * 1024; // 2 MB

export default function SidebarAvatar() {
  const [src, setSrc] = useState(null);
  const inputRef = useRef(null);

  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) setSrc(saved);
    } catch {}
  }, []);

  function onPick(event) {
    const file = event.target.files?.[0];
    event.target.value = "";
    if (!file || !file.type.startsWith("image/") || file.size > MAX_BYTES) return;
    const reader = new FileReader();
    reader.onload = () => {
      const url = String(reader.result || "");
      if (!url) return;
      setSrc(url);
      try { localStorage.setItem(STORAGE_KEY, url); } catch {}
    };
    reader.readAsDataURL(file);
  }

  function clear(event) {
    event.stopPropagation();
    setSrc(null);
    try { localStorage.removeItem(STORAGE_KEY); } catch {}
  }

  return (
    <>
      <button
        type="button"
        onClick={() => inputRef.current?.click()}
        aria-label={src ? "Change avatar" : "Upload an avatar"}
        title={src ? "Change avatar" : "Upload an avatar"}
        className="group relative w-9 h-9 rounded-full overflow-hidden flex items-center justify-center cursor-pointer border border-[rgba(20,22,26,0.16)] bg-[rgba(17,19,24,0.035)] transition-colors hover:border-[rgba(20,22,26,0.32)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#111318] focus-visible:ring-offset-2 focus-visible:ring-offset-white/50"
      >
        {src ? (
          <img src={src} alt="Avatar" className="w-full h-full object-cover" />
        ) : (
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9aa1ab" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M12 16V8M8 12h8" />
          </svg>
        )}
        <span className="absolute inset-0 hidden group-hover:flex items-center justify-center bg-black/35 text-white">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M12 16V6M12 6 7.5 10.5M12 6l4.5 4.5" />
            <path d="M5 18v1.5A1.5 1.5 0 0 0 6.5 21h11a1.5 1.5 0 0 0 1.5-1.5V18" />
          </svg>
        </span>
        {src ? (
          <span
            role="button"
            tabIndex={-1}
            onClick={clear}
            aria-label="Remove avatar"
            className="absolute -top-0.5 -right-0.5 hidden group-hover:flex w-4 h-4 items-center justify-center rounded-full bg-[#111318] text-white text-[9px] leading-none"
          >
            ×
          </span>
        ) : null}
      </button>
      <input ref={inputRef} type="file" accept="image/*" hidden onChange={onPick} />
    </>
  );
}
