// JoinBlock + ZoomShareOverlay + ZoomChatCopy
// QR is generated client-side via the qrcode-generator UMD library loaded in the HTML.

const { useState: useStateJ, useEffect: useEffectJ, useMemo, useRef: useRefJ } = React;

function makeQrSvg(text, opts = {}) {
  const { margin = 1, dark = "#0E1F14", light = "transparent" } = opts;
  if (typeof window.qrcode !== "function") return "";
  try {
    // typeNumber 0 = auto-fit, error correction "M" = ~15% (good middle ground)
    const qr = window.qrcode(0, "M");
    qr.addData(text);
    qr.make();
    const count = qr.getModuleCount();
    const size = count + margin * 2;
    let cells = "";
    for (let r = 0; r < count; r++) {
      for (let c = 0; c < count; c++) {
        if (qr.isDark(r, c)) {
          cells += `<rect x="${c + margin}" y="${r + margin}" width="1.02" height="1.02" fill="${dark}"/>`;
        }
      }
    }
    return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" shape-rendering="crispEdges" preserveAspectRatio="xMidYMid meet">
      <rect width="100%" height="100%" fill="${light}"/>
      ${cells}
    </svg>`;
  } catch (e) {
    console.warn("QR generation failed:", e);
    return "";
  }
}

function QRCode({ text, size = 160, dark = "#0E1F14", light = "transparent" }) {
  // Library loads async; re-render once available.
  const [ready, setReady] = useStateJ(typeof window.qrcode === "function");
  useEffectJ(() => {
    if (ready) return;
    const i = setInterval(() => {
      if (typeof window.qrcode === "function") {
        setReady(true);
        clearInterval(i);
      }
    }, 100);
    return () => clearInterval(i);
  }, [ready]);

  const svg = useMemo(() => (ready ? makeQrSvg(text, { dark, light }) : ""), [ready, text, dark, light]);

  if (!ready) {
    return (
      <div className="qr-fallback" style={{ width: size, height: size }} aria-label="Generating QR code">
        <span>QR…</span>
      </div>
    );
  }
  return (
    <div
      className="qr-svg"
      style={{ width: size, height: size }}
      role="img"
      aria-label={`QR code linking to ${text}`}
      dangerouslySetInnerHTML={{ __html: svg }}
    />
  );
}

function prettyUrl(url) {
  return (url || "").replace(/^https?:\/\//, "").replace(/\/$/, "");
}

function copyText(text) {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    return navigator.clipboard.writeText(text);
  }
  // Fallback
  const ta = document.createElement("textarea");
  ta.value = text;
  ta.style.position = "fixed"; ta.style.opacity = "0";
  document.body.appendChild(ta);
  ta.select();
  try { document.execCommand("copy"); } catch (_) {}
  document.body.removeChild(ta);
  return Promise.resolve();
}

function useTweakValue(key, fallback) {
  // Reads from TWEAK_DEFAULTS and live-updates when the Tweaks panel dispatches
  // 'tweakchange' (the in-page event peer to __edit_mode_set_keys).
  const [val, setVal] = useStateJ(() => {
    const t = window.TWEAK_DEFAULTS || {};
    return t[key] !== undefined ? t[key] : fallback;
  });
  useEffectJ(() => {
    const onChange = (e) => {
      const edits = (e && e.detail) || {};
      if (key in edits) setVal(edits[key]);
    };
    window.addEventListener("tweakchange", onChange);
    return () => window.removeEventListener("tweakchange", onChange);
  }, [key]);
  return val;
}

// ───────── JoinBlock (compact, on Welcome screen) ─────────

function JoinBlock({ onShowOnZoom, isPresenter }) {
  const joinUrl = useTweakValue("joinUrl", "https://reset.webinar.com");
  const joinCode = useTweakValue("joinCode", "RESET");
  const eventTimeLabel = useTweakValue("eventTimeLabel", "Self-guided · About 30–40 minutes");
  const [copied, setCopied] = useStateJ(false);

  const handleCopy = async () => {
    await copyText(joinUrl);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  return (
    <div className="join-block" role="region" aria-label="Join this session">
      <div className="jb-head">
        <div className="eyebrow">Live now</div>
        <h3 className="jb-title">{eventTimeLabel}</h3>
        <p className="caption">
          Open this companion on your phone or laptop. No sign-in. Your answers stay on your own device.
        </p>
      </div>

      <div className="jb-body">
        <div className="jb-qr-wrap">
          <QRCode text={joinUrl} size={150} />
          <div className="jb-qr-cap">Scan with phone camera</div>
        </div>

        <div className="jb-info">
          <div className="jb-row">
            <div className="jb-row-label">On a phone</div>
            <div className="jb-row-val">Scan the code →</div>
          </div>
          <div className="jb-row">
            <div className="jb-row-label">On a laptop</div>
            <div className="jb-row-val jb-url">{prettyUrl(joinUrl)}</div>
          </div>
          <div className="jb-row">
            <div className="jb-row-label">Join code</div>
            <div className="jb-row-val jb-code">{joinCode}</div>
          </div>
          <div className="jb-actions">
            <button className="jb-btn jb-btn-ghost" onClick={handleCopy}>
              {copied ? "✓ Copied" : "Copy link"}
            </button>
            {isPresenter && onShowOnZoom && (
              <button className="jb-btn jb-btn-primary" onClick={onShowOnZoom}>
                Show fullscreen on Zoom
              </button>
            )}
          </div>
        </div>
      </div>

      {isPresenter && <ZoomChatCopy joinUrl={joinUrl} joinCode={joinCode} eventTimeLabel={eventTimeLabel} />}
    </div>
  );
}

// ───────── ZoomChatCopy — paste-ready block for Zoom chat ─────────

function ZoomChatCopy({ joinUrl, joinCode, eventTimeLabel }) {
  const text = useMemo(() => (
`📱 Companion app for today's webinar — open on your phone or laptop:
${joinUrl}

Join code: ${joinCode}
${eventTimeLabel ? `When: ${eventTimeLabel}\n` : ""}
• Phone: scan the QR I'm showing on screen, or open the link above
• Laptop: open the link in a new tab and keep Zoom visible too
• No sign-in. Your answers stay private on your own device.`
  ), [joinUrl, joinCode, eventTimeLabel]);
  const [copied, setCopied] = useStateJ(false);

  const handleCopy = async () => {
    await copyText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  return (
    <div className="zoom-chat">
      <div className="zc-head">
        <div className="eyebrow">For the Zoom chat</div>
        <div className="zc-sub">Paste this so participants who didn't catch the QR can still join.</div>
      </div>
      <pre className="zc-pre">{text}</pre>
      <button className="jb-btn jb-btn-primary" onClick={handleCopy} style={{ marginTop: 10 }}>
        {copied ? "✓ Copied — now paste in Zoom chat" : "Copy for Zoom chat"}
      </button>
    </div>
  );
}

// ───────── ZoomShareOverlay — fullscreen takeover for presenter ─────────

function ZoomShareOverlay({ open, onClose }) {
  const joinUrl = useTweakValue("joinUrl", "https://reset.webinar.com");
  const joinCode = useTweakValue("joinCode", "RESET");
  const eventName = useTweakValue("eventName", "Reset Webinar");
  const eventTimeLabel = useTweakValue("eventTimeLabel", "");

  useEffectJ(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div className="zoom-overlay" role="dialog" aria-modal="true" aria-label="Join screen for Zoom share">
      <button className="zo-close" onClick={onClose} aria-label="Hide join screen">
        Hide  ✕
      </button>

      <div className="zo-inner">
        <div className="zo-eyebrow">Join the companion app</div>
        <h1 className="zo-title">{eventName}</h1>
        {eventTimeLabel && <div className="zo-time">{eventTimeLabel}</div>}

        <div className="zo-grid">
          <div className="zo-qr-card">
            <QRCode text={joinUrl} size={360} />
            <div className="zo-qr-cap">Scan with your phone camera</div>
          </div>

          <div className="zo-info">
            <div className="zo-block">
              <div className="zo-label">On a laptop, go to</div>
              <div className="zo-url">{prettyUrl(joinUrl)}</div>
            </div>
            <div className="zo-divider" aria-hidden="true">or</div>
            <div className="zo-block">
              <div className="zo-label">Join code</div>
              <div className="zo-code">{joinCode}</div>
            </div>
            <ul className="zo-bullets">
              <li>No sign-in. Your answers stay on your own device.</li>
              <li>You can keep Zoom and the app open side by side.</li>
              <li>Tap the link as soon as you've arrived.</li>
            </ul>
          </div>
        </div>

        <div className="zo-foot">
          Press <kbd>Esc</kbd> or click <strong>Hide</strong> to return to the presenter view.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { JoinBlock, ZoomShareOverlay, ZoomChatCopy, QRCode });
