// Pillar-segmented Resource Hub — one clear section per topic, low visual noise.

function ResourcesView() {
  const { RESOURCES, TAGS } = window.DATA;
  const [query, setQuery] = useState("");
  const [openPillars, setOpenPillars] = useState(new Set()); // which pillars are expanded

  const matches = (r) => !query || r.title.toLowerCase().includes(query.toLowerCase());
  const searching = query.length > 0;

  const togglePillar = (key) => {
    setOpenPillars(prev => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key); else next.add(key);
      return next;
    });
  };

  const pinned = RESOURCES.filter(r => r.pinned && matches(r));

  // Pillar metadata — icon + one-liner purpose
  const PILLARS = [
    { key: "recruiting",    img: "assets/recruiting-logo.avif",     padding: 6, desc: "Timelines, outreach templates, and family conversation guides." },
    { key: "mental_health", img: "assets/mental-health-logo.webp",  padding: 0, desc: "Screening tools, warm-handoff scripts, and family guides." },
    { key: "academic",      img: "assets/academic-logo.png",        padding: 7, desc: "Course planning, study blocks, and multi-sport calendars." },
    { key: "ncaa",          img: "assets/ncaa-logo.png",            padding: 0, desc: "Eligibility center references, amateurism, and transcripts." },
  ];

  return (
    <>
      <window.TopBar
        title="Resource Hub"
        subtitle={`${RESOURCES.length} counselor-vetted resources, organized by pillar.`}
        right={
          <div style={{ position: "relative" }}>
            <input
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Search all resources…"
              style={{
                width: 280, padding: "8px 12px 8px 34px",
                background: "var(--bg-2)", border: "1px solid var(--line)",
                borderRadius: 8, fontSize: 13,
              }}
            />
            <window.I.Search size={14} stroke="var(--ink-3)" style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)" }} />
          </div>
        }
      />

      <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 32 }}>

        {/* Pinned strip */}
        {pinned.length > 0 && !searching && (
          <section>
            <SectionHeader
              icon={<window.I.Bookmark size={13} stroke="var(--ink-2)" style={{ fill: "var(--ink-2)" }} />}
              label="Pinned by your district"
              count={pinned.length}
            />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 12 }}>
              {pinned.map(r => <ResourceCard key={r.id} r={r} />)}
            </div>
          </section>
        )}

        {/* Section label */}
        <div style={{ fontSize: 11, letterSpacing: 0.08, textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 600, marginTop: pinned.length > 0 && !searching ? 0 : -8 }}>
          Browse by pillar
        </div>

        {/* Four hero pillar cards in a 2x2 grid */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }}>
          {PILLARS.map(p => {
            const def = TAGS[p.key];
            const items = RESOURCES.filter(r => r.category === p.key && matches(r));
            const isOpen = openPillars.has(p.key) || searching;

            return (
              <PillarBlock
                key={p.key}
                pillar={p}
                def={def}
                items={items}
                isOpen={isOpen}
                onToggle={() => togglePillar(p.key)}
              />
            );
          })}
        </div>

        {searching && RESOURCES.filter(matches).length === 0 && (
          <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)", border: "1px dashed var(--line)", borderRadius: "var(--radius)" }}>
            No resources match "{query}".
          </div>
        )}
      </div>
    </>
  );
}

function SectionHeader({ icon, label, count }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, paddingBottom: 10, borderBottom: "1px solid var(--line)" }}>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
        {icon}
        <div style={{ fontSize: 11, letterSpacing: 0.08, textTransform: "uppercase", color: "var(--ink-2)", fontWeight: 600 }}>
          {label}
        </div>
      </div>
      <div style={{ fontSize: 11, color: "var(--ink-3)" }}>· {count}</div>
    </div>
  );
}

