// The Feedback button on every page, and its drawer. Ported from the AMF staff app's charm
// (amf-internal-app assets/js/feedback.js): same fields and behaviour, without its PIN, since
// the tools login already says who is writing. Posts to meadowcraft-vps POST /feedback.
const { useState: useFbState, useEffect: useFbEffect, useRef: useFbRef } = React;

const FB_MAX_BYTES = 2 * 1024 * 1024; // matches the API (the row must fit one MySQL packet)
const FB_TYPES = /^image\/(png|jpeg|gif|webp)$/;
const FB_MAX_EDGE = 2000;

// A screenshot over the limit (a large full-screen PNG) is redrawn smaller in the browser so
// it can still be sent: WebP where the browser can encode it, else JPEG (Safari's toBlob
// ignores image/webp and returns a PNG). Resolves to null if even that is too big.
async function fbShrink(file) {
  if (file.size <= FB_MAX_BYTES) return file;
  const img = await createImageBitmap(file);
  const scale = Math.min(1, FB_MAX_EDGE / Math.max(img.width, img.height));
  const canvas = document.createElement("canvas");
  canvas.width = Math.round(img.width * scale);
  canvas.height = Math.round(img.height * scale);
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "#fff"; // JPEG has no transparency
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  for (const type of ["image/webp", "image/jpeg"]) {
    for (const quality of [0.85, 0.7, 0.5]) {
      const blob = await new Promise((done) => canvas.toBlob(done, type, quality));
      if (!blob || blob.type !== type) break; // this browser can't encode it: next type
      if (blob.size <= FB_MAX_BYTES) {
        return new File([blob], `screenshot.${type === "image/webp" ? "webp" : "jpg"}`, { type });
      }
    }
  }
  return null;
}

