/* ==================================================================
   Engine Config modal — curated subset (timer / navigation / scoring /
   atomic_block_shuffle). Loads current config from the test detail
   endpoint, PATCHes back to /api/tests/:display_id/engine-config.
   ================================================================== */

const EngineConfigModal = ({ test, onClose, onSaved }) => {
  const [cfg, setCfg] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    if (!test) { setCfg(null); setErr(""); return; }
    let cancelled = false;
    setLoading(true);
    window.AppApi.get(`/tests/${test.id}`)
      .then(d => { if (!cancelled) setCfg(d.engine_config); })
      .catch(e => { if (!cancelled) setErr(e.message || "failed to load config"); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [test]);

  if (!test) return null;

  const set = (path, value) => {
    setCfg(prev => {
      const next = JSON.parse(JSON.stringify(prev));
      const keys = path.split(".");
      let node = next;
      for (let i = 0; i < keys.length - 1; i++) node = node[keys[i]];
      node[keys[keys.length - 1]] = value;
      return next;
    });
  };

  const handleSave = async () => {
    setSaving(true); setErr("");
    try {
      const r = await window.AppApi.patch(`/tests/${test.id}/engine-config`, cfg);
      if (onSaved) onSaved(r.engine_config);
      onClose();
    } catch (e) {
      setErr(e.message || "failed to save");
    } finally {
      setSaving(false);
    }
  };

  const SectionTitle = ({ children }) => (
    <div className="ui-section-label" style={{ margin: "18px 0 6px", paddingBottom: 6,
                  borderBottom: "1px solid var(--line)" }}>{children}</div>
  );
  const Row = ({ label, children }) => (
    <label style={{ display: "grid", gridTemplateColumns: "minmax(0, 200px) 1fr", gap: 12,
                    alignItems: "center", minHeight: 40, padding: "4px 0", fontSize: 13, color: "var(--ink-1)" }}>
      <span>{label}</span>
      <span>{children}</span>
    </label>
  );
  const Num = ({ value, onChange, min, step = 1 }) => (
    <input type="number" value={value ?? 0} step={step} min={min}
      onChange={e => onChange(Number(e.target.value))}
      className="input" style={{ width: 120 }}/>
  );
  const Bool = ({ value, onChange }) => (
    <input type="checkbox" checked={!!value} onChange={e => onChange(e.target.checked)}
      style={{ width: 16, height: 16, accentColor: "var(--primary)" }}/>
  );

  return (
    <div className="ui-scrim" onClick={onClose} style={{ zIndex: 200 }}>
      <div className="ui-modal" role="dialog" aria-modal="true" aria-label="Engine config"
           style={{ width: "min(620px, 100%)" }} onClick={e => e.stopPropagation()}>
        <div className="ui-modal-head">
          <div style={{ minWidth: 0 }}>
            <div className="ui-section-label" style={{ marginBottom: 2 }}>
              <span className="mono">{test.id}</span> · Engine config
            </div>
            <div className="ui-modal-title">{test.title}</div>
          </div>
          <button type="button" className="ui-iconbtn ui-modal-close" aria-label="Close" onClick={onClose}>
            <window.AppUI.Icon name="x" size={16}/>
          </button>
        </div>

        <div className="ui-modal-body">
          {loading && <div style={{ color: "var(--ink-3)", fontSize: 13 }}>Loading…</div>}
          {!loading && cfg && (
            <>
              <SectionTitle>Timer</SectionTitle>
              <Row label="Type">
                <select value={cfg.timing.type}
                  onChange={e => set("timing.type", e.target.value)}
                  className="select" style={{ maxWidth: 320 }}>
                  <option value="global">Global (one timer for whole test)</option>
                  <option value="sectional">Sectional</option>
                  <option value="per_question">Per question</option>
                  <option value="none">None</option>
                </select>
              </Row>
              {cfg.timing.type !== "none" && cfg.timing.type !== "per_question" && (
                <Row label="Total duration (sec)">
                  <Num value={cfg.timing.duration_seconds} min={0}
                       onChange={v => set("timing.duration_seconds", v)}/>
                </Row>
              )}
              {cfg.timing.type === "per_question" && (
                <>
                  <Row label="Per-question (sec)">
                    <Num value={cfg.timing.per_question_duration ?? 60} min={0}
                         onChange={v => set("timing.per_question_duration", v)}/>
                  </Row>
                  <Row label="Hard-lock on timeout">
                    <Bool value={cfg.timing.hard_lock_on_timeout}
                          onChange={v => set("timing.hard_lock_on_timeout", v)}/>
                  </Row>
                </>
              )}
              {cfg.timing.type !== "none" && (
                <>
                  <Row label="Show timer to student">
                    <Bool value={cfg.timing.show_timer} onChange={v => set("timing.show_timer", v)}/>
                  </Row>
                  <Row label="Auto-submit on expiry">
                    <Bool value={cfg.timing.auto_submit_on_expiry}
                          onChange={v => set("timing.auto_submit_on_expiry", v)}/>
                  </Row>
                </>
              )}

              <SectionTitle>Navigation</SectionTitle>
              <Row label="Allow back-tracking">
                <Bool value={cfg.navigation.allow_back_tracking}
                      onChange={v => set("navigation.allow_back_tracking", v)}/>
              </Row>
              <Row label="Allow jumping (palette)">
                <Bool value={cfg.navigation.allow_jumping}
                      onChange={v => set("navigation.allow_jumping", v)}/>
              </Row>
              <Row label="Show question palette">
                <Bool value={cfg.navigation.show_question_palette}
                      onChange={v => set("navigation.show_question_palette", v)}/>
              </Row>

              <SectionTitle>Scoring</SectionTitle>
              <Row label="Correct marks">
                <Num value={cfg.scoring.correct_marks} step={0.25}
                     onChange={v => set("scoring.correct_marks", v)}/>
              </Row>
              <Row label="Wrong marks (negative ok)">
                <Num value={cfg.scoring.wrong_marks} step={0.25}
                     onChange={v => set("scoring.wrong_marks", v)}/>
              </Row>
              <Row label="Unattempted marks">
                <Num value={cfg.scoring.unattempted_marks} step={0.25}
                     onChange={v => set("scoring.unattempted_marks", v)}/>
              </Row>

              <SectionTitle>Logic</SectionTitle>
              <Row label="Atomic block shuffle">
                <Bool value={cfg.logic.atomic_block_shuffle}
                      onChange={v => set("logic.atomic_block_shuffle", v)}/>
              </Row>
              <div className="hint" style={{ marginTop: 4 }}>
                Keeps grouped questions (RC / DI passages) together when shuffling.
              </div>
            </>
          )}
          {err && <div className="ui-alert red" style={{ marginTop: 12 }}>{err}</div>}
        </div>

        <div className="ui-modal-foot">
          <button className="btn" onClick={onClose} disabled={saving}>Cancel</button>
          <button className="btn primary" onClick={handleSave}
                  disabled={saving || loading || !cfg}>
            {saving ? "Saving…" : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
};

window.EngineConfigModal = EngineConfigModal;
