/* lightbox.jsx — fullscreen viewer with rating/status/notes/comments,
   and the side-by-side compare overlay. */

function LbAction({ icon, label, on, cls, onClick }) {
  return (
    <button className={"lb-act" + (on ? " " + cls : "")} onClick={onClick}>
      <Icon name={icon} size={17} fill={icon === "heart" && on} /> {label}
    </button>
  );
}

function Lightbox({ list, index, setIndex, store, role, project, onClose }) {
  const photo = list[index];
  const [draftNote, setDraftNote] = React.useState(photo ? photo.note : "");
  const [draftComment, setDraftComment] = React.useState("");
  const toast = useToast();

  React.useEffect(() => { if (photo) setDraftNote(photo.note || ""); }, [photo && photo.id]);

  const go = React.useCallback((d) => setIndex((i) => Math.max(0, Math.min(list.length - 1, i + d))), [list.length, setIndex]);

  React.useEffect(() => {
    const h = (e) => {
      if (e.target.tagName === "TEXTAREA" || e.target.tagName === "INPUT") return;
      if (e.key === "ArrowRight") go(1);
      else if (e.key === "ArrowLeft") go(-1);
      else if (e.key === "Escape") onClose();
      else if (e.key >= "1" && e.key <= "5") store.setStars(photo.id, +e.key);
      else if (e.key === "0") store.setStars(photo.id, 0);
      else if (e.key === " ") { e.preventDefault(); store.setStatus(photo.id, "pick"); }
      else if (e.key === "Delete" || e.key === "Backspace") { e.preventDefault(); store.setStatus(photo.id, "reject"); }
      else if (e.key.toLowerCase() === "f") store.toggleLike(photo.id);
    };
    window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h);
  }, [photo, go, onClose, store]);

  if (!photo) return null;
  const who = role === "studio" ? "Studio Lụa" : "Cô dâu chú rể";

  const saveNote = () => { store.setNote(photo.id, draftNote); toast("Đã lưu ghi chú", "check"); };
  const sendComment = () => {
    if (!draftComment.trim()) return;
    store.addComment(photo.id, { id: Math.random().toString(36), who, role, text: draftComment.trim(), time: "Vừa xong" });
    setDraftComment("");
  };

  return (
    <div className="lightbox">
      <div className="lb-bar">
        <button className="icon-btn" style={{ color: "inherit" }} onClick={onClose}><Icon name="close" size={20} /></button>
        <div>
          <div className="lb-name">{photo.filename}</div>
          <div className="lb-meta">{index + 1} / {list.length} · {project.name}</div>
        </div>
        <div style={{ flex: 1 }} />
        {role === "studio" && (
          <button className="lb-act" title="Xoá ảnh khỏi project" onClick={() => {
            if (confirm("Xoá ảnh này khỏi project? Ảnh sẽ bị xoá khỏi Cloudflare R2 và không thể khôi phục.")) {
              const wasLast = index >= list.length - 1;
              store.deletePhoto(photo.id);
              if (list.length <= 1) onClose();
              else if (wasLast) setIndex(index - 1);
            }
          }}><Icon name="trash" size={16} /> Xoá</button>
        )}
        <button className="lb-act" onClick={() => go(-1)} disabled={index === 0}><Icon name="left" size={16} /> Trước</button>
        <button className="lb-act" onClick={() => go(1)} disabled={index === list.length - 1}>Sau <Icon name="right" size={16} /></button>
      </div>

      <div className="lb-main">
        <div className="lb-stage">
          {index > 0 && <button className="lb-nav prev" onClick={() => go(-1)}><Icon name="left" size={24} /></button>}
          <div className="lb-img-wrap"><img className="lb-img" src={store.thumb(photo, 1600)} alt={photo.filename} decoding="async"
            onError={(e) => { const f = store.src(photo); if (f && e.currentTarget.src !== f) e.currentTarget.src = f; }} /></div>
          {index < list.length - 1 && <button className="lb-nav next" onClick={() => go(1)}><Icon name="right" size={24} /></button>}
        </div>

        <div className="lb-side">
          {role === "studio" && ((photo.picks || 0) > 0 || (photo.likes || 0) > 0 || (photo.otherStars || 0) > 0) && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 12px", borderRadius: 10, background: "var(--accent)", color: "#fff", fontSize: 13, fontWeight: 600 }}>
              <Icon name="heart" size={15} fill /> Khách đã chọn:
              {(photo.picks || 0) > 0 && <span>✓ Chọn</span>}
              {(photo.otherStars || 0) > 0 && <span>{photo.otherStars}★</span>}
              {(photo.likes || 0) > 0 && <span>♥ Thích</span>}
            </div>
          )}
          <div>
            <div className="note-block" style={{ marginBottom: 10 }}><label>Đánh giá</label></div>
            <Stars value={photo.stars} onChange={(n) => store.setStars(photo.id, n)} size={26} className="lg" onLight />
            <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
              <LbAction icon="heart" label={photo.liked ? "Đã thích" : "Yêu thích"} on={photo.liked} cls="on-pick" onClick={() => store.toggleLike(photo.id)} />
            </div>
          </div>

          <div className="lb-actions" style={{ flexWrap: "wrap" }}>
            <LbAction icon="check" label="Chọn" on={photo.status === "pick"} cls="on-pick" onClick={() => store.setStatus(photo.id, "pick")} />
            <LbAction icon="x" label="Bỏ" on={photo.status === "reject"} cls="on-reject" onClick={() => store.setStatus(photo.id, "reject")} />
          </div>
          <div className="lb-kbd">Phím tắt: <kbd>1–5</kbd> sao · <kbd>Space</kbd> chọn · <kbd>Del</kbd> bỏ · <kbd>F</kbd> thích · <kbd>←</kbd><kbd>→</kbd> chuyển ảnh</div>

          <div>
            <label style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "oklch(0.62 0.01 80)", fontWeight: 700 }}>Album</label>
            <select value={photo.albumId} onChange={(e) => store.moveToAlbum(photo.id, e.target.value)}
              style={{ width: "100%", marginTop: 8, padding: "10px 12px", borderRadius: 10, background: "oklch(0.2 0.01 60 / 0.6)", border: "1px solid oklch(0.36 0.01 60 / 0.6)", color: "oklch(0.92 0.01 80)", fontSize: 13.5, outline: "none" }}>
              {project.albums.map((al) => <option key={al.id} value={al.id} style={{ color: "#222" }}>{al.name}</option>)}
            </select>
          </div>

          <div className="note-block">
            <label>{role === "studio" ? "Ghi chú chỉnh sửa (nội bộ)" : "Ghi chú của bạn"}</label>
            <textarea className="note-input" value={draftNote} onChange={(e) => setDraftNote(e.target.value)}
              onBlur={saveNote} placeholder={role === "studio" ? "VD: tăng sáng, xoá hậu cảnh…" : "VD: thích tấm này, in khổ lớn…"} />
          </div>

          <div className="note-block">
            <label style={{ display: "flex", alignItems: "center", gap: 7 }}><Icon name="message" size={13} /> Trao đổi ({(photo.comments || []).length})</label>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 10 }}>
              {(photo.comments || []).map((c) => (
                <div key={c.id} className="comment">
                  <div className="c-who"><Avatar name={c.who} size={20} role={c.role} /> {c.who}
                    <span className="who-badge" style={c.role === "client" ? { background: "var(--gold)", color: "oklch(0.3 0.05 70)" } : null}>{c.role === "studio" ? "STUDIO" : "KHÁCH"}</span></div>
                  <div className="c-text">{c.text}</div>
                  <div className="c-time">{c.time}</div>
                </div>
              ))}
              {(photo.comments || []).length === 0 && <div style={{ fontSize: 12.5, color: "oklch(0.55 0.01 80)" }}>Chưa có trao đổi nào.</div>}
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
              <input value={draftComment} onChange={(e) => setDraftComment(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && sendComment()} placeholder="Nhắn cho nhau…"
                style={{ flex: 1, padding: "10px 12px", borderRadius: 10, background: "oklch(0.2 0.01 60 / 0.6)", border: "1px solid oklch(0.36 0.01 60 / 0.6)", color: "oklch(0.92 0.01 80)", fontSize: 13, outline: "none" }} />
              <button className="lb-act" onClick={sendComment} style={{ padding: "0 14px" }}><Icon name="send" size={16} /></button>
            </div>
          </div>
        </div>
      </div>

      <div className="lb-thumbs">
        {list.map((p, i) => (
          <img key={p.id} className={"lb-thumb" + (i === index ? " on" : "")} src={store.thumb(p, 160)}
            loading="lazy" decoding="async" alt="" onClick={() => setIndex(i)}
            onError={(e) => { const f = store.src(p); if (f && e.currentTarget.src !== f) e.currentTarget.src = f; }} />
        ))}
      </div>
    </div>
  );
}