function FeedbackCharm() {
  const [open, setOpen] = useFbState(false);
  const [body, setBody] = useFbState("");
  const [shot, setShot] = useFbState(null); // the File to send, from paste, drop or picker
  const [thumb, setThumb] = useFbState(null);
  const [error, setError] = useFbState("");
  const [sending, setSending] = useFbState(false);
  const [sentId, setSentId] = useFbState(null);
  const [over, setOver] = useFbState(false);
  const textRef = useFbRef(null);
  const charmRef = useFbRef(null);
  const fileRef = useFbRef(null);
  const drawerRef = useFbRef(null);
  const thumbRef = useFbRef(null); // the live object URL, so an older pick can't leak it
  const pickSeq = useFbRef(0); // only the latest pick wins when two overlap

  function setPreview(file) {
    if (thumbRef.current) URL.revokeObjectURL(thumbRef.current);
    thumbRef.current = file ? URL.createObjectURL(file) : null;
    setShot(file);
    setThumb(thumbRef.current);
  }

  async function pick(picked) {
    if (!picked) return;
    if (!FB_TYPES.test(picked.type)) return setError("The screenshot must be a PNG, JPEG, GIF or WebP image.");
    const seq = ++pickSeq.current;
    let file = null;
    try {
      file = await fbShrink(picked);
    } catch {
      file = null;
    }
    if (seq !== pickSeq.current) return; // a newer pick replaced this one
    if (!file) return setError("That screenshot is too large to send. Try a smaller one.");
    setPreview(file);
    setError("");
  }

  function unpick() {
    pickSeq.current++;
    setPreview(null);
    if (fileRef.current) fileRef.current.value = "";
  }

  function close() {
    setOpen(false);
    setError("");
    if (sentId !== null) { // a sent ticket starts the next one fresh
      setBody(""); unpick(); setSentId(null);
    }
    charmRef.current && charmRef.current.focus();
  }

  // The listeners call the latest close/pick without re-running the effect (which would
  // also move focus) on every render.
  const latest = useFbRef({});
  latest.current = { close, pick };

  useFbEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") return latest.current.close();
      if (e.key !== "Tab" || !drawerRef.current) return;
      // Keep Tab inside the drawer: it is a modal dialog.
      const focusable = drawerRef.current.querySelectorAll(
        'button:not([disabled]), textarea, input:not([type="file"]), [href], [tabindex]:not([tabindex="-1"])');
      if (!focusable.length) return;
      const first = focusable[0], last = focusable[focusable.length - 1];
      if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
      else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
    };
    const onPaste = (e) => {
      const data = e.clipboardData;
      if (!data) return;
      // Copied cells or a web page carry text as well as a picture of it: paste the text.
      if (data.types && Array.from(data.types).includes("text/plain")) return;
      for (const item of data.items || []) {
        if (item.kind === "file" && item.type.startsWith("image/")) {
          e.preventDefault();
          latest.current.pick(item.getAsFile());
          return;
        }
      }
    };
    document.addEventListener("keydown", onKey);
    document.addEventListener("paste", onPaste);
    const t = setTimeout(() => textRef.current && textRef.current.focus(), 50);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("paste", onPaste);
      clearTimeout(t);
    };
  }, [open]);

  async function send(e) {
    e.preventDefault();
    if (sending) return; // a slow POST must not become two tickets
    if (body.trim().length < 3) return setError("Tell us a little about it first.");
    const data = new FormData();
    data.append("body", body);
    data.append("page_url", window.location.href);
    data.append("page_title", document.title);
    data.append("viewport", `${window.innerWidth}x${window.innerHeight}`);
    if (shot) data.append("screenshot", shot, shot.name || "screenshot.png");
    setSending(true);
    setError("");
    try {
      const res = await apiFetch("/feedback", { method: "POST", body: data });
      if (!res.ok) throw new Error(await apiError(res, "Could not send your feedback"));
      setSentId((await res.json()).id);
    } catch (err) {
      setError(friendlyError(err));
    } finally {
      setSending(false);
    }
  }

  // A file dropped anywhere on the drawer is the screenshot (replacing one already there);
  // without this a near miss makes the browser open the image and lose the draft.
  const dropProps = {
    onDragOver: (e) => { e.preventDefault(); setOver(true); },
    onDragLeave: () => setOver(false),
    onDrop: (e) => { e.preventDefault(); setOver(false); if (e.dataTransfer.files[0]) pick(e.dataTransfer.files[0]); },
  };

  return (
    <>
      <button ref={charmRef} type="button" className="fb-charm" aria-expanded={open}
              aria-controls="fb-drawer" onClick={() => (open ? close() : setOpen(true))}>
        Feedback
      </button>
      {open && <div className="fb-backdrop" onClick={close} onDragOver={(e) => e.preventDefault()} onDrop={(e) => e.preventDefault()} />}
      {open && (
        <aside id="fb-drawer" ref={drawerRef} className="fb-drawer" role="dialog" aria-modal="true"
               aria-labelledby="fb-title" {...dropProps}>
          <header>
            <h3 id="fb-title">Send feedback</h3>
            <button type="button" className="fb-close secondary outline" aria-label="Close" onClick={close}>×</button>
          </header>
          {sentId !== null ? (
            <div role="status">
              <p><strong>Thank you, that's sent.</strong></p>
              <p>Your reference is #{sentId}.</p>
              <button type="button" onClick={close}>Close</button>
            </div>
          ) : (
            <form onSubmit={send}>
              <p><small>From this page: {document.title || window.location.hash}</small></p>
              <label>
                What happened, or what would help?
                <textarea ref={textRef} name="body" rows={6} maxLength={5000} value={body}
                          onChange={(e) => setBody(e.target.value)} />
              </label>
              {thumb ? (
                <div className="fb-preview">
                  <img src={thumb} alt="Screenshot to send" />
                  <button type="button" className="secondary outline" onClick={unpick}>Remove screenshot</button>
                </div>
              ) : (
                <div className={over ? "fb-drop fb-drop-over" : "fb-drop"}>
                  <small>Screenshot (optional): paste it, drop it here, or </small>
                  <label className="fb-file">
                    <small>choose a file</small>
                    <input ref={fileRef} type="file" name="screenshot" accept="image/png,image/jpeg,image/gif,image/webp"
                           onChange={(e) => pick(e.target.files[0])} />
                  </label>
                </div>
              )}
              {error && <p className="form-error" role="alert">{error}</p>}
              <button type="submit" aria-busy={sending} disabled={sending}>Send</button>
            </form>
          )}
        </aside>
      )}
    </>
  );
}
