/* global React, ReactDOM, window */
const { useState, useMemo } = React;

function suffix(n) {
  if (n === 11 || n === 12 || n === 13) return "th";
  const last = n % 10;
  return last === 1 ? "st" : last === 2 ? "nd" : last === 3 ? "rd" : "th";
}

function App() {
  const [studentName, setStudentName] = window.useLocalStorage("cb-student-name", window.ROADMAP.student_name);
  const [currentGrade, setCurrentGrade] = window.useLocalStorage("cb-current-grade", window.ROADMAP.current_grade);
  const [dateLabel, setDateLabel] = window.useLocalStorage("cb-date-label", window.ROADMAP.date_label);
  const [done, setDone] = window.useLocalStorage("cb-done", {});
  const [open, setOpen] = useState(null);
  const [focusYear, setFocusYear] = useState(null);
  const [focusTrack, setFocusTrack] = useState(null);

  // Expose state so grid can read current grade
  window.ROADMAP_STATE = { current_grade: currentGrade };

  const toggle = (id) => setDone((d) => ({ ...d, [id]: !d[id] }));

  const totalCount = window.MILESTONES.length;
  const doneCount = useMemo(() => Object.values(done).filter(Boolean).length, [done]);
  const pct = Math.round(doneCount / totalCount * 100);

  return (
    <>
      <div className="app">
        <div className="sheet">
          {/* Header */}
          <header className="sheet-header">
            <div className="sheet-title-wrap">
              <div className="sheet-eyebrow">
                <span className="logo-mono"><span className="mono-mark" aria-hidden="true"></span>CollegeBound</span>
                <span className="sep">·</span>
                <span>9th – 12th grade roadmap</span>
              </div>
              <h1 className="sheet-title">
                The plan for <window.Editable value={studentName} onChange={setStudentName} placeholder="Your student" />
              </h1>
              <p className="sheet-subtitle">
                Four years, two areas you need to focus on — <em>academic</em> and <em>non-academic</em>. The work starts ninth grade, not the summer before senior year.
              </p>
            </div>
            <div className="header-meta">
              <div className="meta-row">
                <span className="label">Currently</span>
                <span className="value">
                  <window.Editable
                    value={`${currentGrade}${suffix(currentGrade)} grade`}
                    onChange={(v) => {
                      const n = parseInt(v, 10);
                      if (n >= 9 && n <= 12) setCurrentGrade(n);
                    }} />
                  
                </span>
              </div>
              <div className="meta-row">
                <span className="label">Dated</span>
                <span className="value">
                  <window.Editable value={dateLabel} onChange={setDateLabel} />
                </span>
              </div>
            </div>
          </header>

          {/* Toolbar */}
          <div className="toolbar print-hide">
            <div className="toolbar-group">
              <span className="toolbar-label">Focus</span>
              <button className={window.cx("chip", !focusYear && !focusTrack && "active")}
              onClick={() => {setFocusYear(null);setFocusTrack(null);}}>All</button>
              {window.YEARS.map((y) =>
              <button key={y.id}
              className={window.cx("chip", focusYear === y.id && "active")}
              onClick={() => {setFocusYear(focusYear === y.id ? null : y.id);setFocusTrack(null);}}>
                  {y.id}{suffix(y.id)}
                </button>
              )}
              <span style={{ width: 12 }} />
              <button className={window.cx("chip", focusTrack === "academic" && "active")}
              onClick={() => {setFocusTrack(focusTrack === "academic" ? null : "academic");setFocusYear(null);}}>Academic</button>
              <button className={window.cx("chip", focusTrack === "nonacademic" && "active")}
              onClick={() => {setFocusTrack(focusTrack === "nonacademic" ? null : "nonacademic");setFocusYear(null);}}>Non-academic</button>
            </div>
            <div className="toolbar-group">
              <div className="progress-meter">
                <span>Progress</span>
                <div className="bar"><div className="bar-fill" style={{ width: `${pct}%` }} /></div>
                <span className="count">{doneCount} / {totalCount}</span>
              </div>
              <button className="toolbar-print" onClick={() => {
                const params = new URLSearchParams({
                  name: studentName,
                  grade: String(currentGrade),
                  date: dateLabel,
                  print: "1"
                });
                window.open("Roadmap-PDF.html?" + params.toString(), "_blank");
              }}>
                <window.Icons.Printer size={13} /> Print / PDF
              </button>
            </div>
          </div>

          {/* Grid */}
          <window.RoadmapGrid
            years={window.YEARS}
            bands={window.BANDS}
            milestones={window.MILESTONES}
            done={done}
            onToggle={toggle}
            onOpen={setOpen}
            focusYear={focusYear}
            focusTrack={focusTrack} />
          

          {/* Outcomes strip */}
          <div className="strip">
            <div className="strip-col">
              <h3>What this produces by senior spring</h3>
              <div className="outcomes">
                {window.OUTCOMES.map((o) =>
                <div className="outcome" key={o.name}>
                    <span className="oc-eyebrow">{o.eyebrow}</span>
                    <span className="oc-name">{o.name}</span>
                    <span className="oc-desc">{o.desc}</span>
                  </div>
                )}
              </div>
            </div>
            <div className="strip-col">
              <h3>How to read this</h3>
              <p style={{ fontSize: 12.5, lineHeight: 1.65, color: "var(--cb-warm-mid-gray)", fontWeight: 300 }}>
                A milestone spanning multiple years is a body of work, not a task — the bar shows where it lives in the timeline. Tap any milestone for the detail. The current grade column is shaded. One thing is picked out in <span style={{ color: "var(--cb-terracotta)", fontWeight: 500 }}>terracotta</span> — the Big Achievement. That's the centerpiece; treat the rest as the structure that makes it possible.
              </p>
              <div className="footnote" style={{ marginTop: 14 }}>
                <span>CollegeBound · <em>Clarity, Conviction, Craft.</em></span>
                <span>Rev. {dateLabel}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <window.Drawer
        m={open}
        onClose={() => setOpen(null)}
        done={open ? !!done[open.id] : false}
        onToggle={toggle} />
      
    </>);

}

const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(<App />);