// Ch.06 Resources: categorized toolbelt

const RESOURCES_RED = "#c0392b";

// In the "Studio & community" lane, only these render as full cards; everything
// else (synths, FX, samplers, sample packs) collapses into a compact
// "Plugins & sounds" chip shell so the gear list stops dominating the page.
const PRODUCE_CORE = new Set(["skool", "untitled", "dropbox", "fl-studio", "ableton"]);

function ToolIcon({ tool, size = 40 }) {
  const base = window.RESOURCE_LOGO_BASE || "assets/tools";
  if (tool.logo) {
    return (
      <img
        src={`${base}/${tool.logo}`}
        alt=""
        className="resources-card-logo-img"
        style={{ width: size, height: size }}
        loading="lazy"
        decoding="async"
      />
    );
  }
  return (
    <span
      className="resources-card-logo-fallback"
      style={{
        width: size,
        height: size,
        background: `color-mix(in srgb, ${tool.color || RESOURCES_RED} 22%, rgba(255,255,255,0.06))`,
        borderColor: `color-mix(in srgb, ${tool.color || RESOURCES_RED} 45%, transparent)`,
        color: tool.color || "var(--ink-2)",
        fontSize: Math.max(14, size * 0.38),
      }}
      aria-hidden="true"
    >
      {(tool.name || "?").charAt(0)}
    </span>
  );
}

function ToolCard({ tool, lane, highlighted }) {
  const laneObj = lane || window.getResourceLane?.(tool.lane);
  return (
    <a
      id={`resources-${tool.id}`}
      href={tool.url}
      target="_blank"
      rel="noopener noreferrer"
      className={`resources-card${highlighted ? " resources-card--highlight" : ""}`}
    >
      <div className="resources-card-top">
        <ToolIcon tool={tool} />
        <div className="resources-card-meta">
          <span className="resources-card-name">{tool.name}</span>
          <span className="resources-card-lane caption">{laneObj?.label}</span>
        </div>
        <span className="resources-card-arrow" aria-hidden="true">↗</span>
      </div>
      <p className="resources-card-blurb">{tool.blurb}</p>
    </a>
  );
}

function ToolChip({ tool, highlighted }) {
  return (
    <a
      id={`resources-${tool.id}`}
      href={tool.url}
      target="_blank"
      rel="noopener noreferrer"
      className={`resources-chip${highlighted ? " resources-chip--highlight" : ""}`}
      title={tool.blurb}
    >
      <ToolIcon tool={tool} size={22} />
      <span className="resources-chip-name">{tool.name}</span>
    </a>
  );
}

