const { useState, useEffect, useMemo } = React;

const CFG = window.SCORP_CONFIG || {};
const TPL = window.SCORP_TEMPLATES || {};

const THEME_STYLES = {
  "PDL Health Rights": "bg-clay-soft text-[#7A4A2C]",
  "IP Health": "bg-[#E9EFE1] text-[#3E5C33]",
  "Clerk Welfare & Safety": "bg-[#F7EBCF] text-[#7A5A14]",
  "Medical Neutrality": "bg-[#E4EDE9] text-[#316253]",
  "Disaster & Displacement": "bg-[#EDE7DA] text-[#5C5140]"
};
const themeClass = t => THEME_STYLES[t] || "bg-fog text-ink";

const link = (pid, kind, name) => {
  const p = (CFG.projectLinks || {})[pid] || {};
  if (kind === "canva") return p.canva || "";
  return (p.forms || {})[name] || "";
};

const apDoc = p => [
  { h: "Project details", items: ["Project title: " + p.name, "Thematic area: " + p.theme, "Setup: " + p.setup, "Origin: " + p.origin, "Timing: " + p.prep] },
  { h: "I. Rationale", b: p.summary },
  { h: "II. Objectives", b: p.objectives },
  { h: "III. Timeline", b: p.timeline },
  { h: "IV. Targets and evaluation", b: p.outcomes },
  { h: "V. Budget summary", b: "Budget TBD. Attach the itemized budget sheet once costs are set." },
  { h: "VI. Committee roster", b: "Roles to assign: project head, logistics, program, documentation, finance, and ethics point person." }
];

function Chip({ label, active, onClick }) {
  return (
    <button onClick={onClick}
      className={"rounded-full px-3.5 py-1.5 text-[13px] font-medium border transition-all duration-300 ease-brand active:translate-y-px " +
        (active ? "bg-ink text-white border-ink" : "bg-white text-ink border-haze hover:bg-mist")}>
      {label}
    </button>
  );
}

function Filters({ state, toggle, clear, count }) {
  const groups = [
    { key: "themes", label: "Thematic Area", opts: Object.keys(THEME_STYLES) },
    { key: "setups", label: "Setup Type", opts: ["Virtual", "On-ground", "Hybrid"] }
  ];
  if (CFG.showBudgetFilter) groups.push({ key: "budgets", label: "Budget Range", opts: CFG.budgetRanges || [] });
  const anyActive = state.themes.length + state.setups.length + state.budgets.length > 0;
  return (
    <div className="bg-white border border-fog rounded-2xl shadow-card p-5 sm:p-6 flex flex-col gap-4">
      <div className="flex flex-col sm:flex-row sm:flex-wrap gap-5 sm:gap-7">
        {groups.map(g => (
          <div key={g.key} className="flex flex-col gap-2">
            <div className="text-[11px] font-semibold uppercase tracking-[0.1em] text-brand">{g.label}</div>
            <div className="flex flex-wrap gap-2">
              {g.opts.map(o => (
                <Chip key={o} label={o} active={state[g.key].includes(o)} onClick={() => toggle(g.key, o)} />
              ))}
            </div>
          </div>
        ))}
      </div>
      <div className="flex items-center justify-between gap-4 border-t border-fog pt-3.5">
        <div className="text-[13px] text-slate2">{count === 1 ? "Showing 1 project" : "Showing " + count + " projects"}</div>
        {anyActive && (
          <button onClick={clear} className="text-[13px] font-semibold text-brand hover:text-ink">Clear filters</button>
        )}
      </div>
    </div>
  );
}

function ProjectCard({ p, onOpen, index = 0 }) {
  return (
    <button onClick={onOpen} style={{ animationDelay: Math.min(index, 8) * 90 + "ms" }}
      className="anim-rise text-left bg-white border border-fog rounded-2xl shadow-card p-6 flex flex-col gap-3.5 transition-all duration-300 ease-brand hover:shadow-lift hover:border-clay hover:-translate-y-1 active:translate-y-0">
      <div className="flex items-center justify-between gap-2">
        <span className={"rounded-full px-3 py-1 text-xs font-semibold " + themeClass(p.theme)}>{p.theme}</span>
        <span className="text-xs font-medium text-quiet">{p.year}</span>
      </div>
      <div className="flex flex-col gap-1.5">
        <div className="text-[17px] font-semibold leading-snug">{p.name}</div>
        <div className="text-[13.5px] text-slate2 leading-relaxed">{p.summary}</div>
      </div>
      <div className="flex flex-wrap gap-2 mt-auto pt-1">
        {[p.setup, p.budget, p.origin].map(t => (
          <span key={t} className="bg-mist rounded-full px-2.5 py-1 text-xs font-medium text-ink">{t}</span>
        ))}
      </div>
    </button>
  );
}

