(() => {
  const { Icon } = window.HiraIcons;
  const { EmptyState } = window.HiraUI;
  const HiraFormat = window.HiraFormat;

// ── ImgCard ───────────────────────────────────────────────────────────────────
function BatchCheckbox({ checked, onChange }) {
  return (
    <div className="absolute top-2 left-2 z-20 bg-black/60 rounded-full p-0.5 backdrop-blur">
      <input
        type="checkbox"
        checked={!!checked}
        onChange={(e) => onChange?.(e.target.checked)}
        className="w-5 h-5 rounded accent-amber-400 cursor-pointer"
        onClick={(e) => e.stopPropagation()}
      />
    </div>
  );
}

function ImgCard({ item, T, fav, onToggleFav, onOpen, onMenu, batchMode, batchSelected, onBatchToggle }) {
  return (
    <div className="break-inside-avoid mb-5 card-enter">
      <div className="lantern-card rounded-2xl overflow-hidden relative group cursor-pointer" onClick={() => batchMode ? onBatchToggle?.(item.id) : onOpen(item)}>
        {batchMode && <BatchCheckbox checked={batchSelected?.has(item.id)} onChange={(checked) => onBatchToggle?.(item.id, checked)} />}
        <div className={`absolute inset-0 ring-1 ${T.ring} rounded-2xl pointer-events-none`} />
        <img
          src={HiraFormat.imageThumb(item)}
          alt={item.title}
          className="w-full object-cover block bg-white/5"
          style={{ minHeight: 120 }}
          loading="lazy"
          onError={(e) => {
            e.target.onerror = null;
            e.target.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='32' height='32' fill='none' stroke='%23999' stroke-width='1.5'%3E%3Crect x='3' y='3' width='18' height='18' rx='2'/%3E%3Ccircle cx='8.5' cy='8.5' r='1.5'/%3E%3Cpath d='M21 15l-5-5L5 21'/%3E%3C/svg%3E";
            e.target.alt = "Gagal memuat";
          }}
        />
        {/* Favorit selalu terlihat (mobile-friendly); unduh muncul saat hover di desktop */}
        <div className="absolute top-2 right-2 z-10 flex flex-col gap-1.5 items-end">
          <button
            type="button"
            aria-label={fav ? "Hapus favorit" : "Tambah favorit"}
            onClick={(e) => { e.stopPropagation(); onToggleFav(item); }}
            className={`p-1.5 rounded-full bg-black/55 backdrop-blur transition-colors ${fav ? "text-rose-400" : "text-stone-100"}`}
          >
            <Icon.Heart filled={fav} />
          </button>
          <a
            href={HiraFormat.imageFull(item)}
            target="_blank"
            rel="noreferrer"
            aria-label="Unduh"
            onClick={(e) => e.stopPropagation()}
            className="p-1.5 rounded-full bg-black/50 text-stone-100 backdrop-blur opacity-0 group-hover:opacity-100 transition-opacity hidden sm:inline-flex"
          >
            <Icon.Download />
          </a>
        </div>
      </div>
      <div className="flex items-start justify-between gap-1.5 px-0.5 pt-2">
        <p className="text-xs sm:text-sm leading-snug line-clamp-2">{item.title}</p>
        <button onClick={(e) => { e.stopPropagation(); onMenu(item); }} className={`shrink-0 p-1 rounded-full ${T.sub} ${T.hoverSoft}`}><Icon.More /></button>
      </div>
    </div>
  );
}

function Masonry({ items, T, favorites, onToggleFav, onOpen, onMenu, batchMode, batchSelected, onBatchToggle }) {
  if (items.length === 0) {
    return <EmptyState T={T} title="Belum ada gambar" body="Tidak ada gambar yang cocok dengan filter ini." />;
  }
  return (
    <div className="columns-2 sm:columns-3 lg:columns-4 xl:columns-5 gap-4">
      {items.map((it) => (
        <ImgCard key={it.id} item={it} T={T} fav={favorites.has(it.id)} onToggleFav={onToggleFav} onOpen={onOpen} onMenu={onMenu} batchMode={batchMode} batchSelected={batchSelected} onBatchToggle={onBatchToggle} />
      ))}
    </div>
  );
}

// ── LibraryScrollStrip ─────────────────────────────────────────────────────────
function LibraryScrollStrip({ items, onOpen }) {
  if (!items || items.length === 0) return null;
  if (items.length < 4) {
    return (
      <div className="flex gap-3 px-5 sm:px-8">
        {items.map((it) => (
          <button key={it.id} onClick={() => onOpen(it)}
            className="relative shrink-0 w-36 h-36 sm:w-44 sm:h-44 rounded-2xl overflow-hidden group/strip smooth-btn">
            <img src={HiraFormat.imageThumb(it)} className="w-full h-full object-cover transition-transform duration-500 group-hover/strip:scale-110" loading="lazy" />
            <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover/strip:opacity-100 transition-opacity duration-300" />
          </button>
        ))}
      </div>
    );
  }
  const display = [...items, ...items];
  const duration = items.length * 3;

  return (
    <div className="overflow-hidden"
      style={{ maskImage: "linear-gradient(to right, transparent 0%, black 6%, black 94%, transparent 100%)",
               WebkitMaskImage: "linear-gradient(to right, transparent 0%, black 6%, black 94%, transparent 100%)" }}>
      <div className="flex gap-3 py-1"
        style={{ width: "max-content", animation: `scrollLeft ${duration}s linear infinite` }}
        onMouseEnter={e => e.currentTarget.style.animationPlayState = "paused"}
        onMouseLeave={e => e.currentTarget.style.animationPlayState = "running"}>
        {display.map((it, i) => (
          <button key={`${it.id}-${i}`} onClick={() => onOpen(it)}
            className="relative shrink-0 w-36 h-36 sm:w-44 sm:h-44 rounded-2xl overflow-hidden group/strip smooth-btn">
            <img src={HiraFormat.imageThumb(it)} className="w-full h-full object-cover transition-transform duration-500 group-hover/strip:scale-110" loading="lazy" />
            <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 group-hover/strip:opacity-100 transition-opacity duration-300" />
          </button>
        ))}
      </div>
    </div>
  );
}


// ── ShareSheet ────────────────────────────────────────────────────────────────
function ShareSheet({ item, T, fav, onToggleFav, onSave, onOpenPreview, onEdit, onDelete, onCopyPublic, canDelete, onClose }) {
  const doShare = async () => {
    const text = `${item.title} — ${item.description || ""}`;
    const shareUrl = HiraFormat.imageFull(item);
    try {
      if (navigator.share) await navigator.share({ title: item.title, text, url: shareUrl });
      else if (navigator.clipboard) await navigator.clipboard.writeText(`${text} ${shareUrl}`);
    } catch (e) {}
  };
  const confirmDelete = () => {
    onDelete(item);
    onClose();
  };
  const OPTIONS = [
    { label: "Bagikan langsung", action: doShare },
    { label: "Salin link publik", action: () => { onCopyPublic?.("image", item.id); onClose(); } },
    { label: "Edit info gambar", action: () => { onEdit(item); onClose(); } },
    { label: "Simpan ke koleksi", action: () => onSave(item) },
    { label: "Buka pratinjau", action: () => { onOpenPreview(item); onClose(); } },
    { label: "Unduh gambar", action: () => { window.open(HiraFormat.imageFull(item), "_blank"); onClose(); } },
    { label: fav ? "Hapus dari favorit" : "Tambah ke favorit", action: () => { onToggleFav(item); onClose(); } },
    ...(canDelete ? [{ label: "Hapus gambar", action: confirmDelete, danger: true }] : []),
  ];
  return (
    <div className={`fixed inset-0 z-50 flex items-end sm:items-center justify-center ${T.overlay} overlay-enter`} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} className={`w-full sm:max-w-sm rounded-t-3xl sm:rounded-2xl border ${T.modalBg} p-5 pb-8 sm:pb-5 sheet-enter`}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-display text-lg">Opsi gambar</h3>
          <button onClick={onClose} className={T.sub}><Icon.X /></button>
        </div>
        {OPTIONS.map((o) => (
          <button key={o.label} onClick={o.action} className={`w-full text-left px-1 py-2.5 rounded-lg text-sm ${T.hoverSoft} ${o.danger ? "text-rose-400" : ""}`}>{o.label}</button>
        ))}
      </div>
    </div>
  );
}


  window.HiraGallery = { BatchCheckbox, ImgCard, Masonry, LibraryScrollStrip, ShareSheet };
})();
