/* ============================================================================
   MEMORIES — real photo gallery. Capture from camera or upload from library;
   photos persist in the app and feed the recap.
   ============================================================================ */
function MemoriesScreen() {
  const store = usePhotos();
  const photos = store.list;
  const rotate = [-1.5, 1.2, -1, 1.6, -1.3, 0.8];
  const [syncing, setSyncing] = React.useState(false);
  const [prog, setProg] = React.useState(null);
  const pending = photos.filter((p) => !p.gphotos).length;
  const backup = async () => {
    if (syncing) return; setSyncing(true); setProg("0/" + pending);
    await store.syncAll((d, t) => setProg(d + "/" + t));
    setSyncing(false); setProg(null);
  };

  return (
    <div style={{ padding: "8px 16px 8px" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, marginBottom: 14 }}>
        <p style={{ fontSize: 13, color: "var(--colorNeutralForeground3)", margin: 0, lineHeight: 1.4, flex: 1 }}>
          Snap a photo or upload from your library — they're saved with the trip and appear in your recap.
        </p>
        <Chip tone="teal"><Icon name="image_multiple" size={13} filled color="var(--color-teal)" /> {photos.length}</Chip>
      </div>

      <div style={{ marginBottom: 12 }}>
        <AddPhotoBar />
      </div>

      {photos.length > 0 && (
        <button onClick={backup} disabled={syncing || pending === 0} style={{
          width: "100%", marginBottom: 18, padding: "11px", borderRadius: 12, cursor: pending === 0 ? "default" : "pointer",
          border: "1px solid var(--colorNeutralStroke2)", background: "var(--colorNeutralBackground1)",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "var(--fontFamilyBase)",
          fontSize: 13, fontWeight: 700, color: pending === 0 ? "var(--colorStatusSuccessForeground1)" : "var(--color-darkTeal)" }}>
          <Icon name={pending === 0 ? "checkmark_circle" : "image_multiple"} size={16} filled color={pending === 0 ? "var(--colorStatusSuccessForeground1)" : "var(--color-teal)"} />
          {syncing ? `Backing up… ${prog || ""}` : pending === 0 ? "All photos backed up to Google Photos" : `Back up ${pending} to Google Photos`}
        </button>
      )}

      {photos.length === 0 ? (
        <div style={{ marginTop: 8, padding: "40px 20px", borderRadius: 18, textAlign: "center",
          border: "1.5px dashed var(--colorNeutralStroke1)", background: "var(--colorNeutralBackground1)" }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "rgba(3,131,135,0.10)",
            display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
            <Icon name="camera" size={28} color="var(--color-teal)" />
          </div>
          <div style={{ fontSize: 15, fontWeight: 700, color: "var(--colorNeutralForeground1)" }}>No memories yet</div>
          <div style={{ fontSize: 13, color: "var(--colorNeutralForeground3)", marginTop: 4, lineHeight: 1.4 }}>
            Tap <b>Take photo</b> to capture the moment, or <b>Upload</b> to add from your gallery.
          </div>
        </div>
      ) : (
        <div style={{ columnCount: 2, columnGap: 11 }}>
          {photos.map((p, i) => (
            <PhotoCard key={p.id} photo={p} rotate={rotate[i % rotate.length]} />
          ))}
        </div>
      )}
    </div>
  );
}

function PhotoCard({ photo, rotate }) {
  const [caption, setCaption] = React.useState(photo.caption || "");
  return (
    <div style={{
      breakInside: "avoid", marginBottom: 11,
      background: "var(--colorNeutralBackground1)", borderRadius: 14, padding: 7,
      border: "1px solid var(--colorNeutralStroke2)", boxShadow: "var(--shadow4)",
      transform: `rotate(${rotate}deg)`,
    }}>
      <div style={{ position: "relative" }}>
        <img src={photo.src} alt={caption || photo.place} style={{ display: "block", width: "100%", borderRadius: 9, objectFit: "cover" }} />
        <button onClick={() => photoStore.remove(photo.id)} aria-label="delete photo" style={{
          position: "absolute", top: 6, right: 6, width: 26, height: 26, borderRadius: "50%",
          border: "none", background: "rgba(16,24,40,0.55)", color: "#fff", cursor: "pointer",
          display: "inline-flex", alignItems: "center", justifyContent: "center", backdropFilter: "blur(4px)",
        }}>
          <Icon name="dismiss" size={14} color="#fff" />
        </button>
      </div>
      <input
        value={caption}
        onChange={(e) => setCaption(e.target.value)}
        onBlur={() => photoStore.update(photo.id, { caption })}
        placeholder="Add a caption…"
        style={{
          width: "100%", border: "none", outline: "none", background: "transparent",
          fontFamily: "var(--fontFamilySerif)", fontStyle: "italic", fontSize: 14,
          color: "var(--colorNeutralForeground1)", padding: "8px 5px 2px", boxSizing: "border-box",
        }}
      />
      <div style={{ display: "flex", alignItems: "center", gap: 5, padding: "0 5px 4px" }}>
        <Icon name="location" size={12} color="var(--color-teal)" />
        <span style={{ fontSize: 11.5, color: "var(--colorNeutralForeground3)", fontWeight: 600 }}>{photo.place} · {photo.day}</span>
      </div>
      <div style={{ display: "flex", gap: 6, padding: "2px 4px 4px" }}>
        <button onClick={() => sharePhoto(photo)} style={photoActBtn}>
          <Icon name="share" size={13} color="var(--color-darkTeal)" /> Share
        </button>
        <button onClick={() => downloadPhoto(photo)} style={photoActBtn}>Download</button>
      </div>
    </div>
  );
}

const photoActBtn = {
  flex: 1, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 4,
  padding: "6px 8px", borderRadius: 9, cursor: "pointer", fontFamily: "var(--fontFamilyBase)",
  border: "1px solid var(--colorNeutralStroke2)", background: "var(--colorNeutralBackground1)",
  color: "var(--color-darkTeal)", fontSize: 11.5, fontWeight: 700,
};

Object.assign(window, { MemoriesScreen });
