const { useState, useEffect, useMemo, useCallback, useRef, createContext, useContext } = React;

/* ─── Global App Context ─────────────────────────────────────────── */
const AppContext = createContext();

function useApp() { return useContext(AppContext); }

/* ─── Helpers ─────────────────────────────────────────────────────── */
function getSchool(districtCode, schoolCode) {
  const key = districtCode + "_" + schoolCode;
  const idx = window.CMAS.schoolIndex[key];
  return idx != null ? window.CMAS.schools[idx] : null;
}
function getDistrict(code) {
  const idx = window.CMAS.districtIndex[code];
  return idx != null ? window.CMAS.districts[idx] : null;
}
function fmt(v, decimals = 1) {
  if (v == null) return "—";
  return Number(v).toFixed(decimals);
}
function fmtPct(v) {
  if (v == null) return "—";
  return Number(v).toFixed(1) + "%";
}
function fmtOrd(n) {
  if (n == null) return "—";
  const s = ["th","st","nd","rd"];
  const v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function pctileClass(p) {
  if (p == null) return "mid";
  if (p >= 70) return "high";
  if (p >= 30) return "mid";
  return "low";
}
function deltaArrow(d) {
  if (d == null) return { cls: "flat", text: "—" };
  if (d > 0) return { cls: "up", text: "↑ " + Math.abs(d).toFixed(1) + " pp" };
  if (d < 0) return { cls: "down", text: "↓ " + Math.abs(d).toFixed(1) + " pp" };
  return { cls: "flat", text: "0.0 pp" };
}
function subjectColor(subj) {
  switch (subj) {
    case "ELA": return "var(--teal)";
    case "Math": return "var(--amber)";
    case "Science": return "var(--rose)";
    case "Spanish Language Arts": return "var(--indigo)";
    default: return "var(--text3)";
  }
}
function participationLevel(rate) {
  if (rate == null) return "green";
  if (rate >= 95) return "green";
  if (rate >= 85) return "yellow";
  return "red";
}

/* ─── SVG Icons (inline) ──────────────────────────────────────────── */
const Icons = {
  home: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>,
  school: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c0 1 2 3 6 3s6-2 6-3v-5"/></svg>,
  compare: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
  rankings: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>,
  district: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="2" width="16" height="20" rx="2"/><line x1="9" y1="6" x2="15" y2="6"/><line x1="9" y1="10" x2="15" y2="10"/><line x1="9" y1="14" x2="15" y2="14"/><line x1="9" y1="18" x2="15" y2="18"/></svg>,
  map: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/></svg>,
  search: () => <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
  collapse: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>,
  expand: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>,
  close: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  info: () => <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>,
};

/* ─── Sidebar ─────────────────────────────────────────────────────── */
const NAV_ITEMS = [
  { id: "overview", label: "Overview", icon: "home" },
  { id: "school", label: "School", icon: "school" },
  { id: "compare", label: "Compare", icon: "compare" },
  { id: "rankings", label: "Rankings", icon: "rankings" },
  { id: "district", label: "District", icon: "district" },
  { id: "map", label: "District Heatmap", icon: "map" },
];

function Sidebar({ page, setPage, collapsed, setCollapsed }) {
  return (
    <nav className={"sidebar" + (collapsed ? " collapsed" : "")}>
      <div className="sidebar-logo">
        <div className="logo-icon">C</div>
        <div className="logo-text"><span>CMAS</span> Colorado</div>
      </div>
      <div className="sidebar-nav">
        {NAV_ITEMS.map(item => {
          const Icon = Icons[item.icon];
          return (
            <button
              key={item.id}
              className={"nav-item" + (page === item.id ? " active" : "")}
              onClick={() => setPage(item.id)}
              title={item.label}
            >
              <Icon /><span className="nav-label">{item.label}</span>
            </button>
          );
        })}
      </div>
      <div className="sidebar-footer">
        {!collapsed && (
          <div style={{ padding: "0 12px 10px", fontSize: 11, color: "var(--text3)", lineHeight: 1.5 }}>
            <div style={{ fontWeight: 600 }}>Amai 2026</div>
            <a href="mailto:tian.yu.h@protonmail.com" style={{ color: "var(--text3)", textDecoration: "none" }}>tian.yu.h@protonmail.com</a>
          </div>
        )}
        <button className="collapse-btn" onClick={() => setCollapsed(!collapsed)}>
          {collapsed ? <Icons.expand /> : <Icons.collapse />}
          <span className="nav-label">{collapsed ? "" : "Collapse"}</span>
        </button>
      </div>
    </nav>
  );
}

/* ─── Top Filter Bar ──────────────────────────────────────────────── */
function TopBar({ page }) {
  const { year, setYear, subject, setSubject, showSLA, setShowSLA } = useApp();
  const pageTitle = NAV_ITEMS.find(n => n.id === page)?.label || "";
  return (
    <div className="topbar">
      <div className="topbar-title">{pageTitle === "Overview" ? "State Overview" : pageTitle}</div>
      <div className="filter-group">
        <span className="filter-label">YEAR</span>
        <select className="filter-select" value={year} onChange={e => setYear(e.target.value)}>
          {["2025","2024","2023","2022"].map(y => <option key={y} value={y}>{y}</option>)}
        </select>
      </div>
      <div className="filter-group">
        <span className="filter-label">SUBJECT</span>
        <select className="filter-select" value={subject} onChange={e => setSubject(e.target.value)}>
          <option value="ELA">ELA</option>
          <option value="Math">Math</option>
          <option value="Science">Science</option>
          {showSLA && <option value="Spanish Language Arts">SLA</option>}
        </select>
      </div>
      <div className={"toggle-pill" + (showSLA ? " on" : "")} onClick={() => setShowSLA(!showSLA)}>
        <div className="toggle-dot" />
        <span>SLA</span>
      </div>
    </div>
  );
}

/* ─── Compare Tray ────────────────────────────────────────────────── */
function CompareTray({ collapsed }) {
  const { compareList, removeFromCompare, setPage } = useApp();
  if (compareList.length === 0) return null;
  return (
    <div className={"compare-tray" + (collapsed ? " collapsed-sidebar" : "")}>
      <span style={{ fontSize: "12px", color: "var(--text3)", fontWeight: 600, marginRight: 4 }}>COMPARING:</span>
      {compareList.map(s => (
        <div className="compare-chip" key={s.districtCode + "_" + s.code}>
          <span>{s.name}</span>
          <button className="chip-remove" onClick={() => removeFromCompare(s.districtCode, s.code)}>
            <Icons.close />
          </button>
        </div>
      ))}
      <button className="compare-btn" onClick={() => setPage("compare")}>
        Compare {compareList.length} Schools
      </button>
    </div>
  );
}

/* ─── Main App ────────────────────────────────────────────────────── */
function App() {
  const [page, setPage] = useState("overview");
  const [collapsed, setCollapsed] = useState(false);
  const [year, setYear] = useState("2025");
  const [subject, setSubject] = useState("ELA");
  const [showSLA, setShowSLA] = useState(false);
  const [selectedSchool, setSelectedSchool] = useState(null); // { districtCode, schoolCode }
  const [selectedDistrict, setSelectedDistrict] = useState(null); // districtCode
  const [compareList, setCompareList] = useState([]); // [{ districtCode, code, name }]

  const addToCompare = useCallback((districtCode, schoolCode) => {
    if (compareList.length >= 5) return;
    const key = districtCode + "_" + schoolCode;
    if (compareList.some(c => c.districtCode + "_" + c.code === key)) return;
    const s = getSchool(districtCode, schoolCode);
    if (s) setCompareList(prev => [...prev, { districtCode, code: schoolCode, name: s.name }]);
  }, [compareList]);

  const removeFromCompare = useCallback((districtCode, schoolCode) => {
    setCompareList(prev => prev.filter(c => !(c.districtCode === districtCode && c.code === schoolCode)));
  }, []);

  const navigateToSchool = useCallback((districtCode, schoolCode) => {
    setSelectedSchool({ districtCode, schoolCode });
    setPage("school");
  }, []);

  const navigateToDistrict = useCallback((districtCode) => {
    setSelectedDistrict(districtCode);
    setPage("district");
  }, []);

  const ctx = {
    year, setYear, subject, setSubject, showSLA, setShowSLA,
    selectedSchool, selectedDistrict,
    compareList, addToCompare, removeFromCompare,
    navigateToSchool, navigateToDistrict, setPage,
  };

  const renderPage = () => {
    switch (page) {
      case "overview":  return <LandingPage />;
      case "school":    return <SchoolProfilePage />;
      case "compare":   return <ComparisonPage />;
      case "rankings":  return <RankingsPage />;
      case "district":  return <DistrictPage />;
      case "map":       return <MapPage />;
      default:          return <LandingPage />;
    }
  };

  return (
    <AppContext.Provider value={ctx}>
      <div className="app">
        <Sidebar page={page} setPage={setPage} collapsed={collapsed} setCollapsed={setCollapsed} />
        <div className="main">
          <TopBar page={page} />
          <div className="content" style={compareList.length > 0 ? { paddingBottom: 60 } : undefined}>
            {renderPage()}
          </div>
        </div>
        <CompareTray collapsed={collapsed} />
      </div>
    </AppContext.Provider>
  );
}

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