/* ==================================================================
   Test picker modal — shown when user opens "Paper Evaluation" from sidebar
   ================================================================== */

const { Icon: TPIcon, StatusPill: TPStatusPill } = window.KXUI;

const TestPickerModal = ({ open, onClose, onPick }) => {
  const [search, setSearch] = React.useState("");
  const [classFilter, setClassFilter] = React.useState("All");
  const [subjectFilter, setSubjectFilter] = React.useState("All");

  if (!open) return null;

  // Only tests that can be evaluated — those with structured questions and uploaded scripts
  const candidates = window.KX.TESTS.filter(t => t.status === "grading" || t.status === "optimised" || t.status === "closed");
  const filtered = candidates.filter(t => {
    if (classFilter !== "All" && t.className !== classFilter) return false;
    if (subjectFilter !== "All" && t.subject !== subjectFilter) return false;
    if (search && !t.title.toLowerCase().includes(search.toLowerCase()) && !t.id.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const recent = filtered.slice(0, 3);
  const rest = filtered.slice(3);

  return (
    <div onClick={onClose} style={{ position:"fixed", inset: 0, background:"rgba(0,0,0,0.78)", zIndex: 250, display:"grid", placeItems:"center", padding: 30 }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:"var(--bg-1)", border:"1px solid var(--line-strong)", borderRadius: 10, width: 780, maxWidth:"100%", maxHeight:"86vh", display:"flex", flexDirection:"column" }}>
        <div style={{ padding:"14px 18px", borderBottom:"1px solid var(--line)", display:"flex", alignItems:"center", gap: 10 }}>
          <span style={{ color:"var(--accent)" }}><TPIcon name="sparkle" size={14}/></span>
          <div>
            <div style={{ color:"var(--ink-0)", fontSize: 14, fontWeight: 600 }}>Open Paper Evaluation</div>
            <div className="muted" style={{ fontSize: 11.5 }}>Pick a test to evaluate · only structured & uploaded tests are listed.</div>
          </div>
          <button className="btn sm ghost" style={{ marginLeft:"auto" }} onClick={onClose}>✕</button>
        </div>

        <div style={{ padding:"10px 18px", borderBottom:"1px solid var(--line)", display:"flex", gap: 8, alignItems:"center" }}>
          <div style={{ position:"relative", flex: 1 }}>
            <span style={{ position:"absolute", left: 10, top:"50%", transform:"translateY(-50%)", color:"var(--ink-3)" }}><TPIcon name="search" size={12}/></span>
            <input className="input" autoFocus placeholder="Search by name or ID…" value={search} onChange={e=>setSearch(e.target.value)} style={{ paddingLeft: 28, padding: "6px 10px 6px 28px", fontSize: 12.5 }}/>
          </div>
          <select className="select" value={classFilter} onChange={e=>setClassFilter(e.target.value)} style={{ width: 90, padding:"5px 8px", fontSize: 12 }}>
            <option>All</option><option>X</option><option>XI</option><option>XII</option>
          </select>
          <select className="select" value={subjectFilter} onChange={e=>setSubjectFilter(e.target.value)} style={{ width: 130, padding:"5px 8px", fontSize: 12 }}>
            <option>All</option><option>Chemistry</option><option>Physics</option><option>Mathematics</option><option>Biology</option>
          </select>
        </div>

        <div style={{ flex: 1, overflow:"auto", padding: 14 }}>
          {recent.length > 0 && (
            <>
              <div className="muted" style={{ fontSize: 10, letterSpacing:".09em", textTransform:"uppercase", margin:"4px 4px 8px" }}>Recent · in active grading</div>
              <div style={{ display:"grid", gap: 8, marginBottom: recent.length ? 18 : 0 }}>
                {recent.map(t => <TestPickerRow key={t.id} test={t} onPick={onPick} primary/>)}
              </div>
            </>
          )}
          {rest.length > 0 && (
            <>
              <div className="muted" style={{ fontSize: 10, letterSpacing:".09em", textTransform:"uppercase", margin:"4px 4px 8px" }}>All tests · {rest.length}</div>
              <div style={{ display:"grid", gap: 6 }}>
                {rest.map(t => <TestPickerRow key={t.id} test={t} onPick={onPick}/>)}
              </div>
            </>
          )}
          {filtered.length === 0 && (
            <div style={{ padding: 40, textAlign:"center", color:"var(--ink-3)", fontSize: 13 }}>
              No matching tests. Try widening the filters or upload scripts to a test first.
            </div>
          )}
        </div>

        <div style={{ padding:"10px 18px", borderTop:"1px solid var(--line)", display:"flex", alignItems:"center", gap: 8, fontSize: 11, color:"var(--ink-3)" }}>
          <TPIcon name="keyboard" size={11}/>
          <span>↑ ↓ to move · <span className="kbd">Enter</span> to open · <span className="kbd">Esc</span> to cancel</span>
          <span style={{ marginLeft:"auto" }}>{filtered.length} match{filtered.length === 1 ? "" : "es"}</span>
        </div>
      </div>
    </div>
  );
};

const TestPickerRow = ({ test, onPick, primary }) => {
  const pct = test.students ? Math.round(test.reviewed / test.students * 100) : 0;
  const pending = test.students - test.reviewed;
  return (
    <div onClick={() => onPick(test)}
      onMouseEnter={(e) => { e.currentTarget.style.background = "var(--bg-2)"; e.currentTarget.style.borderColor = "var(--accent)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = primary ? "var(--bg-2)" : "transparent"; e.currentTarget.style.borderColor = "var(--line)"; }}
      style={{
        display:"grid", gridTemplateColumns:"60px 1fr 100px 110px 100px", gap: 12, alignItems:"center",
        padding: primary ? "12px 14px" : "10px 12px",
        background: primary ? "var(--bg-2)" : "transparent",
        border:"1px solid var(--line)", borderRadius: 6, cursor:"pointer",
        transition:"background 0.12s, border-color 0.12s",
      }}>
      <span className="mono muted" style={{ fontSize: 11 }}>{test.id}</span>
      <div>
        <div style={{ color:"var(--ink-0)", fontSize: 13, fontWeight: 500 }}>{test.title}</div>
        <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{test.className} · {test.subject} · {test.chapter}</div>
      </div>
      <TPStatusPill status={test.status} scheduledDate={test.date} isExpired={test.is_expired}/>
      <div style={{ display:"flex", flexDirection:"column", gap: 3 }}>
        <div className="progress"><div style={{ width: pct + "%", background: test.status === "closed" ? "var(--green)" : "var(--accent)" }}></div></div>
        <span className="mono muted" style={{ fontSize: 10 }}>{test.reviewed}/{test.students} · {pending > 0 ? `${pending} pending` : "complete"}</span>
      </div>
      <button className="btn sm primary" style={{ justifySelf:"end" }} onClick={(e) => { e.stopPropagation(); onPick(test); }}>
        Open →
      </button>
    </div>
  );
};

window.TestPickerModal = TestPickerModal;