function DocModal({ project, form, onClose }) {
  useEffect(() => {
    const h = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", h); document.body.style.overflow = ""; };
  }, [onClose]);
  const sections = form.kind === "ap" ? apDoc(project) : (form.doc || []);
  const live = link(project.id, "form", form.name);
  return (
    <div onClick={onClose} className="anim-dim fixed inset-0 z-50 bg-ink-deep/55 overflow-y-auto p-4 sm:p-12 flex items-start justify-center">
      <div onClick={e => e.stopPropagation()} className="anim-pop bg-white rounded-2xl shadow-modal w-full max-w-3xl p-6 sm:p-11 flex flex-col gap-5">
        <div className="flex items-start justify-between gap-4 border-b-2 border-ink pb-4">
          <div className="flex flex-col gap-1">
            <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-brand">{project.name}</div>
            <div className="text-xl sm:text-[22px] font-bold">{form.name}</div>
          </div>
          <button onClick={onClose} className="shrink-0 rounded-full border border-haze px-4 py-2 text-[13px] font-semibold hover:bg-mist">Close</button>
        </div>
        {sections.map((s, i) => (
          <div key={i} className="flex flex-col gap-2">
            <div className="text-[13px] font-semibold uppercase tracking-[0.08em] text-brand">{s.h}</div>
            {s.b && <div className="text-sm leading-relaxed">{s.b}</div>}
            {s.items && (
              <div className="flex flex-col gap-1.5">
                {s.items.map((it, j) => (
                  <div key={j} className="flex gap-2.5 text-sm leading-relaxed">
                    <span className="text-brand font-bold shrink-0">·</span><span>{it}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
        <div className="border-t border-fog pt-3.5 flex flex-col sm:flex-row sm:items-center gap-3 justify-between">
          <div className="text-[13px] text-quiet leading-relaxed">
            {live ? "A live version is attached." : "Generated draft. Copy it into Google Docs or Forms, then add the link in config.js."}
          </div>
          {live && (
            <a href={live} target="_blank" rel="noopener" className="shrink-0 rounded-full bg-brand hover:bg-brand-dark px-5 py-2.5 text-sm font-semibold text-white hover:text-white">Open live form</a>
          )}
        </div>
      </div>
    </div>
  );
}

const FieldBox = ({ children, className = "" }) => (
  <div className={"rounded-lg border border-haze bg-[#FBF9F4] px-3 py-2.5 text-[13.5px] leading-relaxed text-quiet shadow-[inset_0_1px_2px_rgba(28,26,20,0.06)] " + className}>{children}</div>
);

const TplCard = ({ code, title, children }) => (
  <div key={code} className="anim-fade bg-white border border-fog rounded-2xl shadow-card p-6 sm:p-9 flex flex-col gap-5">
    <div className="flex flex-col gap-1 border-b-2 border-ink pb-4">
      <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-brand">{code}</div>
      <div className="text-xl sm:text-[22px] font-bold">{title}</div>
    </div>
    {children}
  </div>
);

const TPL_TABS = [
  { id: "ap", label: "Activity Proposal" },
  { id: "budget", label: "Budget Sheet" },
  { id: "canva", label: "Canva Kit Standard" },
  { id: "ethics", label: "Ethics Checklist" },
  { id: "directory", label: "Partner Directory" }
];

function Templates() {
  const [t, setT] = useState("ap");
  const cols = TPL.directoryCols || [];
  return (
    <div className="anim-rise max-w-4xl mx-auto w-full px-5 sm:px-10 pt-8 sm:pt-10 pb-20 flex flex-col gap-7">
      <div className="flex flex-col gap-2">
        <h1 className="text-2xl sm:text-3xl font-bold tracking-[-0.01em]">Standardized module templates</h1>
        <p className="text-[15px] text-slate2 leading-relaxed max-w-xl">Blank versions of every section in the module structure. Copy them into your own docs when packaging a new project for submission.</p>
      </div>

      <div className="flex gap-1 border-b border-fog overflow-x-auto no-scrollbar -mx-5 px-5 sm:mx-0 sm:px-0">
        {TPL_TABS.map(x => (
          <button key={x.id} onClick={() => setT(x.id)}
            className={"px-4 py-3 text-sm font-semibold whitespace-nowrap border-b-2 -mb-px transition-colors duration-300 ease-brand " +
              (t === x.id ? "text-ink border-brand" : "text-quiet border-transparent hover:text-slate2")}>
            {x.label}
          </button>
        ))}
      </div>

      {t === "ap" && (
        <TplCard code="SCORP Form 01" title="Activity Proposal (AP)">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {(TPL.apHeaderFields || []).map(f => (
              <div key={f.label} className="flex flex-col gap-1.5">
                <div className="text-xs font-semibold uppercase tracking-[0.06em] text-brand">{f.label}</div>
                <FieldBox>{f.hint}</FieldBox>
              </div>
            ))}
          </div>
          {(TPL.apSections || []).map(s => (
            <div key={s.title} className="flex flex-col gap-1.5">
              <div className="text-[15px] font-semibold">{s.title}</div>
              <FieldBox className="min-h-12">{s.hint}</FieldBox>
            </div>
          ))}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-6 border-t border-fog pt-6">
            {(TPL.apSignatures || []).map(sig => (
              <div key={sig} className="flex flex-col gap-2">
                <div className="h-7 border-b border-ink"></div>
                <div className="text-xs text-slate2">{sig}</div>
              </div>
            ))}
          </div>
        </TplCard>
      )}

      {t === "budget" && (
        <TplCard code="SCORP Form 02" title="Itemized Budget Sheet">
          <div className="border border-fog rounded-xl overflow-x-auto">
            <table className="w-full min-w-[640px] text-[13px] border-collapse">
              <thead>
                <tr className="bg-mist">
                  {["Item / Description", "Qty", "Unit Cost", "Total", "Fund Source"].map(h => (
                    <th key={h} className="text-left font-semibold px-3.5 py-2.5 border-b border-fog">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {(TPL.budgetRows || []).map((r, i) => (
                  <tr key={i} className={r.sample ? "text-quiet italic" : "text-haze"}>
                    {[r.item, r.qty, r.unit, r.total, r.source].map((c, j) => (
                      <td key={j} className="px-3.5 py-3 border-b border-fog align-top">{c || "\u00a0"}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="sm:self-end w-full sm:w-80 flex flex-col gap-1.5">
            {[["Subtotal", false], ["Contingency (10%)", false]].map(([k]) => (
              <div key={k} className="flex justify-between text-sm"><span className="text-slate2">{k}</span><span className="font-semibold">₱ ______</span></div>
            ))}
            <div className="flex justify-between text-base border-t-2 border-ink pt-2 mt-1">
              <span className="font-semibold">Grand Total</span><span className="font-bold">₱ ______</span>
            </div>
          </div>
          <div className="text-[13px] text-slate2 leading-relaxed bg-mist rounded-xl px-4 py-3.5">{TPL.budgetNote}</div>
        </TplCard>
      )}

      {t === "canva" && (
        <TplCard code="SCORP Kit Standard" title="Canva Kit required contents">
          <div className="text-sm text-slate2 leading-relaxed">Every submitted project must include one shared Canva folder with this exact structure, so any chapter can find what they need in seconds.</div>
          <div className="flex flex-col gap-2.5">
            {(TPL.canvaFolders || []).map(f => (
              <div key={f.name} className="border border-fog rounded-xl px-5 py-4 flex flex-col gap-1.5">
                <div className="text-[15px] font-semibold">{f.name}</div>
                <div className="text-[13.5px] text-slate2 leading-relaxed">{f.contents}</div>
              </div>
            ))}
          </div>
          <div className="text-[13px] text-slate2 leading-relaxed bg-mist rounded-xl px-4 py-3.5">{TPL.canvaNote}</div>
        </TplCard>
      )}

      {t === "ethics" && (
        <TplCard code="SCORP Form 03" title="Legal and Ethics Master Checklist">
          <div className="text-sm text-slate2 leading-relaxed">{TPL.ethicsNote}</div>
          {(TPL.ethicsGroups || []).map(g => (
            <div key={g.title} className="flex flex-col gap-2.5">
              <div className="text-[13px] font-semibold uppercase tracking-[0.08em] text-brand">{g.title}</div>
              <div className="flex flex-col gap-2">
                {g.items.map(it => (
                  <div key={it.label} className="flex gap-3 items-start">
                    <span className="mt-0.5 w-[18px] h-[18px] shrink-0 rounded-[5px] border-2 border-haze"></span>
                    <span className="text-sm leading-relaxed flex items-baseline gap-2">
                      {it.hard && <span className="w-2 h-2 shrink-0 rounded-full bg-alert inline-block"></span>}
                      <span>{it.label}</span>
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </TplCard>
      )}

      {t === "directory" && (
        <TplCard code="SCORP Form 04" title="Speaker and Partner Directory">
          <div className="border border-fog rounded-xl overflow-x-auto">
            <table className="w-full min-w-[720px] text-[13px] border-collapse">
              <thead>
                <tr className="bg-mist">
                  {cols.map(c => <th key={c} className="text-left font-semibold px-3.5 py-2.5 border-b border-fog">{c}</th>)}
                </tr>
              </thead>
              <tbody>
                {[0, 1, 2].map(r => (
                  <tr key={r}>{cols.map(c => <td key={c} className="px-3.5 py-4 border-b border-fog">{"\u00a0"}</td>)}</tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="text-[13px] text-slate2 leading-relaxed bg-mist rounded-xl px-4 py-3.5">{TPL.directoryNote}</div>
        </TplCard>
      )}
    </div>
  );
}

const TABS = [
  { id: "blueprint", label: "Executive Blueprint" },
  { id: "canva", label: "Canva Kit" },
  { id: "forms", label: "Admin Forms" },
  { id: "ethics", label: "Legal/Ethics Checklist" },
  { id: "directory", label: "Speakers & Partners" }
];

function Detail({ p, onBack }) {
  const [tab, setTab] = useState("blueprint");
  const [doc, setDoc] = useState(null);
  const [checks, setChecks] = useState({});

  useEffect(() => {
    try { const s = localStorage.getItem("scorp-ethics-checks"); if (s) setChecks(JSON.parse(s)); } catch (e) {}
  }, []);
  const toggleCheck = key => setChecks(prev => {
    const next = { ...prev, [key]: !prev[key] };
    try { localStorage.setItem("scorp-ethics-checks", JSON.stringify(next)); } catch (e) {}
    return next;
  });

  const canva = link(p.id, "canva");
  const doneCount = (p.ethics || []).filter((e, i) => checks[p.id + "-" + i]).length;

  return (
    <div className="anim-rise max-w-4xl mx-auto w-full px-5 sm:px-10 pt-6 pb-20 flex flex-col gap-6">
      <button onClick={onBack} className="self-start text-sm font-semibold text-brand hover:text-ink">Back to all projects</button>

      <div className="flex flex-col gap-3">
        <div className="flex flex-wrap gap-2">
          <span className={"rounded-full px-3 py-1 text-xs font-semibold " + themeClass(p.theme)}>{p.theme}</span>
          {[p.setup, p.budget, p.origin + " · " + p.year].map(t => (
            <span key={t} className="bg-mist rounded-full px-3 py-1 text-xs font-medium">{t}</span>
          ))}
        </div>
        <h1 className="text-2xl sm:text-3xl font-bold tracking-[-0.01em] leading-tight">{p.name}</h1>
        <p className="text-[15px] text-slate2 leading-relaxed">{p.summary}</p>
      </div>

      <div className="flex gap-1 border-b border-fog overflow-x-auto no-scrollbar -mx-5 px-5 sm:mx-0 sm:px-0">
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            className={"px-4 py-3 text-sm font-semibold whitespace-nowrap border-b-2 -mb-px transition-colors duration-300 ease-brand " +
              (tab === t.id ? "text-ink border-brand" : "text-quiet border-transparent hover:text-slate2")}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === "blueprint" && (
        <div key="blueprint" className="anim-fade flex flex-col gap-4">
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {[["Reach", p.reach], ["Team Size", p.team], ["Prep Time", p.prep]].map(([k, v]) => (
              <div key={k} className="bg-white border border-fog rounded-2xl p-5 flex flex-col gap-1">
                <div className="text-xs font-semibold uppercase tracking-[0.08em] text-brand">{k}</div>
                <div className="text-lg sm:text-[22px] font-bold leading-tight">{v}</div>
              </div>
            ))}
          </div>
          <div className="bg-white border border-fog rounded-2xl p-6 sm:p-7 flex flex-col gap-5">
            {[["Objectives", p.objectives], ["Timeline", p.timeline], ["Key outcomes and targets", p.outcomes]].map(([k, v]) => (
              <div key={k} className="flex flex-col gap-2">
                <div className="text-[15px] font-semibold">{k}</div>
                <div className="text-sm text-slate2 leading-[1.7]">{v}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "canva" && (
        <div key="canva" className="anim-fade flex flex-col gap-4">
          <div className="bg-white border border-fog rounded-2xl p-6 sm:p-7 flex flex-col gap-4">
            <div className="text-sm text-slate2 leading-[1.7]">One shared Canva folder per project. Open it and choose "Use as template" to duplicate the designs into your chapter's Canva. The brief below lists what belongs in the folder.</div>
            {canva
              ? <a href={canva} target="_blank" rel="noopener" className="self-start rounded-full bg-brand hover:bg-brand-dark px-6 py-3 text-sm font-semibold text-white hover:text-white">Open Canva Kit</a>
              : <div className="self-start rounded-full border border-dashed border-haze px-6 py-3 text-sm font-semibold text-quiet">Canva folder link to be attached</div>}
          </div>
          <div className="flex flex-col gap-3">
            {(p.canvaKit || []).map(k => (
              <div key={k.name} className="bg-white border border-fog rounded-2xl p-5 sm:px-6 flex flex-col gap-1">
                <div className="text-[15px] font-semibold">{k.name}</div>
                <div className="text-[13px] text-slate2 leading-relaxed">{k.spec}</div>
              </div>
            ))}
          </div>
          <div className="text-[13px] text-quiet leading-relaxed">Naming convention: PROJECTNAME_Type_Version, for example SILONG_Pubmat-Announcement_v1. Set folder sharing to "Anyone with the link, Can view."</div>
        </div>
      )}

      {tab === "forms" && (
        <div key="forms" className="anim-fade flex flex-col gap-3">
          {(p.forms || []).map(f => (
            <button key={f.name} onClick={() => setDoc(f)}
              className="text-left bg-white border border-fog rounded-2xl p-5 sm:px-6 flex items-center justify-between gap-4 transition-all duration-300 ease-brand hover:border-clay hover:shadow-lift hover:-translate-y-0.5 active:translate-y-0">
              <div className="flex flex-col gap-1">
                <div className="text-[15px] font-semibold">{f.name}</div>
                <div className="text-[13px] text-slate2 leading-relaxed">{f.desc}</div>
              </div>
              <div className="text-[13px] font-semibold text-brand whitespace-nowrap shrink-0">
                {link(p.id, "form", f.name) ? "Open" : "View draft"}
              </div>
            </button>
          ))}
          <div className="text-[13px] text-quiet leading-relaxed px-1">Drafts are generated from the module blueprint. Move each one into Google Docs or Forms, then add the live link in config.js.</div>
        </div>
      )}

      {tab === "ethics" && (
        <div key="ethics" className="anim-fade bg-white border border-fog rounded-2xl p-4 sm:p-7 flex flex-col">
          {(p.ethics || []).map((e, i) => {
            const key = p.id + "-" + i, on = !!checks[key];
            return (
              <button key={key} onClick={() => toggleCheck(key)} className="text-left flex gap-3.5 items-start p-3 rounded-xl hover:bg-mist transition-colors duration-300 ease-brand">
                <span className={"mt-0.5 w-6 h-6 shrink-0 rounded-md border-2 flex items-center justify-center transition-all duration-300 ease-brand " + (on ? "bg-brand border-brand" : "bg-white border-haze")}>
                  {on && (
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
                  )}
                </span>
                <span className="flex flex-col gap-0.5">
                  <span className={"text-[14.5px] font-medium " + (on ? "text-quiet line-through" : "")}>{e.label}</span>
                  <span className="text-[13px] text-quiet leading-relaxed">{e.note}</span>
                </span>
              </button>
            );
          })}
          <div className="border-t border-fog mt-3 pt-4 text-[13px] text-slate2">
            {doneCount} of {(p.ethics || []).length} items checked. Your checks are saved in this browser.
          </div>
        </div>
      )}

      {tab === "directory" && (
        <div key="directory" className="anim-fade bg-white border border-fog rounded-2xl overflow-hidden">
          <div className="hidden sm:grid grid-cols-[1.2fr_1.2fr_1fr_1fr] text-[13px]">
            {["Name", "Organization", "Role / Topic", "Contact"].map(h => (
              <div key={h} className="px-5 py-3 font-semibold bg-mist border-b border-fog">{h}</div>
            ))}
            {(p.partners || []).map((pt, i) => (
              <React.Fragment key={i}>
                <div className="px-5 py-3.5 border-b border-fog font-medium">{pt.name}</div>
                <div className="px-5 py-3.5 border-b border-fog text-slate2">{pt.org}</div>
                <div className="px-5 py-3.5 border-b border-fog text-slate2">{pt.role}</div>
                <div className="px-5 py-3.5 border-b border-fog text-brand font-medium">{pt.contact}</div>
              </React.Fragment>
            ))}
          </div>
          <div className="sm:hidden divide-y divide-fog">
            {(p.partners || []).map((pt, i) => (
              <div key={i} className="p-5 flex flex-col gap-1">
                <div className="text-[15px] font-semibold">{pt.name}</div>
                <div className="text-[13px] text-slate2">{pt.org} · {pt.role}</div>
                <div className="text-[13px] font-medium text-brand">{pt.contact}</div>
              </div>
            ))}
          </div>
          <div className="px-5 py-3.5 text-[13px] text-quiet bg-[#FBF9F4]">Contact routes go through the national team until chapter directories are filed.</div>
        </div>
      )}

      {doc && <DocModal project={p} form={doc} onClose={() => setDoc(null)} />}
    </div>
  );
}

function App() {
  const [view, setView] = useState("projects");
  const [activeId, setActiveId] = useState(null);
  const [menuOpen, setMenuOpen] = useState(false);
  const [projects, setProjects] = useState(null);
  const [loadError, setLoadError] = useState("");
  const [f, setF] = useState({ themes: [], setups: [], budgets: [] });

  useEffect(() => {
    window.loadProjects()
      .then(setProjects)
      .catch(err => { setProjects([]); setLoadError(String(err.message || err)); });
  }, []);

  const toggle = (key, val) => setF(s => ({ ...s, [key]: s[key].includes(val) ? s[key].filter(v => v !== val) : [...s[key], val] }));
  const clear = () => setF({ themes: [], setups: [], budgets: [] });

  const all = projects || [];
  const filtered = useMemo(() => all.filter(p =>
    (!f.themes.length || f.themes.includes(p.theme)) &&
    (!f.setups.length || f.setups.includes(p.setup)) &&
    (!f.budgets.length || f.budgets.includes(p.budget))
  ), [f, projects]);

  const active = view === "projects" ? all.find(p => p.id === activeId) : null;
  useEffect(() => { window.scrollTo(0, 0); setMenuOpen(false); }, [activeId, view]);
  const navBtn = on => "relative px-1 py-1 text-sm font-semibold transition-colors duration-300 ease-brand after:absolute after:left-0 after:right-0 after:-bottom-0.5 after:h-0.5 after:rounded-full after:transition-all after:duration-300 " +
    (on ? "text-white after:bg-white" : "text-white/70 hover:text-white after:bg-transparent hover:after:bg-white/50");
  const navBtnMobile = on => "w-full text-left px-1 py-2.5 text-[15px] font-semibold border-l-2 pl-3 transition-colors duration-300 ease-brand " +
    (on ? "text-white border-white" : "text-white/70 border-transparent hover:text-white hover:border-white/40");

  return (
    <div className="min-h-screen flex flex-col">
      <header className="sticky top-0 z-40 bg-ink text-white">
        <div className="px-5 sm:px-10 py-4 flex items-center gap-4">
          <button onClick={() => { setView("projects"); setActiveId(null); }} className="text-left flex flex-col gap-0.5 min-w-0 flex-1">
            <span className="text-[10px] sm:text-[11px] font-semibold uppercase tracking-[0.14em] text-[#C9C0AC]">{CFG.orgName}</span>
            <span className="text-base sm:text-[19px] font-bold tracking-[-0.01em] leading-tight">{CFG.repoTitle}</span>
          </button>

          <div className="hidden md:flex items-center gap-6 shrink-0">
            <button onClick={() => { setView("projects"); setActiveId(null); }} className={navBtn(view === "projects")}>Projects</button>
            <button onClick={() => setView("templates")} className={navBtn(view === "templates")}>Templates</button>
            {CFG.submitFormUrl
              ? <a href={CFG.submitFormUrl} target="_blank" rel="noopener" className="rounded-full bg-brand hover:bg-brand-dark px-5 py-2.5 text-sm font-semibold text-white hover:text-white whitespace-nowrap">Submit a Project</a>
              : <span className="rounded-full border border-dashed border-brand px-5 py-2.5 text-sm font-semibold text-[#C9C0AC] whitespace-nowrap">Form link pending</span>}
          </div>

          <button onClick={() => setMenuOpen(o => !o)} aria-label="Menu" aria-expanded={menuOpen}
            className="md:hidden shrink-0 rounded-xl border border-white/30 p-2.5 hover:bg-white/10 transition-colors duration-300 ease-brand">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              {menuOpen
                ? <g><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></g>
                : <g><line x1="3" y1="7" x2="21" y2="7" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="17" x2="21" y2="17" /></g>}
            </svg>
          </button>
        </div>

        {menuOpen && (
          <div className="anim-dim md:hidden border-t border-white/15 px-5 pb-4 pt-3 flex flex-col gap-1">
            <button onClick={() => { setView("projects"); setActiveId(null); }} className={navBtnMobile(view === "projects")}>Projects</button>
            <button onClick={() => setView("templates")} className={navBtnMobile(view === "templates")}>Templates</button>
            {CFG.submitFormUrl
              ? <a href={CFG.submitFormUrl} target="_blank" rel="noopener" className="mt-2 rounded-full bg-brand hover:bg-brand-dark px-5 py-3 text-sm font-semibold text-white hover:text-white text-center">Submit a Project</a>
              : <span className="mt-2 rounded-full border border-dashed border-brand px-5 py-3 text-sm font-semibold text-[#C9C0AC] text-center">Form link pending</span>}
          </div>
        )}
      </header>

      {view === "templates" ? <Templates /> : active
        ? <Detail p={active} onBack={() => setActiveId(null)} />
        : (
          <div className="max-w-6xl mx-auto w-full px-5 sm:px-10 pt-8 sm:pt-10 pb-20 flex flex-col gap-7">
            <div className="flex flex-col gap-2">
              <h1 className="text-2xl sm:text-3xl font-bold tracking-[-0.01em]">Browse proven SCORP projects</h1>
              <p className="text-[15px] text-slate2 leading-relaxed max-w-xl">Every module comes ready to adopt: executive blueprint, Canva kit, admin forms, ethics checklist, and partner directory. Filter to find one that fits your chapter.</p>
            </div>
            <Filters state={f} toggle={toggle} clear={clear} count={filtered.length} />
            {projects === null && (
              <div className="py-16 text-center text-[15px] text-slate2">Loading projects.</div>
            )}
            {loadError && (
              <div className="bg-white border border-fog rounded-2xl p-6 flex flex-col gap-2">
                <div className="text-[15px] font-semibold">Projects could not be loaded</div>
                <div className="text-sm text-slate2 leading-relaxed">Project pages are read from the <code>projects/</code> folder at runtime, so the page has to be served over http rather than opened as a local file. Run <code>python3 -m http.server</code> in this folder, or view it on GitHub Pages.</div>
                <div className="text-[13px] text-quiet">{loadError}</div>
              </div>
            )}
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
              {filtered.map((p, i) => <ProjectCard key={p.id} p={p} index={i} onOpen={() => setActiveId(p.id)} />)}
            </div>
            {projects !== null && !loadError && !filtered.length && (
              <div className="py-16 text-center flex flex-col gap-3">
                <div className="text-[17px] font-semibold">No projects match those filters</div>
                <div className="text-[15px] text-slate2">Try removing a filter, or be the first to submit one like this.</div>
              </div>
            )}
          </div>
        )}

      <footer className="mt-auto bg-white border-t border-fog px-5 sm:px-10 py-6 flex flex-col sm:flex-row justify-between gap-3 text-[13px] text-quiet">
        <div>{CFG.maintainer}</div>
        <div className="flex gap-5">
          {CFG.telegramUrl && <a href={CFG.telegramUrl} target="_blank" rel="noopener" className="font-semibold">Chapter heads channel</a>}
          {CFG.submitFormUrl && <a href={CFG.submitFormUrl} target="_blank" rel="noopener" className="font-semibold">Submit a project</a>}
        </div>
      </footer>
    </div>
  );
}

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