/* ============================================================
   Share helpers — modal that calls /api/share and copies the URL.
   ============================================================ */

const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

// Tiny modal: opens, calls /api/share, shows the URL + Copy button.
// Use via:  ctx.openShare({ kind: "track"|"album", id: "..." })
//
// We wire it into App's ctx with a small piece of state.

function ShareModal({ ctx }) {
  const share = ctx.share;
  const isAdmin = !!ctx.me?.isAdmin;
  const Ic = window.Icons;
  const [data, setData] = useStateS(null);
  const [busy, setBusy] = useStateS(true);
  const [err, setErr] = useStateS("");
  const [copied, setCopied] = useStateS(false);

  useEffectS(() => {
    if (!share) return;
    setBusy(true); setErr(""); setData(null); setCopied(false);
    (async () => {
      try {
        const res = await fetch("/api/share", {
          method: "POST",
          credentials: "include",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ kind: share.kind, id: share.id }),
        });
        if (!res.ok) {
          const j = await res.json().catch(() => ({}));
          throw new Error(j.error || "Could not create share");
        }
        setData(await res.json());
      } catch (e) {
        setErr(e.message);
      }
      setBusy(false);
    })();
  }, [share?.kind, share?.id]);

  if (!share) return null;

  async function doCopy() {
    if (!data?.url) return;
    try {
      await navigator.clipboard.writeText(data.url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (e) {}
  }

  async function nativeShare() {
    if (!data?.url || !navigator.share) return doCopy();
    try {
      await navigator.share({
        title: share.label || "Discothèque",
        text: share.label || "Listen on Discothèque",
        url: data.url,
      });
    } catch (e) {}
  }

  return (
    <div className="qmenu-backdrop" onClick={ctx.closeShare}>
      <div className="qmenu" style={{ width: 460 }} onClick={(e) => e.stopPropagation()}>
        <h3>Share {share.kind}</h3>
        <p className="sub">
          {share.label && <span style={{ color: "var(--ink-2)" }}>{share.label}</span>}
        </p>

        {busy && <div style={{ color: "var(--ink-3)", padding: "12px 0" }}>Creating link…</div>}
        {err && <div style={{ color: "var(--pink)", padding: "12px 0" }}>{err}</div>}

        {data && (
          <>
            <div style={{
              background: "var(--bg-0)",
              border: "1px solid var(--line-strong)",
              borderRadius: 10,
              padding: "12px 14px",
              fontFamily: "var(--f-mono)",
              fontSize: 12,
              color: "var(--ink-2)",
              wordBreak: "break-all",
              userSelect: "all",
              marginBottom: 14,
            }}>{data.url}</div>

            <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 14 }}>
              <button
                onClick={doCopy}
                style={{
                  background: copied ? "var(--gold)" : "var(--pink)",
                  color: "var(--bg-0)",
                  padding: "12px 18px",
                  borderRadius: 999,
                  fontFamily: "var(--f-display)",
                  fontWeight: 800,
                  fontSize: 12,
                  letterSpacing: "0.18em",
                  textTransform: "uppercase",
                  flex: 1,
                }}
              >{copied ? "✓ Copied" : "Copy link"}</button>
              {typeof navigator !== "undefined" && navigator.share && (
                <button
                  onClick={nativeShare}
                  style={{
                    background: "var(--bg-3)",
                    color: "var(--ink)",
                    padding: "12px 18px",
                    borderRadius: 999,
                    fontFamily: "var(--f-display)",
                    fontWeight: 800,
                    fontSize: 12,
                    letterSpacing: "0.18em",
                    textTransform: "uppercase",
                  }}
                >Share…</button>
              )}
            </div>

            <div style={{
              fontSize: 12,
              color: "var(--ink-3)",
              lineHeight: 1.5,
              padding: "10px 14px",
              borderRadius: 10,
              background: data.public ? "rgba(245,193,75,0.08)" : "rgba(255,61,154,0.08)",
              border: "1px solid " + (data.public ? "rgba(245,193,75,0.3)" : "rgba(255,61,154,0.3)"),
            }}>
              {data.public ? (
                <>
                  <strong style={{ color: "var(--gold)" }}>Public link.</strong>{" "}
                  Anyone with this URL can listen — no login required. Preview card with cover art will show in iMessage, WhatsApp, etc.
                </>
              ) : (
                <>
                  <strong style={{ color: "var(--pink)" }}>Private link.</strong>{" "}
                  The recipient needs a Discothèque account to play. iMessage / WhatsApp will still show a cover-art preview card.
                </>
              )}
            </div>
          </>
        )}

        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 18 }}>
          <button
            onClick={ctx.closeShare}
            style={{ color: "var(--ink-3)", fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700 }}
          >Close</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ShareModal });
