// browse.jsx — Search/Browse results screen

const { useState: useStateB, useMemo: useMemoB } = React;

const FILTER_GROUPS = [
  { id: "category", label: "Category", multi: true,
    options: ["Coding", "Research", "Writing", "Data", "Ops"] },
  { id: "environment", label: "Environment", multi: true,
    options: ["Claude Code", "Claude.ai", "CLI", "API"] },
  { id: "trust", label: "Trust", multi: true,
    options: [
      { value: "verified", label: "Verified" },
      { value: "secure", label: "Security reviewed" },
      { value: "team", label: "Team-approved" },
    ]},
  { id: "maintenance", label: "Maintenance", multi: false,
    options: [
      { value: "active", label: "Active" },
      { value: "recent", label: "Updated recently" },
    ]},
  { id: "pricing", label: "Pricing", multi: true,
    options: ["Free", "Paid", "Internal"] },
  { id: "install", label: "Install type", multi: true,
    options: ["One-click", "CLI", "Repo import"] },
];

function BrowseScreen({ onOpen, onInstall, query, setQuery, prefilters, installedSet }) {
  const [filters, setFilters] = useStateB(() => ({
    category: prefilters?.cat ? [prefilters.cat] : [],
    environment: [],
    trust: [],
    maintenance: null,
    pricing: [],
    install: [],
  }));
  const [sort, setSort] = useStateB("Recommended");
  const [layout, setLayout] = useStateB("grid"); // grid | list

  const results = useMemoB(() => {
    const q = (query || "").trim().toLowerCase();
    let out = SKILLS.filter(s => {
      if (q) {
        const hay = [s.name, s.one_liner, s.description, s.author, s.category, ...(s.use_cases||[])].join(" ").toLowerCase();
        if (!hay.includes(q)) return false;
      }
      if (filters.category.length && !filters.category.includes(s.category)) return false;
      if (filters.environment.length && !filters.environment.some(e => s.compatibility.includes(e))) return false;
      if (filters.trust.length && !filters.trust.every(t => s.badges.includes(t))) return false;
      if (filters.maintenance === "recent" && !["1 day ago","Yesterday","2 days ago","3 days ago","4 days ago","5 days ago","1 week ago"].includes(s.last_updated)) return false;
      if (filters.pricing.length && !filters.pricing.includes(s.pricing)) return false;
      return true;
    });
    if (sort === "Trending") out = [...out].sort((a,b) => b.installs_30d - a.installs_30d);
    else if (sort === "Most used") out = [...out].sort((a,b) => b.installs_30d - a.installs_30d);
    else if (sort === "Recently updated") out = [...out].sort((a,b) => a.last_updated.localeCompare(b.last_updated));
    else if (sort === "Best rated") out = [...out].sort((a,b) => (b.rating||0) - (a.rating||0));
    return out;
  }, [query, filters, sort]);

  const toggleMulti = (groupId, value) => {
    setFilters(f => {
      const set = new Set(f[groupId] || []);
      if (set.has(value)) set.delete(value); else set.add(value);
      return { ...f, [groupId]: [...set] };
    });
  };
  const setSingle = (groupId, value) => {
    setFilters(f => ({ ...f, [groupId]: f[groupId] === value ? null : value }));
  };
  const clearAll = () => setFilters({ category: [], environment: [], trust: [], maintenance: null, pricing: [], install: [] });

  const activeCount = Object.values(filters).reduce((n, v) => n + (Array.isArray(v) ? v.length : (v ? 1 : 0)), 0);

  return (
    <div className="col">
      {/* Search bar */}
      <div style={{ borderBottom: "1px solid var(--line)", padding: "20px 0", background: "var(--bg-soft)" }}>
        <div className="page row gap-3" style={{ alignItems: "center" }}>
          <div className="row gap-3" style={{
            flex: 1, height: 44, padding: "0 14px",
            border: "1px solid var(--line-strong)", borderRadius: 10, background: "var(--bg)",
          }}>
            <I.Search size={16} style={{ color: "var(--ink-3)" }} />
            <input value={query || ""} onChange={(e) => setQuery(e.target.value)}
              placeholder="Search skills, authors, tasks…"
              style={{ flex: 1, border: "none", outline: "none", background: "transparent", font: "400 14.5px/1 var(--font-sans)" }}
            />
            {query && (
              <button className="icon-btn" onClick={() => setQuery("")} style={{ width: 24, height: 24 }}>
                <I.X size={12} />
              </button>
            )}
          </div>
          <div className="row gap-1" style={{ background: "var(--bg)", border: "1px solid var(--line-strong)", borderRadius: 8, padding: 2 }}>
            <button className={`icon-btn ${layout === "grid" ? "" : ""}`}
              onClick={() => setLayout("grid")}
              style={{ background: layout === "grid" ? "var(--bg-muted)" : "transparent", color: layout === "grid" ? "var(--ink)" : "var(--ink-3)" }}>
              <I.Grid size={14} />
            </button>
            <button className="icon-btn"
              onClick={() => setLayout("list")}
              style={{ background: layout === "list" ? "var(--bg-muted)" : "transparent", color: layout === "list" ? "var(--ink)" : "var(--ink-3)" }}>
              <I.List size={14} />
            </button>
          </div>
        </div>
      </div>

      <div className="page" style={{ padding: "28px 28px 56px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 36 }}>
          {/* FILTER RAIL */}
          <aside className="col gap-6" style={{ position: "sticky", top: 80, alignSelf: "start", maxHeight: "calc(100vh - 96px)", overflow: "auto", paddingRight: 4 }}>
            <div className="row between" style={{ alignItems: "baseline" }}>
              <div className="row gap-2" style={{ alignItems: "baseline" }}>
                <I.Sliders size={14} style={{ color: "var(--ink-3)" }} />
                <span style={{ font: "600 13px/1 var(--font-sans)" }}>Filters</span>
                {activeCount > 0 && <span className="meta">({activeCount})</span>}
              </div>
              {activeCount > 0 && (
                <button className="btn-ghost btn btn-sm" onClick={clearAll} style={{ height: 22, padding: "0 6px", fontSize: 12 }}>Clear</button>
              )}
            </div>
            {FILTER_GROUPS.map(g => (
              <div key={g.id} className="col gap-3">
                <div style={{ font: "600 11px/1 var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-3)" }}>{g.label}</div>
                <div className="col gap-2">
                  {g.options.map(opt => {
                    const value = typeof opt === "string" ? opt : opt.value;
                    const label = typeof opt === "string" ? opt : opt.label;
                    const active = g.multi
                      ? (filters[g.id] || []).includes(value)
                      : filters[g.id] === value;
                    return (
                      <label key={value} className="row gap-2" style={{ cursor: "pointer", padding: "2px 0" }}>
                        <input
                          type={g.multi ? "checkbox" : "radio"}
                          checked={active}
                          onChange={() => g.multi ? toggleMulti(g.id, value) : setSingle(g.id, value)}
                          style={{ accentColor: "var(--accent)" }}
                        />
                        <span className="body-sm" style={{ color: active ? "var(--ink)" : "var(--ink-2)" }}>{label}</span>
                      </label>
                    );
                  })}
                </div>
              </div>
            ))}
          </aside>

          {/* RESULTS */}
          <div className="col gap-5">
            <div className="row between" style={{ alignItems: "baseline" }}>
              <div className="col gap-1">
                <h2 className="h3" style={{ margin: 0 }}>
                  {query ? `Results for “${query}”` : "All skills"}
                </h2>
                <div className="body-sm text-3">
                  {results.length} {results.length === 1 ? "skill" : "skills"}
                  {activeCount > 0 && ` · ${activeCount} ${activeCount === 1 ? "filter" : "filters"} applied`}
                </div>
              </div>
              <div className="row gap-3">
                <span className="meta">Sort by</span>
                <select value={sort} onChange={(e) => setSort(e.target.value)}
                  style={{
                    appearance: "none",
                    height: 32, padding: "0 28px 0 12px",
                    border: "1px solid var(--line-strong)", borderRadius: 8, background: "var(--bg)",
                    font: "500 13px/1 var(--font-sans)", color: "var(--ink-1)",
                    backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path fill='rgba(0,0,0,.5)' d='M0 0h10L5 6z'/></svg>\")",
                    backgroundRepeat: "no-repeat",
                    backgroundPosition: "right 10px center",
                  }}>
                  {["Recommended","Trending","Most used","Recently updated","Best rated"].map(o => <option key={o}>{o}</option>)}
                </select>
              </div>
            </div>

            {/* Active filter row */}
            {activeCount > 0 && (
              <div className="row gap-2 wrap" style={{ paddingBottom: 4 }}>
                {Object.entries(filters).flatMap(([g, v]) => {
                  if (!v) return [];
                  const arr = Array.isArray(v) ? v : [v];
                  return arr.map(item => {
                    const grp = FILTER_GROUPS.find(x => x.id === g);
                    const o = grp.options.find(o => (typeof o === "string" ? o : o.value) === item);
                    const lbl = typeof o === "string" ? o : (o?.label || item);
                    return (
                      <span key={`${g}-${item}`} className="chip active" onClick={() => grp.multi ? toggleMulti(g, item) : setSingle(g, item)}>
                        {lbl}
                        <I.X size={10} />
                      </span>
                    );
                  });
                })}
              </div>
            )}

            {results.length === 0 ? (
              <div className="card col gap-3" style={{ padding: 36, alignItems: "center", textAlign: "center" }}>
                <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--bg-muted)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}>
                  <I.Search size={20} />
                </div>
                <div style={{ font: "600 16px/1.2 var(--font-display)" }}>No skills match those filters.</div>
                <div className="body-sm text-3" style={{ maxWidth: 380 }}>
                  Try a broader search like “review”, “summarize”, or “deploy” — or clear filters to see everything.
                </div>
                <div className="row gap-2">
                  <button className="btn" onClick={clearAll}>Clear filters</button>
                  <button className="btn btn-primary" onClick={() => setQuery("")}>Reset search</button>
                </div>
              </div>
            ) : layout === "grid" ? (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
                {results.map(s => <SkillCard key={s.id} skill={s} onOpen={onOpen} onInstall={onInstall} installed={installedSet.has(s.id)} />)}
              </div>
            ) : (
              <div className="col gap-2">
                {results.map(s => <SkillRow key={s.id} skill={s} onOpen={onOpen} onInstall={onInstall} installed={installedSet.has(s.id)} />)}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BrowseScreen = BrowseScreen;
