// Quizrs — Share / embed dialog (new-feature polish over the existing public link + embed.js).

function CopyField({ label, value, multiline }) {
  const [copied, setCopied] = React.useState(false);
  const copy = () => {
    navigator.clipboard?.writeText(value).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1400);
    }).catch(() => {});
  };
  return (
    <div style={{ marginBottom: 14 }}>
      <div className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", marginBottom: 7 }}>{label}</div>
      <div className="row" style={{ gap: 8, alignItems: "stretch" }}>
        {multiline
          ? <textarea readOnly value={value} className="mono" style={{ flex: 1, minHeight: 78, resize: "none", padding: "10px 12px",
              border: "1px solid var(--border)", borderRadius: "var(--r-sm)", background: "var(--surface-2)", color: "var(--ink-2)", fontSize: 12, lineHeight: 1.5 }} />
          : <input readOnly value={value} className="mono" style={{ flex: 1, padding: "10px 12px", border: "1px solid var(--border)",
              borderRadius: "var(--r-sm)", background: "var(--surface-2)", color: "var(--ink-2)", fontSize: 12.5 }} />}
        <Btn kind={copied ? "primary" : "ghost"} sm icon={copied ? "check" : "copy"} onClick={copy}
          style={multiline ? { alignSelf: "flex-start" } : null}>{copied ? "Copied" : "Copy"}</Btn>
      </div>
    </div>
  );
}

function ShareDialog({ quiz, onClose }) {
  const { shareUrlFor, siteUrl } = useStore();
  if (!quiz) return null;

  const isLive = quiz.status === "live";
  const url = shareUrlFor(quiz);
  const slug = quiz.publicId || quiz.id;
  const base = (siteUrl || "").replace(/\/+$/, "");
  const embed = `<div id="quizrs-widget"></div>\n<script src="${base}/embed.js"\n  data-quiz="${slug}"\n  data-theme="light"\n  async></script>`;
  const qr = url ? `https://api.qrserver.com/v1/create-qr-code/?size=160x160&margin=0&data=${encodeURIComponent(url)}` : null;

  return (
    <div className="qz-modal-backdrop" onClick={onClose}>
      <div className="qz-palette" style={{ maxWidth: 560 }} onClick={(e) => e.stopPropagation()}>
        <div className="card-pad" style={{ borderBottom: "1px solid var(--hairline)", display: "flex", alignItems: "center", gap: 10 }}>
          <Cover tint={quiz.tint} glyph={quiz.glyph} h={34} r={8} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 15, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Share “{quiz.title}”</div>
            <div className="muted" style={{ fontSize: 12.5 }}>{isLive ? "Public link is live" : "Publish first to enable the public link"}</div>
          </div>
          <Btn kind="ghost" sm icon="x" onClick={onClose} />
        </div>
        <div className="card-pad">
          {!isLive && (
            <ErrorNote>This quiz is a draft. Publish it from the Creator to activate the link and embed.</ErrorNote>
          )}
          <div className="row" style={{ gap: 18, alignItems: "flex-start" }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <CopyField label="Public link" value={url || "Publish to generate a link"} />
              <CopyField label="Embed snippet" value={embed} multiline />
            </div>
            {qr && isLive && (
              <div style={{ textAlign: "center", flex: "0 0 auto" }}>
                <div className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".4px", textTransform: "uppercase", marginBottom: 7 }}>QR</div>
                <img src={qr} width={140} height={140} alt="QR code"
                  style={{ borderRadius: "var(--r-sm)", border: "1px solid var(--border)", background: "#fff", padding: 6 }} />
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.ShareDialog = ShareDialog;
window.CopyField = CopyField;
