// HomeScreen.jsx

const COURSES = [
  { title: "ME 80: Mechanics of Materials", tint: "amber", lastPracticed: "5. 12. 26", progress: 44, icon: "M4 18c3-6 5-9 8-9s5 3 8 9 M10 9V5 M14 9V5" },
  { title: "PHYSICS 43: Electricity and Magnetism", tint: "blue", lastPracticed: "5. 12. 26", progress: 18, icon: "M14 5l5 5-9 9H5v-5z M12 7l5 5" },
  { title: "MATH 21: Calculus", tint: "red", lastPracticed: "5. 12. 26", progress: 72, icon: "M4 6h16v12H4z M8 10h4 M8 14h8" },
  { title: "CS 161: Algorithms", tint: "green", lastPracticed: "4. 28. 26", progress: 60, icon: "M6 8l-3 4 3 4 M18 8l3 4-3 4 M14 4l-4 16" },
  { title: "CHEM 31: Thermodynamics", tint: "olive", lastPracticed: "4. 22. 26", progress: 32, icon: "M9 3v5L4 18a2 2 0 002 3h12a2 2 0 002-3l-5-10V3" },
  { title: "BIO 55: Molecular Biology", tint: "amber", lastPracticed: "4. 10. 26", progress: 15, icon: "M7 4c6 4 4 12 10 16 M17 4c-6 4 -4 12 -10 16" },
];

function EditableName() {
  const [name, setName] = React.useState(() => localStorage.getItem("didactic.userName") || "");
  const ref = React.useRef(null);

  const commit = (value) => {
    const v = (value || "").replace(/\s+/g, " ").trim();
    setName(v);
    localStorage.setItem("didactic.userName", v);
  };

  return (
    <span
      ref={ref}
      className={"editable-name" + (name ? "" : " editable-name-empty")}
      contentEditable
      suppressContentEditableWarning
      spellCheck={false}
      onBlur={(e) => commit(e.currentTarget.textContent)}
      onKeyDown={(e) => {
        if (e.key === "Enter") { e.preventDefault(); e.currentTarget.blur(); }
      }}
    >{name}</span>
  );
}

function HomeScreen({ onOpenCourse, onCreate }) {
  return (
    <section className="home">
      <header className="home-head">
        <div className="eyebrow">Welcome, <EditableName />.</div>
        <h1 className="serif-head">Let's get back to the action!</h1>
      </header>

      <button className="create-card" onClick={onCreate}>
        <div className="plus">
          <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" strokeWidth="1.75" fill="none">
            <path d="M12 5v14M5 12h14"/>
          </svg>
        </div>
        <div className="create-label">Create a new course</div>
      </button>

      <div className="section-label">Recents</div>
      <div className="courses-row">
        {COURSES.slice(0, 2).map(c => (
          <div key={c.title} onClick={() => onOpenCourse(c)} role="button">
            <CourseCard course={c} />
          </div>
        ))}
      </div>

      <div className="section-label">All courses</div>
      <div className="courses-grid">
        {COURSES.map(c => (
          <div key={c.title} onClick={() => onOpenCourse(c)} role="button">
            <CourseCard course={c} />
          </div>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { HomeScreen, COURSES });
