/* ─── District Page ───────────────────────────────────────────────── */

function DistrictPage() {
  const { selectedDistrict, year, subject, showSLA, navigateToSchool, navigateToDistrict } = useApp();
  const data = window.CMAS;
  const psatData = window.PSAT;
  const [searchQuery, setSearchQuery] = useState("");
  const [searchFocused, setSearchFocused] = useState(false);
  const [schoolTypeFilter, setSchoolTypeFilter] = useState("all");

  const district = selectedDistrict ? getDistrict(selectedDistrict) : null;
  const subjects = showSLA ? ["ELA", "Math", "Science", "Spanish Language Arts"] : ["ELA", "Math", "Science"];
  const years = ["2022", "2023", "2024", "2025"];

  // ALL hooks must be called before any conditional return
  const searchResults = useMemo(() => {
    if (!searchQuery || searchQuery.length < 2) return [];
    const q = searchQuery.toLowerCase();
    return data.districts
      .filter(d => d.name.toLowerCase().includes(q))
      .slice(0, 10)
      .map(d => ({ name: d.name, code: d.code }));
  }, [searchQuery, data]);

  // District KPIs
  const kpiCards = useMemo(() => {
    if (!district) return [];
    return subjects.map(subj => {
      const d = district.years?.[year]?.[subj] || {};
      const prevYr = String(parseInt(year) - 1);
      const prevPct = district.years?.[prevYr]?.[subj]?.pct;
      const delta = (d.pct != null && prevPct != null) ? d.pct - prevPct : null;
      return {
        subject: subj,
        pct: d.pct,
        rank: d.stateRank,
        total: d.stateTotal,
        pctile: d.statePctile,
        delta: delta,
        color: CHART_COLORS[subj],
      };
    });
  }, [district, year, subjects]);

  // District trends
  const trendDatasets = useMemo(() => {
    if (!district) return [];
    return subjects.map(subj => ({
      label: subj,
      color: CHART_COLORS[subj],
      values: years.map(y => district.years?.[y]?.[subj]?.pct ?? null),
    }));
  }, [district, subjects]);

  // Schools in district — with type filtering
  const allDistSchools = useMemo(() => {
    if (!district) return [];
    return data.schools
      .filter(s => s.districtCode === district.code)
      .map(s => {
        const sd = s.years?.[year]?.[subject] || {};
        return {
          code: s.code,
          districtCode: s.districtCode,
          name: s.name,
          types: s.types || [],
          pct: sd.pct,
          tierPct: sd.tierPct || {},
          typeRanks: sd.typeRanks || {},
          distRank: sd.distRank,
          distTotal: sd.distTotal,
          stateRank: sd.stateRank,
          stateTotal: sd.stateTotal,
          statePctile: sd.statePctile,
          sparkline: years.map(y => s.years?.[y]?.[subject]?.pct ?? null),
        };
      });
  }, [data, district, year, subject]);

  // Filtered by selected type
  const distSchools = useMemo(() => {
    let filtered = allDistSchools;
    if (schoolTypeFilter !== "all") {
      filtered = filtered.filter(s => s.types.includes(schoolTypeFilter));
    }
    // Sort: use tier pct if filtering by type, otherwise overall pct
    const sortPct = (s) => {
      if (schoolTypeFilter !== "all" && s.tierPct[schoolTypeFilter] != null) {
        return s.tierPct[schoolTypeFilter];
      }
      return s.pct;
    };
    return filtered.sort((a, b) => (sortPct(b) ?? -1) - (sortPct(a) ?? -1));
  }, [allDistSchools, schoolTypeFilter]);

  // Type counts for tab labels
  const typeCounts = useMemo(() => ({
    all: allDistSchools.length,
    elementary: allDistSchools.filter(s => s.types.includes("elementary")).length,
    middle: allDistSchools.filter(s => s.types.includes("middle")).length,
    high: allDistSchools.filter(s => s.types.includes("high")).length,
  }), [allDistSchools]);

  // SAT data for high schools in this district
  const satBySchool = useMemo(() => {
    if (!psatData || !district) return {};
    const map = {};
    psatData.schools.forEach((s, idx) => {
      if (s.districtCode === district.code) {
        map[s.code] = s.years?.[year] || {};
      }
    });
    return map;
  }, [psatData, district, year]);

  // ── Conditional render: no district selected ──
  if (!district) {
    return (
      <div style={{ padding: 60, textAlign: "center" }}>
        <div style={{ fontSize: 48, marginBottom: 16, opacity: 0.3 }}>🏛️</div>
        <h2 style={{ fontFamily: "var(--font-head)", fontSize: 22, marginBottom: 8 }}>Select a District</h2>
        <p style={{ color: "var(--text3)", marginBottom: 24 }}>Search for a district or click one from the leaderboard</p>
        <div className="search-container" style={{ maxWidth: 500, margin: "0 auto" }}>
          <div className="search-icon"><Icons.search /></div>
          <input className="search-input" placeholder="Find your district..." value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            onFocus={() => setSearchFocused(true)}
            onBlur={() => setTimeout(() => setSearchFocused(false), 200)} />
          {searchFocused && searchResults.length > 0 && (
            <div className="search-results">
              {searchResults.map((r, i) => (
                <div key={i} className="search-result-item"
                  onMouseDown={() => { navigateToDistrict(r.code); setSearchQuery(""); }}>
                  <div className="search-result-icon district">🏛️</div>
                  <div><div className="search-result-name">{r.name}</div></div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  }

  // Helper to get display pct for a school given current filter
  function getDisplayPct(s) {
    if (schoolTypeFilter !== "all" && s.tierPct[schoolTypeFilter] != null) {
      return s.tierPct[schoolTypeFilter];
    }
    return s.pct;
  }

  // Helper to get type-specific rank info
  function getTypeRankInfo(s) {
    if (schoolTypeFilter !== "all" && s.typeRanks[schoolTypeFilter]) {
      const tr = s.typeRanks[schoolTypeFilter];
      return { rank: tr.r, total: tr.t, pctile: tr.p };
    }
    return { rank: s.stateRank, total: s.stateTotal, pctile: s.statePctile };
  }

  const TYPE_TABS = [
    { id: "all", label: "All" },
    { id: "elementary", label: "Elementary" },
    { id: "middle", label: "Middle" },
    { id: "high", label: "High" },
  ];

  return (
    <div>
      {/* ── Header ────────────────────────────────────────────────── */}
      <div className="page-header">
        <h1 className="page-header-title">{district.name}</h1>
        <p className="page-header-sub">District — {allDistSchools.length} schools</p>
      </div>

      {/* ── Rank Badges ───────────────────────────────────────────── */}
      <div className="p-section">
        <div className={"grid-" + Math.min(kpiCards.length, 4)}>
          {kpiCards.map(k => {
            const da = deltaArrow(k.delta != null ? Math.round(k.delta * 10) / 10 : null);
            return (
              <div key={k.subject} className="kpi-card" style={{ "--accent-color": k.color }}>
                <div className="kpi-label">{k.subject}</div>
                <div className="kpi-value">
                  {k.pct != null ? k.pct.toFixed(1) + "%" : "—"}
                  {k.delta != null && <span className={"kpi-delta " + da.cls} style={{ fontSize: 12, marginLeft: 8 }}>{da.text}</span>}
                </div>
                <div className="kpi-sub" style={{ marginTop: 4 }}>
                  <span className="rank-num">#{k.rank || "—"}</span>
                  <span style={{ color: "var(--text3)" }}> of {k.total || "—"} districts</span>
                  {k.pctile != null && (
                    <span className={"pctile-badge " + pctileClass(k.pctile)} style={{ marginLeft: 8 }}>{fmtOrd(Math.round(k.pctile))}</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* ── Trend ─────────────────────────────────────────────────── */}
      <div className="p-section">
        <div className="card">
          <div className="card-head">
            <div className="card-title">District Trends 2022–2025</div>
            <div style={{ display: "flex", gap: 10 }}>
              {subjects.map(s => (
                <div key={s} style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 11, color: "var(--text3)" }}>
                  <span style={{ width: 10, height: 3, borderRadius: 2, background: CHART_COLORS[s] }} />{s === "Spanish Language Arts" ? "SLA" : s}
                </div>
              ))}
            </div>
          </div>
          <div className="card-body">
            <LineChart datasets={trendDatasets} labels={years} height={240} />
          </div>
        </div>
      </div>

      {/* ── Schools Table ─────────────────────────────────────────── */}
      <div className="p-section">
        <div className="card">
          <div className="card-head" style={{ flexDirection: "column", alignItems: "stretch", gap: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div className="card-title">Schools in {district.name} — {subject} {year}{schoolTypeFilter === "high" ? " + SAT" : ""}</div>
              <div style={{ fontSize: 12, color: "var(--text3)" }}>{distSchools.length} schools</div>
            </div>
            {/* ── School Type Tabs ── */}
            <div className="tab-bar">
              {TYPE_TABS.map(tab => (
                <button
                  key={tab.id}
                  className={"tab" + (schoolTypeFilter === tab.id ? " active" : "")}
                  onClick={() => setSchoolTypeFilter(tab.id)}
                >
                  {tab.label} ({typeCounts[tab.id]})
                </button>
              ))}
            </div>
          </div>
          <div className="card-body" style={{ padding: 0, maxHeight: 500, overflowY: "auto" }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>School</th>
                  <th>% Met/Exceeded{schoolTypeFilter !== "all" ? ` (${schoolTypeFilter})` : ""}</th>
                  <th>State Rank</th>
                  <th>State Pctile</th>
                  {schoolTypeFilter === "high" && <th>SAT ERW</th>}
                  {schoolTypeFilter === "high" && <th>SAT Math</th>}
                  <th>Trend</th>
                </tr>
              </thead>
              <tbody>
                {distSchools.map((s, i) => {
                  const displayPct = getDisplayPct(s);
                  const rankInfo = getTypeRankInfo(s);
                  const sat = schoolTypeFilter === "high" ? satBySchool[s.code] : null;
                  return (
                    <tr key={s.code} onClick={() => navigateToSchool(s.districtCode, s.code)}>
                      <td><span className="rank-num">#{i + 1}</span></td>
                      <td style={{ fontWeight: 500 }}>
                        {s.name}
                        {schoolTypeFilter === "all" && s.types.length > 0 && (
                          <span style={{ marginLeft: 6, fontSize: 10, color: "var(--text3)", fontWeight: 400 }}>
                            {s.types.map(t => t === "elementary" ? "E" : t === "middle" ? "M" : t === "high" ? "H" : "").join("·")}
                          </span>
                        )}
                      </td>
                      <td style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>
                        {displayPct != null ? displayPct.toFixed(1) + "%" : <span className="suppressed">— <Icons.info /></span>}
                      </td>
                      <td><span className="rank-num">{rankInfo.rank != null ? `#${rankInfo.rank}` : "—"}</span> <span style={{ color: "var(--text3)", fontSize: 11 }}>of {rankInfo.total || "—"}</span></td>
                      <td>
                        {rankInfo.pctile != null ? (
                          <span className={"pctile-badge " + pctileClass(rankInfo.pctile)}>{fmtOrd(Math.round(rankInfo.pctile))}</span>
                        ) : "—"}
                      </td>
                      {schoolTypeFilter === "high" && (
                        <td style={{ fontVariantNumeric: "tabular-nums", fontSize: 12 }}>
                          {sat?.["SAT ERW"]?.pct != null ? (
                            <span>
                              <span style={{ fontWeight: 600, color: "var(--teal)" }}>{sat["SAT ERW"].pct.toFixed(1)}%</span>
                              {sat["SAT ERW"].meanScore != null && (
                                <span style={{ color: "var(--text3)", marginLeft: 4 }}>{sat["SAT ERW"].meanScore}</span>
                              )}
                            </span>
                          ) : <span className="suppressed">—</span>}
                        </td>
                      )}
                      {schoolTypeFilter === "high" && (
                        <td style={{ fontVariantNumeric: "tabular-nums", fontSize: 12 }}>
                          {sat?.["SAT Math"]?.pct != null ? (
                            <span>
                              <span style={{ fontWeight: 600, color: "var(--amber)" }}>{sat["SAT Math"].pct.toFixed(1)}%</span>
                              {sat["SAT Math"].meanScore != null && (
                                <span style={{ color: "var(--text3)", marginLeft: 4 }}>{sat["SAT Math"].meanScore}</span>
                              )}
                            </span>
                          ) : <span className="suppressed">—</span>}
                        </td>
                      )}
                      <td><Sparkline values={s.sparkline} color={subjectColor(subject)} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
