// Category hub + Topic hub components.
// Reads window.LANE + window.CATEGORY (and optional window.TOPIC) and pulls
// straight from window.FINANCE_TAXONOMY. One component for both levels so
// every /lane/category/ and /lane/category/topic/ URL renders from the
// same data source — no duplicated copy.

const _leafUrl = window.leafUrl || (() => null);

function CatBreadcrumbs({ lane, cat, topic }) {
  const laneLabel = lane.slug === "personal" ? "PERSONAL" : "BUSINESS";
  const homeHref = `/${lane.slug}/`;
  const catHref = `/${lane.slug}/${cat.slug}/`;
  const pathText = topic ? `/${lane.slug}/${cat.slug}/${topic.slug}` : `/${lane.slug}/${cat.slug}`;
  const totalGuides = topic
    ? topic.guides.length
    : cat.topics.reduce((n, t) => n + t.guides.length, 0);
  return (
    <div className="crumbs">
      <div className="crumbs__inner">
        <a href="/" className="crumbs__item">HOME</a>
        <span className="crumbs__sep">/</span>
        <a href={homeHref} className="crumbs__item">{laneLabel}</a>
        <span className="crumbs__sep">/</span>
        {topic ? (
          <>
            <a href={catHref} className="crumbs__item">{cat.name.toUpperCase()}</a>
            <span className="crumbs__sep">/</span>
            <span className="crumbs__item" style={{color: "var(--forest-ink)"}}>{topic.name.toUpperCase()}</span>
          </>
        ) : (
          <span className="crumbs__item" style={{color: "var(--forest-ink)"}}>{cat.name.toUpperCase()}</span>
        )}
        <span className="crumbs__spacer" />
        <span className="crumbs__stats">
          <span>PATH</span>
          <span className="crumbs__val">{pathText}</span>
          <span>·</span>
          <span>COUNT</span>
          <span className="crumbs__val">{totalGuides}</span>
        </span>
      </div>
    </div>
  );
}

function CatHero({ lane, cat, topic }) {
  const isP = lane.slug === "personal";
  const laneNum = isP ? "01" : "02";
  const laneLabel = isP ? "PERSONAL" : "BUSINESS";
  const title = topic ? topic.name : cat.name;
  const tagline = topic
    ? `${topic.guides.length} ways to handle ${topic.name.toLowerCase()} — filed plainly, structured like a procedure.`
    : cat.tagline;
  const totalGuides = topic
    ? topic.guides.length
    : cat.topics.reduce((n, t) => n + t.guides.length, 0);
  const crumbLabel = topic ? `${cat.name.toUpperCase()} · ${topic.name.toUpperCase()}` : cat.name.toUpperCase();
  return (
    <section className={`lane-hero lane-hero--${lane.slug}`}>
      <div className="lane-hero__bg" aria-hidden="true" />
      <div className="lane-hero__inner">
        <div className="lane-hero__meta">
          <span className="lane-hero__num">{laneNum}</span>
          <span className="lane-hero__bar" />
          <span className="lane-hero__label">{laneLabel} · {crumbLabel}</span>
          <span className="lane-hero__dot">·</span>
          <span className="lane-hero__counter">{totalGuides} GUIDES</span>
          <span className="lane-hero__dot">·</span>
          <span className="lane-hero__counter">UPDATED WEEKLY</span>
        </div>
        <h1 className="lane-hero__h1">{title}</h1>
        <p className="lane-hero__lede">{tagline}</p>
        <form className="lane-hero__search" onSubmit={(e) => e.preventDefault()}>
          <span className="lane-hero__search-label">SEARCH &gt;</span>
          <input placeholder={`search ${title.toLowerCase()}…`} />
          <span className="lane-hero__search-kbd">⌘ K</span>
          <button type="submit" className="lane-hero__search-btn">EXECUTE</button>
        </form>
      </div>
    </section>
  );
}

/* ========== TOPIC CARDS (used inside CategoryHub) ==========
   Each card shows a single topic and its 5 guide titles as a preview.
   Clicking the card headline goes to the topic hub; clicking a built
   guide title goes straight to the leaf. */

function TopicCard({ lane, cat, topic, index, hover }) {
  const topicHref = `/${lane.slug}/${cat.slug}/${topic.slug}/`;
  return (
    <article className={`subcat ${hover ? "is-hover" : ""}`} style={{display: "flex"}}>
      <div className="subcat__top">
        <div className="subcat__num">{String(index + 1).padStart(2, "0")}</div>
        <div className="subcat__count">
          <span className="subcat__count-v">{topic.guides.length}</span>
          <span className="subcat__count-k">GUIDES</span>
        </div>
      </div>
      <h3 className="subcat__title">
        <a href={topicHref} style={{color: "inherit", textDecoration: "none"}}>{topic.name}</a>
      </h3>
      <ul className="subcat__guides">
        {topic.guides.map((g) => {
          const url = _leafUrl(g.title) || `/${lane.slug}/${cat.slug}/${topic.slug}/${g.slug}/`;
          const isBuilt = g.status === "built";
          const byline = g.author ? g.author.toUpperCase() : null;
          return (
            <li key={g.slug}>
              <a href={url} className={`subcat__guide ${isBuilt ? "is-built" : ""}`}>
                <span className="subcat__guide-t">{g.title}</span>
                {byline && <span className="subcat__guide-by">{byline}</span>}
              </a>
            </li>
          );
        })}
      </ul>
      <div className="subcat__cta">
        <a href={topicHref} style={{color: "inherit", textDecoration: "none", display: "flex", justifyContent: "space-between", alignItems: "center", width: "100%"}}>
          <span>ENTER {topic.name.toUpperCase()}</span>
          <span className="subcat__arrow">→</span>
        </a>
      </div>
    </article>
  );
}