/* ---- Compare overlay ---- */
function CompareLauncher({ ids, list, store, role, onClose }) {
  const photos = ids.map((id) => list.find((p) => p.id === id)).filter(Boolean);
  if (photos.length < 2) return null;
  React.useEffect(() => {
    const h = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <div className="compare">
      <div className="lb-bar">
        <button className="icon-btn" style={{ color: "inherit" }} onClick={onClose}><Icon name="close" size={20} /></button>
        <div className="lb-name" style={{ fontFamily: "var(--font-display)", fontSize: 20 }}>So sánh ảnh</div>
        <div style={{ flex: 1 }} />
        <div className="lb-meta" style={{ paddingRight: 8 }}>Chọn ảnh ưng hơn bằng các nút bên dưới mỗi ảnh</div>
      </div>
      <div className="compare-stage">
        {photos.map((p, i) => (
          <div className="compare-pane" key={p.id}>
            <span className="cp-tag">{p.filename}</span>
            <img src={store.src(p)} alt={p.filename} />
            <div className="cp-acts">
              <Stars value={p.stars} onChange={(n) => store.setStars(p.id, n)} size={20} onLight />
              <button className={"lb-act" + (p.status === "pick" ? " on-pick" : "")} onClick={() => store.setStatus(p.id, "pick")}><Icon name="check" size={15} /> Chọn</button>
              <button className={"lb-act" + (p.liked ? " on-pick" : "")} onClick={() => store.toggleLike(p.id)}><Icon name="heart" size={15} fill={p.liked} /></button>
              <button className={"lb-act" + (p.status === "reject" ? " on-reject" : "")} onClick={() => store.setStatus(p.id, "reject")}><Icon name="x" size={15} /> Bỏ</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Lightbox, CompareLauncher });
