/* Floating feedback widget. A small tab pinned bottom-right that opens a compact
   panel: quick thumbs (optional) + a free-text box. Writes one row to the
   Supabase `feedback` table (anon key, fire-and-forget — same posture as
   NewsletterSignup / affiliate clicks). A Supabase DB webhook on that insert
   emails the team via /api/notify (table "feedback"); storage works even if the
   webhook isn't set up yet.

   Placed bottom-RIGHT so it never collides with the bottom-left prototype data
   switcher (.proto-sw). Reuses the --paper / --ink / --accent design tokens.

   Usage: <FeedbackWidget page="collection" user={user} /> */

(function () {
  const { useState, useEffect, useRef } = React;

  function FeedbackWidget({ page = "site", user = null }) {
    const [open, setOpen] = useState(false);
    const [msg, setMsg] = useState("");
    const [sentiment, setSentiment] = useState(null); // 'up' | 'down' | null
    const [state, setState] = useState("idle");        // idle | saving | done | error
    const [atFooter, setAtFooter] = useState(false);   // tuck the launcher away over the footer
    const areaRef = useRef(null);

    // The launcher is position:fixed bottom-right; over the footer it can cover
    // footer links / podium cards. Fade it out while the footer is in view (but
    // never while the panel is open, so an in-progress note is never hidden).
    useEffect(() => {
      const footer = document.querySelector("footer");
      if (!footer || typeof IntersectionObserver === "undefined") return;
      const io = new IntersectionObserver(
        (entries) => setAtFooter(entries[0].isIntersecting),
        { rootMargin: "0px 0px -8px 0px" }
      );
      io.observe(footer);
      return () => io.disconnect();
    }, []);

    // Focus the textarea when the panel opens.
    useEffect(() => {
      if (open && areaRef.current) {
        const t = setTimeout(() => areaRef.current && areaRef.current.focus(), 60);
        return () => clearTimeout(t);
      }
    }, [open]);

    // Close on Escape while the panel is open.
    useEffect(() => {
      if (!open) return;
      function onKey(e) { if (e.key === "Escape") setOpen(false); }
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [open]);

    async function submit() {
      const value = (msg || "").trim();
      if (!value) { setState("error"); return; }
      setState("saving");
      try {
        if (window.BBR_supabase) {
          const { error } = await window.BBR_supabase.from("feedback").insert({
            message: value,
            sentiment,
            page,
            path: (typeof location !== "undefined" && location.pathname) || null,
            email: (user && user.email) || null,
            user_id: (user && user.id) || null,
            user_agent: (typeof navigator !== "undefined" && navigator.userAgent) || null,
          });
          if (error) throw error;
        }
        setState("done");
        // Reset shortly after the thank-you, then auto-close.
        setTimeout(() => {
          setOpen(false);
          setState("idle");
          setMsg("");
          setSentiment(null);
        }, 2200);
      } catch (e) {
        console.error("[BBR] feedback failed", e);
        setState("error");
      }
    }

    return (
      <div className={"fbw" + (open ? " fbw-open" : "") + (atFooter && !open ? " fbw--hidden" : "")}>
        {open && (
          <div className="fbw-panel" role="dialog" aria-label="Send feedback">
            {state === "done" ? (
              <div className="fbw-done">
                <span className="fbw-tick">✓</span>
                <div className="fbw-done-t">Thank you</div>
                <div className="fbw-done-s">We read every note — it genuinely shapes what we build next.</div>
              </div>
            ) : (
              <React.Fragment>
                <div className="fbw-head">
                  <div className="fbw-title">Got a second?</div>
                  <button className="fbw-x" onClick={() => setOpen(false)} aria-label="Close">✕</button>
                </div>
                <div className="fbw-sub">Tell us what’s working, what’s missing, or what you’d love to see.</div>
                <div className="fbw-mood">
                  <button
                    type="button"
                    className={"fbw-mood-b" + (sentiment === "up" ? " on" : "")}
                    onClick={() => setSentiment(sentiment === "up" ? null : "up")}
                    aria-label="Thumbs up"
                  >👍</button>
                  <button
                    type="button"
                    className={"fbw-mood-b" + (sentiment === "down" ? " on down" : "")}
                    onClick={() => setSentiment(sentiment === "down" ? null : "down")}
                    aria-label="Thumbs down"
                  >👎</button>
                </div>
                <textarea
                  ref={areaRef}
                  className="fbw-area"
                  rows={4}
                  placeholder="Your feedback…"
                  value={msg}
                  onChange={(e) => { setMsg(e.target.value); if (state === "error") setState("idle"); }}
                  onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) submit(); }}
                  maxLength={2000}
                />
                {state === "error" && <div className="fbw-err">Please add a note (or try again in a moment).</div>}
                <button className="fbw-send" onClick={submit} disabled={state === "saving"}>
                  {state === "saving" ? "Sending…" : "Send feedback"}
                </button>
                <div className="fbw-foot">Goes straight to the team{user && user.email ? "" : " — no sign-in needed"}.</div>
              </React.Fragment>
            )}
          </div>
        )}
        <button
          className="fbw-tab"
          onClick={() => setOpen((o) => !o)}
          aria-expanded={open}
          aria-label={open ? "Close feedback" : "Send feedback"}
        >
          {open ? (
            <span className="fbw-tab-x">✕</span>
          ) : (
            <React.Fragment>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
              <span className="fbw-tab-t">Feedback</span>
            </React.Fragment>
          )}
        </button>
      </div>
    );
  }

  window.FeedbackWidget = FeedbackWidget;
})();
