// user-data.jsx — shared hooks for user-uploaded photos and letters
// Persists to localStorage. Keeps original content intact.

const USER_PHOTOS_KEY = 'es-user-photos-v1';
const USER_LETTERS_KEY = 'es-user-letters-v1';
const HIDDEN_PHOTOS_KEY = 'es-hidden-photos-v1';
const PHOTO_ADMIN_KEY = 'es-photo-admin-v1';
const PHOTO_ADMIN_PASSWORD = '20260330';

function useUserPhotos() {
  const [photos, setPhotos] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(USER_PHOTOS_KEY) || '[]'); }
    catch { return []; }
  });
  React.useEffect(() => {
    try { localStorage.setItem(USER_PHOTOS_KEY, JSON.stringify(photos)); } catch {}
  }, [photos]);
  const addPhoto = (photo) => setPhotos(p => [...p, { id: Date.now() + Math.random(), ...photo }]);
  const removePhoto = (id) => setPhotos(p => p.filter(x => x.id !== id));
  return { photos, addPhoto, removePhoto };
}

function useUserLetters() {
  const [letters, setLetters] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(USER_LETTERS_KEY) || '[]'); }
    catch { return []; }
  });
  React.useEffect(() => {
    try { localStorage.setItem(USER_LETTERS_KEY, JSON.stringify(letters)); } catch {}
  }, [letters]);
  const addLetter = (letter) => setLetters(p => [...p, { id: Date.now() + Math.random(), ...letter }]);
  const removeLetter = (id) => setLetters(p => p.filter(x => x.id !== id));
  return { letters, addLetter, removeLetter };
}

function usePhotoAdmin() {
  const [isAdmin, setIsAdmin] = React.useState(() => {
    try { return localStorage.getItem(PHOTO_ADMIN_KEY) === 'unlocked'; }
    catch { return false; }
  });
  const [hiddenPhotoIds, setHiddenPhotoIds] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(HIDDEN_PHOTOS_KEY) || '[]'); }
    catch { return []; }
  });

  React.useEffect(() => {
    try {
      if (isAdmin) localStorage.setItem(PHOTO_ADMIN_KEY, 'unlocked');
      else localStorage.removeItem(PHOTO_ADMIN_KEY);
    } catch {}
  }, [isAdmin]);

  React.useEffect(() => {
    try { localStorage.setItem(HIDDEN_PHOTOS_KEY, JSON.stringify(hiddenPhotoIds)); } catch {}
  }, [hiddenPhotoIds]);

  const login = (password) => {
    if (String(password).trim() !== PHOTO_ADMIN_PASSWORD) return false;
    setIsAdmin(true);
    return true;
  };
  const logout = () => setIsAdmin(false);
  const hidePhoto = (id) => setHiddenPhotoIds((ids) => ids.includes(id) ? ids : [...ids, id]);
  const restorePhotos = () => setHiddenPhotoIds([]);

  return { isAdmin, login, logout, hiddenPhotoIds, hidePhoto, restorePhotos };
}

// Convert a File into a data URL, compressed to max 1200px so localStorage survives.
async function fileToCompressedDataURL(file, maxSize = 1200, quality = 0.82) {
  const dataUrl = await new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onload = () => resolve(r.result);
    r.onerror = reject;
    r.readAsDataURL(file);
  });
  const img = await new Promise((resolve, reject) => {
    const i = new Image();
    i.onload = () => resolve(i);
    i.onerror = reject;
    i.src = dataUrl;
  });
  let { width, height } = img;
  if (width > maxSize || height > maxSize) {
    const ratio = Math.min(maxSize / width, maxSize / height);
    width = Math.round(width * ratio);
    height = Math.round(height * ratio);
  }
  const canvas = document.createElement('canvas');
  canvas.width = width; canvas.height = height;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, width, height);
  return canvas.toDataURL('image/jpeg', quality);
}

Object.assign(window, { useUserPhotos, useUserLetters, usePhotoAdmin, fileToCompressedDataURL });
