/* iBD Coliseum — lightweight submission modal (+ masking gate) */

const SCREENSHOT_ACCEPT = ["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"];
const SCREENSHOT_MAX_DIM = 1200;
const SCREENSHOT_MAX_BYTES = 750000;

async function compressScreenshot(file) {
  const bitmap = await createImageBitmap(file);
  try {
    const cap = Math.min(SCREENSHOT_MAX_DIM, Math.max(bitmap.width, bitmap.height));
    const scale = Math.min(1, cap / Math.max(bitmap.width, bitmap.height));
    const w = Math.max(1, Math.round(bitmap.width * scale));
    const h = Math.max(1, Math.round(bitmap.height * scale));
    const canvas = document.createElement("canvas");
    canvas.width = w;
    canvas.height = h;
    canvas.getContext("2d").drawImage(bitmap, 0, 0, w, h);
    return canvas.toDataURL("image/webp", 0.85);
  } finally {
    bitmap.close && bitmap.close();
  }
}

function SubmitModal({ onClose, onSubmit, tone, context, missionTitle, accent, initial }) {
  const { CATEGORIES, TOOLS, storedEntryLink } = window.COLISEUM_DATA;
  const isMission = context === "mission";
  const isEdit = !!initial;
  const init = initial || {};
  const [title, setTitle] = useState(init.title || "");
  const [desc, setDesc] = useState(init.desc || "");
  const [cat, setCat] = useState(init.cat || "");
  const [tools, setTools] = useState(init.tools || []);
  const [skill, setSkill] = useState(init.skill || "");
  const [outputImage, setOutputImage] = useState(init.detail?.outputImage || init.outputImage || "");
  const [screenshotName, setScreenshotName] = useState(outputImage ? "Saved screenshot" : "");
  const [screenshotError, setScreenshotError] = useState("");
  const screenshotRef = React.useRef(null);
  const [reproText, setReproText] = useState(
    (init.reproSteps && init.reproSteps.length && init.reproSteps.join("\n"))
    || init.detail?.prompt
    || init.prompt
    || ""
  );
  const [stage, setStage] = useState("form"); // form | done

  const toolList = Object.keys(TOOLS);
  const toggleTool = (t) => setTools(ts => ts.includes(t) ? ts.filter(x => x !== t) : [...ts, t]);

  const canSubmit = title.trim() && desc.trim() && cat && tools.length && storedEntryLink(skill);

  const onScreenshotPick = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = "";
    if (!file) return;
    if (!SCREENSHOT_ACCEPT.includes(file.type)) {
      setScreenshotError("Use a PNG, JPEG, WebP, GIF, or AVIF image.");
      return;
    }
    setScreenshotError("");
    try {
      const dataUrl = await compressScreenshot(file);
      if (dataUrl.length > SCREENSHOT_MAX_BYTES) {
        setScreenshotError("That image is too large after compression — try a smaller screenshot.");
        return;
      }
      setOutputImage(dataUrl);
      setScreenshotName(file.name);
    } catch (err) {
      console.error(err);
      setScreenshotError("Could not read that image. Try another file.");
    }
  };

  const clearScreenshot = () => {
    setOutputImage("");
    setScreenshotName("");
    setScreenshotError("");
  };

  const submit = () => {
    if (!canSubmit) return;
    const reproSteps = reproText
      .split(/\n+/)
      .map((line) => line.trim())
      .filter(Boolean);
    onSubmit({
      title: title.trim(),
      desc: desc.trim(),
      cat,
      tools,
      skill: storedEntryLink(skill),
      prompt: reproText.trim(),
      output: "",
      reproSteps,
      outputImage,
    });
    setStage("done");
  };

  const accentStyle = accent ? { "--accent": accent } : undefined;

  return (
    <div className="overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" style={accentStyle}>
        {stage === "form" ? (
          <>
            <div className="mhead">
              <div>
                <div className="eyebrow">{isMission ? `Mission entry${missionTitle ? " · " + missionTitle : ""}` : "Always-on gallery"}</div>
                <h2>{isEdit ? "Edit your entry" : (isMission ? "Enter this mission" : (tone === "neutral" ? "New submission" : "Share one thing you tried"))}</h2>
                <p>{isEdit
                  ? "Update your submission — changes show everywhere it appears."
                  : (isMission
                  ? "Same as a gallery card — a headline, how you did it, and the recipe. Your entry also lands in the gallery."
                  : "Title, a line, and how you did it. Takes about 3 minutes — no scoring, no ranking.")}</p>
              </div>
              <button className="x" onClick={onClose} aria-label="Close"><Icon name="x" className="ic" style={{ width: 16, height: 16 }} /></button>
            </div>

            <div className="mbody">
              <div className="field">
                <label>What did you do? <span className="req">*</span></label>
                <input type="text" maxLength={70} value={title} placeholder="e.g. Cut my weekly report from 3 hrs to 20 min"
                  onChange={e => setTitle(e.target.value)} />
                <span className="charcount">{title.length}/70</span>
              </div>

              <div className="field">
                <label>One line on how it helped <span className="req">*</span></label>
                <textarea maxLength={240} value={desc} placeholder="Used [tool] for [task] and it saved / improved [effect]…"
                  onChange={e => setDesc(e.target.value)}></textarea>
                <span className="charcount">{desc.length}/240</span>
              </div>

              <div className="field">
                <label>Category <span className="req">*</span></label>
                <div className="tagpick">
                  {CATEGORIES.map(c => (
                    <button key={c.id} aria-pressed={cat === c.id} onClick={() => setCat(c.id)}>{c.label}</button>
                  ))}
                </div>
              </div>

              <div className="field">
                <label>Tools used <span className="req">*</span></label>
                <div className="tagpick">
                  {toolList.map(t => (
                    <button key={t} aria-pressed={tools.includes(t)} onClick={() => toggleTool(t)}>{t}</button>
                  ))}
                </div>
              </div>

              <div className="field">
                <label>How to reproduce it <span className="hint">— optional, but it's what makes this a learning resource</span></label>
                <textarea
                  value={reproText}
                  onChange={(e) => setReproText(e.target.value)}
                  placeholder="Paste the prompt or list the steps a colleague could follow…"
                  style={{ minHeight: 60 }}
                ></textarea>
                <span className="hint">Optional — paste the prompt or steps a colleague could follow.</span>
              </div>

              <div className="field">
                <label>Link or skill file <span className="req">*</span></label>
                <input type="url" value={skill} placeholder="https://claude.ai/project/… or https://…/file.xlsx"
                  onChange={e => setSkill(e.target.value)} />
                <span className="hint">Paste a <strong>Claude link</strong> (<code>claude.ai/…</code>) or a <strong>file URL</strong> with a common extension — e.g. <code>.skill</code>, <code>.pdf</code>, <code>.xlsx</code>, <code>.zip</code>, <code>.md</code>, <code>.csv</code>, images, and more.</span>
              </div>

              <div className="field">
                <label>Output screenshot <span className="hint">— optional</span></label>
                <input ref={screenshotRef} type="file" accept="image/png,image/jpeg,image/webp,image/gif,image/avif" hidden onChange={onScreenshotPick} />
                {!outputImage ? (
                  <button type="button" className="file-drop" onClick={() => screenshotRef.current && screenshotRef.current.click()}>
                    <Icon name="plus" className="ic" />
                    <span>
                      Add a screenshot of Claude's output
                      <span className="fd-hint">PNG, JPEG, WebP, or GIF · shown on your card detail</span>
                    </span>
                  </button>
                ) : (
                  <>
                    <div className="file-chip">
                      <Icon name="check" className="ic" />
                      <span className="fc-name">{screenshotName}</span>
                      <button type="button" className="fc-x" onClick={clearScreenshot} aria-label="Remove screenshot"><Icon name="x" className="ic" /></button>
                    </div>
                    <img className="submit-shot-preview" src={outputImage} alt="Output screenshot preview" />
                  </>
                )}
                {screenshotError && <span className="hint" style={{ color: "var(--danger, #c0392b)" }}>{screenshotError}</span>}
              </div>
            </div>

            <div className="mfoot">
              <span className="left"><Icon name="shield" className="ic" style={{ width: 14, height: 14, color: "var(--accent)" }} />Visible inside the org only · retained as a learning asset</span>
              <button className="btn btn-primary" disabled={!canSubmit} onClick={submit}
                style={!canSubmit ? { opacity: 0.45, cursor: "not-allowed" } : {}}>
                {isEdit ? "Save changes" : (isMission ? "Post entry" : "Post to gallery")}<Icon name="arrow" className="ic" />
              </button>
            </div>
          </>
        ) : (
          <div className="done-state">
            <div className="ring"><Icon name="check" className="ic" /></div>
            <h2>{isEdit ? "Saved. ✨" : (isMission ? "Entry posted. Nice one. 🎉" : "Posted. Nice one. 🎉")}</h2>
            <p>{isEdit
              ? "Your changes are live everywhere this entry appears."
              : (isMission
              ? "Your entry is live on the mission and in the gallery. Colleagues can upvote it and follow your recipe."
              : "Your card is live in the gallery. No scores, no ranking — just one more example a colleague can learn from. That's the whole point.")}</p>
            <button className="btn btn-primary btn-lg" onClick={onClose}>{isEdit ? "Done" : (isMission ? "Back to the mission" : "Back to the gallery")}</button>
          </div>
        )}
      </div>
    </div>
  );
}
window.SubmitModal = SubmitModal;
