// app/gallery.jsx — Galerie partagée (photos stockées localement)

const GAL_KEY = "ea-app:gallery";

function GalleryPage() {
  const [photos, setPhotos] = React.useState(() => Store.get(GAL_KEY, []));
  const [author, setAuthor] = React.useState(() => Store.get(GAL_KEY + ":author", ""));
  const fileRef = React.useRef(null);

  const onPick = (e) => {
    const files = Array.from(e.target.files || []);
    const next = [...photos];
    let count = 0;
    files.forEach((f) => {
      if (!f.type.startsWith("image/")) return;
      const reader = new FileReader();
      reader.onload = () => {
        next.push({ src: reader.result, name: f.name, author: author || "Anonyme", at: new Date().toISOString() });
        count++;
        if (count === files.length) {
          setPhotos(next);
          Store.set(GAL_KEY, next);
          Store.set(GAL_KEY + ":author", author);
        }
      };
      reader.readAsDataURL(f);
    });
    e.target.value = "";
  };

  const remove = (i) => {
    const next = photos.filter((_, idx) => idx !== i);
    setPhotos(next);
    Store.set(GAL_KEY, next);
  };

  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={-30} opacity={0.16}/>
      <Page>
        <AppHeader eyebrow="Galerie partagée" title="Vos clichés" />
        <div style={{ textAlign: "center", fontFamily: A.italic, fontStyle: "italic", fontSize: 15, color: A.inkSoft, marginTop: 8, maxWidth: 480, margin: "8px auto 0", lineHeight: 1.55 }}>
          Déposez vos plus belles photos du mariage. Tout le monde y a accès — les flous et les ratages sont les bienvenus.
        </div>

        {/* Upload */}
        <div style={{ marginTop: 24, padding: 20, background: A.paper, border: `2px dashed ${A.or}`, textAlign: "center" }}>
          <input type="text" value={author} onChange={(e) => setAuthor(e.target.value)}
            placeholder="Votre prénom (optionnel)"
            style={{
              width: "100%", maxWidth: 300, padding: "10px 12px", background: A.card,
              border: `1px solid ${A.ruleSoft}`, fontFamily: A.sans, fontSize: 14, color: A.ink, outline: "none",
              marginBottom: 12,
            }}/>
          <input ref={fileRef} type="file" accept="image/*" multiple onChange={onPick} style={{ display: "none" }}/>
          <div>
            <ButtonA primary onClick={() => fileRef.current?.click()}>
              ✦ Ajouter des photos
            </ButtonA>
          </div>
          <div style={{ marginTop: 10, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute }}>
            JPG / PNG / HEIC · Plusieurs à la fois acceptés
          </div>
        </div>

        {/* Galerie */}
        {photos.length === 0 ? (
          <div style={{ marginTop: 32, padding: 40, background: A.white, border: `1px solid ${A.ruleSoft}`, textAlign: "center" }}>
            <div style={{ fontFamily: A.display, fontSize: 40, color: A.or, lineHeight: 1, marginBottom: 14 }}>✦</div>
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 16, color: A.inkSoft, lineHeight: 1.55 }}>
              La galerie est vide pour l'instant.<br/>
              Soyez le premier ou la première à y déposer une photo.
            </div>
          </div>
        ) : (
          <>
            <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div className="eyebrow">★ {photos.length} cliché{photos.length > 1 ? "s" : ""} ★</div>
              <div style={{ fontFamily: A.mono, fontSize: 10, color: A.inkMute, letterSpacing: 1 }}>Cliquez pour agrandir</div>
            </div>
            <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8 }}>
              {photos.map((p, i) => (
                <PhotoTile key={i} photo={p} onRemove={() => remove(i)}/>
              ))}
            </div>
          </>
        )}

        <div style={{ marginTop: 24, padding: "14px 18px", background: A.paper, borderLeft: `3px solid ${A.or}`, fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.ink, lineHeight: 1.55 }}>
          <strong style={{ fontStyle: "normal", fontFamily: A.bold || A.display, color: A.orDeep, fontSize: 11, letterSpacing: 2, textTransform: "uppercase", display: "block", marginBottom: 4 }}>
            Note technique
          </strong>
          Pour le moment, les photos sont stockées sur votre navigateur. Avant le mariage, on branchera une vraie galerie partagée en ligne pour que tout le monde voie tout le monde.
        </div>
      </Page>
    </div>
  );
}

function PhotoTile({ photo, onRemove }) {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <div style={{ position: "relative", aspectRatio: "1/1", overflow: "hidden", background: A.paper, cursor: "pointer", boxShadow: A.shadow }}
        onClick={() => setOpen(true)}>
        <img src={photo.src} alt={photo.name} style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
        {photo.author && (
          <div style={{
            position: "absolute", bottom: 0, left: 0, right: 0,
            padding: "8px 10px", background: "linear-gradient(transparent, rgba(0,0,0,0.6))",
            color: A.white, fontFamily: A.italic, fontStyle: "italic", fontSize: 11,
          }}>
            {photo.author}
          </div>
        )}
      </div>
      {open && (
        <div onClick={() => setOpen(false)} style={{
          position: "fixed", inset: 0, background: "rgba(26,22,18,0.94)", zIndex: 200,
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
          padding: 20, cursor: "pointer",
        }}>
          <img src={photo.src} alt={photo.name} style={{ maxWidth: "100%", maxHeight: "85vh", objectFit: "contain", boxShadow: "0 20px 60px rgba(0,0,0,0.6)" }}/>
          <div style={{ marginTop: 18, color: A.white, fontFamily: A.italic, fontStyle: "italic", fontSize: 14, textAlign: "center" }}>
            {photo.author && <>par {photo.author} · </>}
            {new Date(photo.at).toLocaleDateString("fr-FR")}
          </div>
          <button onClick={(e) => { e.stopPropagation(); if (confirm("Supprimer cette photo ?")) onRemove(); }} style={{
            marginTop: 12, padding: "8px 16px", background: "transparent", border: `1px solid ${A.rouge}`,
            color: A.rouge, fontFamily: A.mono, fontSize: 10, letterSpacing: 2, textTransform: "uppercase", cursor: "pointer",
          }}>
            Supprimer
          </button>
          <button onClick={() => setOpen(false)} style={{
            position: "absolute", top: 20, right: 20, width: 36, height: 36,
            background: "transparent", border: "none", color: A.white, fontSize: 28, cursor: "pointer", lineHeight: 1,
          }}>×</button>
        </div>
      )}
    </>
  );
}

Object.assign(window, { GalleryPage });