function CategoryBody({ lane, cat }) {
  return (
    <section className="subcats" data-cols="2" data-density="default">
      <div className="section-head section-head--left">
        <div className="section-head__kicker">
          <span className="bar"/> {cat.name.toUpperCase()} · 04 TOPICS
        </div>
        <h2 className="section-head__h2">Four corners of {cat.name.toLowerCase()}.</h2>
        <p className="section-head__sub">
          {cat.tagline} Pick the topic closest to the question you're sitting with.
        </p>
      </div>
      <div className="subcats__grid" data-cols="2">
        {cat.topics.map((topic, i) => (
          <TopicCard
            key={topic.slug}
            lane={lane}
            cat={cat}
            topic={topic}
            index={i}
            hover={i === 1}
          />
        ))}
      </div>
    </section>
  );
}

/* ========== TOPIC HUB BODY — the 5 guide cards ========== */

function TopicGuideRow({ lane, cat, topic, g, i }) {
  const url = _leafUrl(g.title) || `/${lane.slug}/${cat.slug}/${topic.slug}/${g.slug}/`;
  const byline = (g.author || "IRIS").toUpperCase();
  const status = g.status === "built"
    ? <span className="pill pill--mint">PUBLISHED ▲</span>
    : g.status === "drafting"
      ? <span className="pill">DRAFTING</span>
      : <span className="pill">IRIS QUEUE</span>;
  return (
    <a href={url} className="guides__row">
      <div className="guides__idx">{String(i + 1).padStart(3, "0")}</div>
      <div className="guides__title">{g.title}</div>
      <div className="guides__cat">{byline}</div>
      <div className="guides__time">—</div>
      <div className="guides__status">{status}</div>
    </a>
  );
}

function TopicBody({ lane, cat, topic }) {
  return (
    <section className="guides">
      <div className="section-head section-head--left">
        <div className="section-head__kicker">
          <span className="bar"/> {topic.name.toUpperCase()} · 05 GUIDES
        </div>
        <h2 className="section-head__h2">Everything in {topic.name.toLowerCase()}.</h2>
        <p className="section-head__sub">
          Five how-tos in this topic, filed by rank. Built guides open immediately; queued guides open when Iris files them — usually within the hour.
        </p>
      </div>
      <div className="guides__table">
        <div className="guides__head">
          <div>#</div>
          <div>TITLE</div>
          <div>WRITER</div>
          <div>READ</div>
          <div>STATUS</div>
        </div>
        {topic.guides.map((g, i) => (
          <TopicGuideRow key={g.slug} lane={lane} cat={cat} topic={topic} g={g} i={i} />
        ))}
      </div>
      <div className="guides__foot">
        <span className="guides__foot-meta">
          Showing {topic.guides.length} of {topic.guides.length} · {topic.name.toUpperCase()}
        </span>
      </div>
    </section>
  );
}

/* ========== RELATED RAIL — three sibling topics / three sibling cats ========== */

function RelatedRail({ lane, cat, topic }) {
  if (topic) {
    const siblings = cat.topics.filter((t) => t.slug !== topic.slug);
    return (
      <section className="related-rail">
        <div className="related-rail__inner">
          <div className="section-head__kicker">
            <span className="bar"/> OTHER TOPICS IN {cat.name.toUpperCase()}
          </div>
          <div className="related-rail__grid">
            {siblings.map((t) => (
              <a key={t.slug} href={`/${lane.slug}/${cat.slug}/${t.slug}/`} className="related-rail__card">
                <div className="related-rail__k">{cat.name.toUpperCase()}</div>
                <div className="related-rail__n">{t.name}</div>
                <div className="related-rail__c">{t.guides.length} GUIDES →</div>
              </a>
            ))}
          </div>
        </div>
      </section>
    );
  }
  const siblings = lane.categories.filter((c) => c.slug !== cat.slug).slice(0, 3);
  return (
    <section className="related-rail">
      <div className="related-rail__inner">
        <div className="section-head__kicker">
          <span className="bar"/> ELSEWHERE IN {lane.label.toUpperCase()}
        </div>
        <div className="related-rail__grid">
          {siblings.map((c) => {
            const count = c.topics.reduce((n, t) => n + t.guides.length, 0);
            return (
              <a key={c.slug} href={`/${lane.slug}/${c.slug}/`} className="related-rail__card">
                <div className="related-rail__k">{lane.label.toUpperCase()}</div>
                <div className="related-rail__n">{c.name}</div>
                <div className="related-rail__c">{count} GUIDES →</div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  CatBreadcrumbs, CatHero, TopicCard, CategoryBody, TopicBody, RelatedRail,
});