function PillarBlock({ pillar, def, items, isOpen, onToggle }) {
  return (
    <div style={{
      borderRadius: 14,
      background: "var(--card)", border: "1px solid var(--line)",
      overflow: "hidden",
      gridColumn: isOpen ? "1 / -1" : "auto",
      transition: "grid-column 0.2s",
    }}>
      {/* Clickable hero header */}
      <button
        onClick={onToggle}
        className="hover-lift"
        style={{
          width: "100%", padding: "22px 22px",
          display: "flex", alignItems: "center", gap: 18,
          background: "transparent", border: "none", cursor: "pointer",
          textAlign: "left",
        }}
      >
        <div style={{
          width: 64, height: 64, borderRadius: 999,
          background: "white", border: "1px solid var(--line-2)",
          display: "flex", alignItems: "center", justifyContent: "center",
          overflow: "hidden", flexShrink: 0,
        }}>
          <img src={pillar.img} alt={def.label} style={{ width: 64, height: 64, objectFit: "contain", padding: pillar.padding + 2, borderRadius: 999 }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
            <h2 style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.015, margin: 0 }}>{def.label}</h2>
            <span style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 400 }}>
              {items.length} {items.length === 1 ? "resource" : "resources"}
            </span>
          </div>
          <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.45 }}>{pillar.desc}</div>
        </div>
        <div style={{
          width: 34, height: 34, borderRadius: 999,
          background: "var(--bg-2)", border: "1px solid var(--line)",
          display: "flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
          transition: "transform 0.2s",
          transform: isOpen ? "rotate(90deg)" : "rotate(0deg)",
        }}>
          <window.I.ChevronRight size={16} stroke="var(--ink-2)" />
        </div>
      </button>

      {/* Collapsible file list */}
      {isOpen && (
        <div style={{ padding: "0 22px 22px", borderTop: "1px solid var(--line)", paddingTop: 18 }}>
          {items.length === 0 ? (
            <div style={{ padding: "20px 0", textAlign: "center", fontSize: 12.5, color: "var(--ink-3)" }}>
              No resources match your search.
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 12 }}>
              {items.map(r => <ResourceCard key={r.id} r={r} />)}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function FileChip({ type, size = 38 }) {
  return (
    <div style={{
      width: size, height: size * 1.24, borderRadius: 6,
      background: "var(--bg-2)",
      border: "1px solid var(--line-2)",
      color: "var(--ink-2)",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontSize: size * 0.24, fontWeight: 600, letterSpacing: 0.04,
      flexShrink: 0,
      fontFamily: "'Geist Mono', ui-monospace, monospace",
    }}>
      {type}
    </div>
  );
}

function ResourceCard({ r }) {
  const [downloaded, setDownloaded] = useState(false);
  return (
    <div className="hover-lift" style={{
      padding: 14, borderRadius: "var(--radius)",
      background: "var(--card)", border: "1px solid var(--line)",
      display: "flex", flexDirection: "column", gap: 12,
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
        <FileChip type={r.type} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 500, lineHeight: 1.35, letterSpacing: -0.005 }}>{r.title}</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 4 }}>
            {r.size} · Updated {new Date(r.updated).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
          </div>
        </div>
        {r.pinned && (
          <window.I.Bookmark size={13} stroke="var(--ink-2)" style={{ fill: "var(--ink-2)", flexShrink: 0 }} />
        )}
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        <button
          onClick={() => {
            setDownloaded(true);
            window.trackDownload && window.trackDownload({
              source: "resource", refId: r.id, title: r.title,
              pillar: r.category, grade: null, assetType: (r.type || "pdf").toLowerCase(),
            });
          }}
          style={{
            flex: 1, padding: "7px 10px", borderRadius: 7,
            background: downloaded ? "var(--bg-2)" : "var(--ink)",
            color: downloaded ? "var(--ink-2)" : "white",
            border: downloaded ? "1px solid var(--line)" : "1px solid var(--ink)",
            fontSize: 12.5, fontWeight: 500, letterSpacing: -0.005,
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6, cursor: "pointer",
          }}
        >
          {downloaded ? <><window.I.Check size={12} sw={3} /> Downloaded</> : <><window.I.Download size={12} /> Download</>}
        </button>
        <button style={{
          padding: "7px 10px", borderRadius: 7,
          background: "var(--card)", color: "var(--ink-2)",
          fontSize: 12.5, fontWeight: 500,
          border: "1px solid var(--line)",
          display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer",
        }}>
          <window.I.Share size={12} /> Share
        </button>
      </div>
    </div>
  );
}

window.ResourcesView = ResourcesView;
