/* ============================================================
   2D PDF viewer (FR-8) — PDF.js, page nav + zoom, fullscreen overlay
   ============================================================ */
const PDFJS_WORKER = "https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js";

function PdfViewer({ url, name, onClose }) {
  const canvasRef = React.useRef(null);
  const pdfRef = React.useRef(null);
  const [page, setPage] = React.useState(1);
  const [num, setNum] = React.useState(0);
  const [scale, setScale] = React.useState(1.3);
  const [err, setErr] = React.useState("");
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      const lib = window.pdfjsLib;
      if (!lib) { setErr("PDF.js chưa tải được"); setLoading(false); return; }
      try {
        lib.GlobalWorkerOptions.workerSrc = PDFJS_WORKER;
        const pdf = await lib.getDocument(url).promise;
        if (cancelled) return;
        pdfRef.current = pdf; setNum(pdf.numPages); setPage(1); setLoading(false);
      } catch (e) { if (!cancelled) { setErr(e.message || "Không mở được PDF"); setLoading(false); } }
    })();
    return () => { cancelled = true; };
  }, [url]);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      const pdf = pdfRef.current; if (!pdf) return;
      try {
        const pg = await pdf.getPage(page);
        const vp = pg.getViewport({ scale });
        const c = canvasRef.current; if (!c || cancelled) return;
        const ctx = c.getContext("2d");
        c.width = vp.width; c.height = vp.height;
        await pg.render({ canvasContext: ctx, viewport: vp }).promise;
      } catch (e) { /* render race on fast nav — ignore */ }
    })();
    return () => { cancelled = true; };
  }, [page, scale, num]);

  const btn = { width: 34, height: 34, borderRadius: 8, border: "1px solid rgba(255,255,255,.2)", background: "rgba(255,255,255,.08)", color: "#fff", cursor: "pointer", display: "grid", placeItems: "center", fontWeight: 700 };
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(8,16,20,.92)", display: "flex", flexDirection: "column" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderBottom: "1px solid rgba(255,255,255,.12)", color: "#fff" }}>
        <Icon.doc size={18} />
        <span className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{name}</span>
        <span style={{ flex: 1 }} />
        <button style={btn} onClick={() => setScale(s => Math.max(0.5, s - 0.2))} title="Thu nhỏ">−</button>
        <span style={{ fontSize: 12, minWidth: 44, textAlign: "center" }}>{Math.round(scale * 100)}%</span>
        <button style={btn} onClick={() => setScale(s => Math.min(3, s + 0.2))} title="Phóng to">+</button>
        <span style={{ width: 12 }} />
        <button style={btn} onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page <= 1}>‹</button>
        <span style={{ fontSize: 12.5, minWidth: 70, textAlign: "center" }}>{num ? `${page} / ${num}` : "—"}</span>
        <button style={btn} onClick={() => setPage(p => Math.min(num, p + 1))} disabled={page >= num}>›</button>
        <span style={{ width: 12 }} />
        <button style={{ ...btn, background: "rgba(255,255,255,.16)" }} onClick={onClose} title="Đóng">✕</button>
      </div>
      <div style={{ flex: 1, overflow: "auto", display: "grid", placeItems: "center", padding: 24 }}>
        {loading && <div style={{ color: "#cfe9e5", fontSize: 14 }}>Đang tải PDF…</div>}
        {err && <div style={{ color: "#ff8a8a", fontSize: 14, fontWeight: 600 }}>Lỗi: {err}</div>}
        {!err && <canvas ref={canvasRef} style={{ boxShadow: "0 8px 40px rgba(0,0,0,.5)", borderRadius: 4, background: "#fff", display: loading ? "none" : "block" }} />}
      </div>
    </div>
  );
}

window.PdfViewer = PdfViewer;
