// Course catalog browser — backed by the real UofSC course catalog (/api/courses/search).
// The backend picks undergrad vs. graduate courses based on the student's profile.
function CoursesView({ setView, currentUser }) {
  const isGraduate = currentUser && currentUser.studentType === "graduate";
  const [q, setQ] = React.useState("");
  const [dept, setDept] = React.useState("All");
  const [results, setResults] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const searchTimer = React.useRef(null);
  const depts = ["All", "ACCT", "BADM", "ECON", "FINA", "IBUS", "MGMT", "MGSC", "MKTG"];

  React.useEffect(() => {
    if (!q.trim() && dept === "All") { setResults([]); setLoading(false); return; }

    setLoading(true);
    if (searchTimer.current) clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(async () => {
      try {
        const token = localStorage.getItem("token");
        const params = new URLSearchParams({ limit: "50" });
        if (q.trim()) params.set("q", q.trim());
        if (dept !== "All") params.set("department", dept);
        const res = await fetch(`${window.API_BASE}/api/courses/search?${params.toString()}`, {
          headers: { "Authorization": "Bearer " + token },
        });
        const data = await res.json();
        setResults(Array.isArray(data) ? data : []);
      } catch (e) {
        setResults([]);
      } finally {
        setLoading(false);
      }
    }, 250);
    return () => clearTimeout(searchTimer.current);
  }, [q, dept]);

  return (
    <div className="view-wrap">
      <div className="view-head">
        <div>
          <h2>Course <em>catalog</em></h2>
          <p>Search UofSC's course catalog. Click to ask your advisor how a course fits your plan.</p>
        </div>
      </div>

      <div className="catalog">
        <div className="catalog-search">
          <I.search />
          <input placeholder={isGraduate
              ? "Search by code or title · try \"ACCT 621\" or \"advanced accounting\""
              : "Search by code or title · try \"FINA 469\" or \"financial statement\""}
            value={q} onChange={(e)=>setQ(e.target.value)} />
          <span style={{fontFamily:"var(--mono)", fontSize:11, color:"var(--ink-4)"}}>
            {loading ? "searching…" : (q.trim() || dept !== "All") ? `${results.length} results` : ""}
          </span>
        </div>

        <div className="filter-chips">
          {depts.map(d => (
            <button key={d} className={`filter-chip ${dept===d?"active":""}`} onClick={()=>setDept(d)}>{d}</button>
          ))}
        </div>

        {!q.trim() && dept === "All" && (
          <p className="chip-empty">Search a course code, title, or pick a department to browse.</p>
        )}

        {(q.trim() || dept !== "All") && !loading && results.length === 0 && (
          <p className="chip-empty">No courses matched.</p>
        )}

        {results.map(c => (
          <div className="course-card" key={c.code}>
            <div className="cc-code">
              {c.code}
              <small>{c.credits} cr · {c.department}</small>
            </div>
            <div>
              <div className="cc-title">{c.title}</div>
              <div className="cc-desc">{c.description}</div>
              <div className="cc-meta">
                <span>PREREQ · <b>{c.prerequisites && c.prerequisites.codes && c.prerequisites.codes.length ? c.prerequisites.codes.join(", ") : "None"}</b></span>
              </div>
            </div>
            <div className="cc-actions">
              <button className="btn primary" onClick={() => setView && setView("chat")}>Ask advisor</button>
              <button className="btn" onClick={() => setView && setView("plan")}>+ Add to plan</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.CoursesView = CoursesView;