function ResourceLaneSection({ lane, tools, highlightTool }) {
  if (!tools.length) return null;
  const isProduce = lane.id === "produce";
  const cards = isProduce ? tools.filter((t) => PRODUCE_CORE.has(t.id)) : tools;
  const packed = isProduce ? tools.filter((t) => !PRODUCE_CORE.has(t.id)) : [];
  return (
    <section id={`resources-lane-${lane.id}`} className="resources-lane" aria-labelledby={`resources-lane-title-${lane.id}`}>
      <div className="resources-lane-head">
        <span className="caption resources-lane-eyebrow">{lane.sub}</span>
        <h3 id={`resources-lane-title-${lane.id}`} className="kicker" style={{ margin: "8px 0 0" }}>{lane.label}</h3>
      </div>
      {cards.length > 0 && (
        <div className="resources-grid">
          {cards.map((tool) => (
            <ToolCard key={tool.id} tool={tool} lane={lane} highlighted={highlightTool === tool.id} />
          ))}
        </div>
      )}
      {packed.length > 0 && (
        <div className="resources-pack">
          <span className="caption resources-pack-label">Plugins &amp; sounds · {packed.length}</span>
          <div className="resources-pack-grid">
            {packed.map((tool) => (
              <ToolChip key={tool.id} tool={tool} highlighted={highlightTool === tool.id} />
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

function ResourceLanePicker({ items, active, onChange }) {
  const stripRef = React.useRef(null);
  const [compact, setCompact] = React.useState(() =>
    typeof window !== "undefined" && window.matchMedia("(max-width: 900px)").matches
  );

  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 900px)");
    const sync = () => setCompact(mq.matches);
    sync();
    mq.addEventListener("change", sync);
    return () => mq.removeEventListener("change", sync);
  }, []);

  React.useEffect(() => {
    if (!compact || !stripRef.current) return;
    const btn = stripRef.current.querySelector(`[data-lane-id="${active}"]`);
    if (btn) btn.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
  }, [active, compact]);

  if (compact) {
    return (
      <div className="resources-lane-strip" ref={stripRef} role="tablist" aria-label="Resource categories">
        <div className="resources-lane-scroll">
          {items.map((it) => {
            const isActive = it.id === active;
            return (
              <button
                key={it.id}
                type="button"
                data-lane-id={it.id}
                className={`resources-lane-btn${isActive ? " active" : ""}`}
                role="tab"
                aria-selected={isActive ? "true" : "false"}
                onClick={() => onChange(it.id)}
              >
                <span className="resources-lane-btn-num">{it.num}</span>
                <span className="resources-lane-btn-label">{it.label}</span>
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  return (
    <GlassSegmented
      className="glass-seg-resources"
      items={items}
      active={active}
      onChange={onChange}
      ariaLabel="Resource categories"
      full
    />
  );
}

function Resources({ navTarget }) {
  const lanes = window.RESOURCE_LANES || [];
  const tools = window.RESOURCE_TOOLS || [];
  const [filter, setFilter] = React.useState("all");
  const [highlightTool, setHighlightTool] = React.useState(null);

  const filterItems = [
    { id: "all", num: "00", label: "All", sub: "Full toolbelt", color: RESOURCES_RED },
    ...lanes.map((l, i) => ({
      id: l.id,
      num: String(i + 1).padStart(2, "0"),
      label: l.label.split(" & ")[0],
      sub: l.sub,
      color: RESOURCES_RED,
    })),
  ];

  React.useEffect(() => {
    if (!navTarget || navTarget.chapter !== "06") return;
    if (navTarget.lane) setFilter(navTarget.lane);
    if (navTarget.tool) {
      const tool = window.getResourceTool?.(navTarget.tool);
      if (tool) {
        setFilter(tool.lane);
        setHighlightTool(tool.id);
        requestAnimationFrame(() => {
          const el = document.getElementById(`resources-${tool.id}`);
          if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
        });
        const t = setTimeout(() => setHighlightTool(null), 2400);
        return () => clearTimeout(t);
      }
    }
    if (navTarget.lane && navTarget.lane !== "all") {
      requestAnimationFrame(() => {
        const el = document.getElementById(`resources-lane-${navTarget.lane}`);
        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      });
    }
  }, [navTarget?.key]);

  const visibleLanes = filter === "all"
    ? lanes
    : lanes.filter((l) => l.id === filter);

  return (
    <section className="section rule-top" id="resources">
      <div className="page">
        <div className="grid" style={{ alignItems: "end", marginBottom: 32 }}>
          <div className="col-4 col-md-5 col-lg-8">
            <span className="caption" style={{ color: RESOURCES_RED }}>06 · Resources</span>
            <h2 className="h-section" style={{ margin: "12px 0 0" }}>
              The <em>toolbelt</em>.
            </h2>
          </div>
          <div className="col-4 col-md-3 col-lg-4">
            <p className="lede" style={{ margin: 0 }}>
              Tools I actually use, not affiliate spam.
            </p>
          </div>
        </div>

        <div style={{ marginTop: 36 }}>
          <ResourceLanePicker
            items={filterItems}
            active={filter}
            onChange={setFilter}
          />
        </div>

        <div className="resources-lanes" style={{ marginTop: 36 }}>
          {visibleLanes.map((lane) => (
            <ResourceLaneSection
              key={lane.id}
              lane={lane}
              tools={tools.filter((t) => t.lane === lane.id)}
              highlightTool={highlightTool}
            />
          ))}
        </div>

        <p className="caption" style={{ marginTop: 40, color: "var(--ink-4)" }}>
          ★ No affiliate links. If something breaks or a better tool shows up, this list gets updated.
        </p>
      </div>
    </section>
  );
}

window.Resources = Resources;
