// components.jsx: shared primitives for the role guide pages.

/* ── Shared design-token data (single source of truth) ─────────────────────
   LL_TIERS is consumed by ds-foundations.jsx (palette swatches) and
   ds-patterns.jsx (TierDisplayPattern, Leaderboard). The "var" field points
   to the live CSS token in styles.css; "hex" is documentation only and is
   the same hex the token resolves to in every palette.
   ──────────────────────────────────────────────────────────────────────── */
const LL_TIERS = [
  { name: "Iron",       var: "--tier-iron",        hex: "#5b5959" },
  { name: "Bronze",     var: "--tier-bronze",      hex: "#a26939" },
  { name: "Silver",     var: "--tier-silver",      hex: "#9ba6b3" },
  { name: "Gold",       var: "--tier-gold",        hex: "#e39a3c" },
  { name: "Platinum",   var: "--tier-platinum",    hex: "#4ea3a3" },
  { name: "Emerald",    var: "--tier-emerald",     hex: "#3f9670" },
  { name: "Diamond",    var: "--tier-diamond",     hex: "#6fa8dc" },
  { name: "Master",     var: "--tier-master",      hex: "#a868d4" },
  { name: "GM",         var: "--tier-grandmaster", hex: "#c9484a" },
  { name: "Challenger", var: "--tier-challenger",  hex: "#d4b468" },
];

// Data Dragon patch version for champion portraits (single source of truth).
const DDRAGON_VER = "14.23.1";

// Current LoL patch shown across the guides. Bump this in ONE place when you
// refresh content for a new patch; role data references it via LL_PATCH.
const LL_PATCH = "26.12";

/* ── ErrorBoundary ─────────────────────────────────────────────────────────
   Wraps each section so a render error in one (e.g. a malformed role-data
   entry) shows a small inline notice instead of blanking the whole page.
   Note: this catches RENDER errors. A syntax error in a role-<x>.jsx file
   stops that file from setting window.ROLE_DATA, which app.jsx already handles
   with its own "No ROLE_DATA" guard. Together they keep the page from going
   blank on a bad edit. */
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, info) {
    console.error("Section failed to render:", this.props.label || "", error, info);
  }
  render() {
    if (this.state.error) {
      return (
        <section className="section shell">
          <p className="section-error">
            This section couldn't be displayed{this.props.label ? ` (${this.props.label})` : ""}.
            The rest of the page is unaffected.
          </p>
        </section>
      );
    }
    return this.props.children;
  }
}

/* ── Glossary ─────────────────────────────────────────────────────────────
   Single source of truth for short, inline LoL term definitions. Use the
   <Gloss term="..."/> component on the FIRST mention of a term in a guide
   to wrap it in a dotted underline + native tooltip. If a term is missing
   here, add it once. Never inline glosses ad-hoc in section files.
   ──────────────────────────────────────────────────────────────────────── */
const LL_GLOSSARY = {
  "CS":            "Creep Score: minions you last-hit for gold.",
  "trinket":       "The free warding tool every champion starts with.",
  "control ward":  "Pink ward: denies enemy vision in its area.",
  "pink ward":     "Older name for a control ward. Denies enemy vision.",
  "scuttle":       "The neutral crab in the river. First one spawns at 2:55.",
  "invade":        "An early enemy push into your jungle, usually pre-1:30.",
  "peel":          "Standing between your carry and the threat that wants them dead.",
  "pit":           "The walled area where an objective (Drake, Baron) spawns.",
  "freeze":        "Holding the wave near your tower so it never pushes.",
  "vision score":  "The in-game stat measuring your contribution to map vision.",
  "TP":            "Teleport: Summoner spell that lets you re-enter a lane from base.",
  "APC":           "AP Carry: a magic-damage carry (e.g. Veigar, Karthus bot).",
  "ADC":           "Attack Damage Carry: the ranged auto-attacker of the bot lane.",
  "keystone":      "The top-row rune that defines your laning identity.",
  "engage":        "Starting a fight. Usually with a hard CC ability.",
  "all-in":        "Committing every cooldown to kill the enemy now.",
  "poke":          "Chipping enemy HP from range without committing to a fight.",
  "enchanter":     "A support archetype focused on shields, heals and buffs.",
  "summoners":     "Summoner Spells: the two extra abilities (Flash, Heal, Ignite…).",
  "Ezreal E":      "Ezreal's dash ability: short blink + skillshot.",
  "Lucian E":      "Lucian's dash ability: short skillshot dash.",
  "kiting":        "Attacking then moving between each auto so you deal damage without standing still. Also called orb-walking.",
  "attack-move":   "A click (default A + click) that auto-attacks the best target near the cursor instead of walking onto it.",
  "power spike":   "A moment your champion gets much stronger: a key item, level, or ability rank.",
  "hypercarry":    "A marksman that is weak early but becomes the team's main damage once it has items.",
  "lethality":     "Flat armor penetration, strongest early. Used by burst marksmen and assassins.",
  "shutdown":      "Bonus gold the enemy earns for killing a fed champion.",
  "trade":         "A short exchange of damage with your laner, then backing off before they retaliate.",
  "slow push":     "Letting your wave grow by only last-hitting, so it crashes big into the enemy tower later.",
  "crash":         "Pushing the whole wave into the enemy tower so it dies there, freeing you to recall or roam.",
  "split push":    "Pushing a side lane on your own to threaten towers and pull enemies away from your team.",
  "juggernaut":    "A melee fighter with high damage and durability but little mobility (Garen, Darius).",
  "Voidgrubs":     "Early top-side river monsters; killing them grants a buff that helps your team break towers.",
  "Rift Herald":   "A top-side river objective; the Eye of the Herald charges into a tower for free plates.",
  "Conqueror":     "A keystone rune that stacks bonus damage as you keep fighting, then heals at full stacks.",
  "Grasp":         "Grasp of the Undying: a keystone that adds bonus damage and healing on a hit every few seconds.",
  "roam":          "Leaving your lane to make a play somewhere else on the map.",
  "lane priority": "The freedom to leave lane, earned when your wave is pushing or you've won the matchup.",
  "waveclear":     "Killing a whole minion wave fast, usually with abilities.",
  "shove":         "Pushing the wave into the enemy tower as fast as you can.",
  "recall":        "Channelling back to base to spend gold and heal (the 'B' button).",
  "skillshot":     "An ability you have to aim, that can miss (a line, a projectile, a zone).",
  "burst":         "Dealing a large amount of damage in a very short window.",
  "assassin":      "A champion built to delete a single target fast, then escape.",
  "control mage":  "A mage that clears waves and zones space from range, scaling into teamfights.",
  "Smite":         "The jungler's summoner spell: heavy damage to monsters, used to secure objectives.",
  "pathing":       "The order you clear your jungle camps in.",
  "gank":          "Ambushing an enemy in a lane with help from outside it.",
  "leash":         "When a laner helps you damage your first camp at the start of the game.",
  "counter-jungle":"Taking camps from the enemy jungler's side to deny them gold and XP.",
  "jungle companion":"The starting jungle item (a small pet) that grows as you clear camps.",
  "objective":     "A neutral monster that gives a team-wide reward: Dragon, Herald, Baron.",
  "skirmish":      "A small fight, usually 2v2 or 3v3, often around a camp or objective.",
  "power farm":    "Clearing camps non-stop to hit your item spikes fast instead of ganking.",
};

/* <Gloss term="CS">CS</Gloss>
   <Gloss term="vision score" def="custom override if you must" />
   First-mention helper. Looks up term in LL_GLOSSARY; def prop wins if given.
   Renders an <abbr> with a native tooltip: no JS hover state needed. */
function Gloss({ term, def, children }) {
  const title = def || LL_GLOSSARY[term] || LL_GLOSSARY[term && term.toLowerCase()];
  return (
    <abbr className="gloss" title={title} data-term={term}>
      {children || term}
    </abbr>
  );
}

/* ── Callout: now the library's LL.Callout (LearningLeagues-Lib, vendored in
   lib/ll-lib.jsx): <LL.Callout type="key|pro|trap" title="…">body</LL.Callout>.
   type is required (no fallback); the label and glyph come from the type. */

/* ── ErrorCard: Symptom / Cause / Fix template ───────────────────────────
   <ErrorCard title="" symptom={…} cause={…} fix={…} />
   The §06 "6 mistakes" pattern lifted into a single component so every
   future role guide uses the exact same Symptom/Cause/Fix triad without
   re-implementing the markup. Children of each field can be a string or
   JSX (e.g. <Gloss term="vision score" /> inside symptom). */
function ErrorCard({ title, symptom, cause, fix }) {
  return (
    <article className="error-card">
      <h3 className="error-title serif">{title}</h3>
      <div className="error-block">
        <span className="error-lbl">Symptom</span>
        <p className="error-text">{symptom}</p>
      </div>
      <div className="error-block">
        <span className="error-lbl">Cause</span>
        <p className="error-text">{cause}</p>
      </div>
      <div className="error-block">
        <span className="error-lbl">Fix</span>
        <p className="error-text">{fix}</p>
      </div>
    </article>
  );
}

function LogoMark() {
  return (
    <svg className="logo-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2">
      <path d="M12 1.5 22.4 7.5 22.4 16.5 12 22.5 1.6 16.5 1.6 7.5Z" />
      <path d="M12 6 18 9.5 18 14.5 12 18 6 14.5 6 9.5Z" />
      <circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none" />
    </svg>
  );
}

function Nav({ activeKey = "roles" }) {
  const linkProps = (key) => ({
    className: "nav-link" + (activeKey === key ? " is-active" : ""),
    "aria-current": activeKey === key ? "page" : undefined,
  });
  const mobileLinks = [
    { key: "foundations", label: "Foundations", href: "Fundamentals.html" },
    { roles: true },
    { key: "champions", label: "Champions", href: "#" },
    { key: "macro", label: "Macro", href: "#" },
    { key: "glossary", label: "Glossary", href: "Glossary.html" },
    { key: "quiz", label: "Role quiz", href: "Quiz.html" },
  ];
  return (
    <div className="nav">
      <div className="shell nav-inner">
        <a className="logo" href="index.html">
          <LogoMark />
          <span>Learning Leagues</span>
        </a>
        <nav className="nav-links" aria-label="Primary">
          <a {...linkProps("foundations")} href="Fundamentals.html">Foundations</a>
          <RolesDropdown active={activeKey === "roles"} />
          <a {...linkProps("champions")} href="#">Champions</a>
          <a {...linkProps("macro")} href="#">Macro</a>
          <a {...linkProps("glossary")} href="Glossary.html">Glossary</a>
        </nav>
        <div className="nav-right">
          <LangSwitcher />
          {/* Library Button since 2026-08-30; its current (you-are-here) state
              since 2026-09-16: the ask filed at adoption, delivered as the
              library's current prop (lib pin 45ea047). .nav-cta-wrap is
              product layout: mobile hiding. */}
          <span className="nav-cta-wrap">
            <LL.Button variant="secondary" href="Quiz.html" current={activeKey === "quiz"}>
              <span>Role quiz</span>
              <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square">
                <path d="M3 8h10M9 4l4 4-4 4" />
              </svg>
            </LL.Button>
          </span>
          <MobileMenu links={mobileLinks} activeKey={activeKey} />
        </div>
      </div>
    </div>
  );
}

const LL_ROLES = [
  { name: "Top",     href: "Top.html" },
  { name: "Jungle",  href: "Jungle.html" },
  { name: "Mid",     href: "Mid.html" },
  { name: "ADC",     href: "ADC.html" },
  { name: "Support", href: "Support.html" },
];

function RolesDropdown({ active }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDoc);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const roles = LL_ROLES;

  return (
    <div className="nav-roles" ref={ref}>
      <button
        type="button"
        className={"nav-link nav-roles-btn" + (active ? " is-active" : "")}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-current={active ? "page" : undefined}
        onClick={() => setOpen((o) => !o)}
      >
        <span>Roles</span>
        <svg className="nav-roles-caret" viewBox="0 0 20 16" fill="currentColor" aria-hidden="true">
          <path d="M10 0L20 16H0L10 0Z" />
        </svg>
      </button>
      {open && (
        <ul className="nav-roles-menu" role="menu">
          {roles.map((r) => (
            <li key={r.name} role="none">
              <a className="nav-roles-item" role="menuitem" href={r.href}>{r.name}</a>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

// Mobile nav: a hamburger that opens a full-width menu below the bar. The
// desktop .nav-links are hidden under 900px; this makes them reachable on phones.
function MobileMenu({ links, activeKey }) {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [open]);

  return (
    <>
      <button
        type="button"
        className="nav-burger"
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
      >
        <span className={"nav-burger-icon" + (open ? " is-open" : "")}><i></i><i></i><i></i></span>
      </button>
      {open && (
        <>
          <div className="nav-mobile-scrim" onClick={() => setOpen(false)} />
          <nav className="nav-mobile" aria-label="Mobile">
            {links.map((l, i) => l.roles ? (
              <div className="nav-mobile-group" key="roles">
                <span className="nav-mobile-label">Roles</span>
                {LL_ROLES.map((r) => (
                  <a key={r.name} className="nav-mobile-sub" href={r.href} onClick={() => setOpen(false)}>{r.name}</a>
                ))}
              </div>
            ) : (
              <a
                key={l.label}
                className={"nav-mobile-link" + (activeKey && l.key === activeKey ? " is-active" : "")}
                href={l.href}
                onClick={() => setOpen(false)}
              >{l.label}</a>
            ))}
          </nav>
        </>
      )}
    </>
  );
}

function Breadcrumb({ current }) {
  return (
    <div className="shell">
      <div className="breadcrumb">
        <a href="index.html">Home</a>
        <span className="sep">›</span>
        <a href="#">Roles</a>
        <span className="sep">›</span>
        <span className="current">{current}</span>
      </div>
    </div>
  );
}

function Hero({ eyebrow, title, intro, meta = [], sigil }) {
  return (
    <section className="hero">
      <div className="shell">
        <div className="hero-grid">
          <div>
            <div className="label-slot hero-eyebrow"><LL.Eyebrow>{eyebrow}</LL.Eyebrow></div>
            <h1 className="serif">{title}<em>.</em></h1>
            <p className="hero-intro">{intro}</p>
            <LL.MetaStrip items={meta} />
          </div>
          <div className="hero-sigil-slot">
            <LL.Sigil>{sigil}</LL.Sigil>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="shell">
        <div className="footer-top">
          <div>
            <div className="footer-brand">
              Learning Leagues
              <span className="baseline">Learning League of Legends, properly.</span>
            </div>
          </div>
          <div className="footer-cols">
            <div className="footer-col">
              <h5>Navigation</h5>
              <a href="Fundamentals.html">Foundations</a>
              <a href="#">Roles</a>
              <a href="#">Champions</a>
              <a href="#">Macro</a>
              <a href="Glossary.html">Glossary</a>
            </div>
            <div className="footer-col">
              <h5>Resources</h5>
              <a href="#">Glossary</a>
              <a href="#">Objective timings</a>
              <a href="Quiz.html">Role quiz</a>
              <a href="#">Patch changelog</a>
            </div>
            <div className="footer-col">
              <h5>Elsewhere</h5>
              <a href="#">YouTube</a>
              <a href="#">Discord</a>
              <a href="#">X / Twitter</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <p className="disclaimer">
            <strong>Learning Leagues isn't endorsed by Riot Games and doesn't reflect the views or opinions of Riot Games</strong> or anyone officially involved in producing or managing League of Legends. League of Legends and Riot Games are trademarks or registered trademarks of Riot Games, Inc.
          </p>
          <span>© 2026 · LEARNING LEAGUES</span>
        </div>
      </div>
    </footer>
  );
}

function LangSwitcher() {
  const [open, setOpen] = React.useState(false);
  const [lang, setLang] = React.useState("EN");
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);
  const langs = ["FR", "EN", "ES", "DE"];
  return (
    <div className="lang-wrap" ref={wrapRef}>
      <button
        className="lang-btn"
        aria-label="Change language"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
      >
        <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="9" />
          <path d="M3 12h18" />
          <path d="M12 3c2.5 3 2.5 15 0 18" />
          <path d="M12 3c-2.5 3-2.5 15 0 18" />
        </svg>
        <span className="lang-code mono">{lang}</span>
        <svg className="lang-chev" viewBox="0 0 10 6" width="9" height="5" fill="currentColor"><path d="M0 0h10L5 6z" /></svg>
      </button>
      {open && (
        <ul className="lang-menu" role="listbox">
          {langs.map((l) => (
            <li
              key={l}
              role="option"
              aria-selected={l === lang}
              className={"lang-item" + (l === lang ? " is-active" : "")}
              onClick={() => { setLang(l); setOpen(false); }}
            >
              <span className="mono">{l}</span>
              <span className="lang-name">{ {FR:"Français",EN:"English",ES:"Español",DE:"Deutsch"}[l] }</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function TocSidebar({ items = [] }) {
  // `items` must be fully populated and stable at mount: the initial active id
  // here and the scroll-spy effect's id list are both captured once. In the
  // engine, app.jsx builds items synchronously from window.ROLE_DATA before
  // first render and never changes them, so the empty [] effect dep is correct.
  const [active, setActive] = React.useState(items[0]?.id);
  const lockRef = React.useRef(false);
  const NAV_OFFSET = 80;
  const TRIGGER = NAV_OFFSET + 40;

  React.useEffect(() => {
    const ids = items.map((i) => i.id);
    const compute = () => {
      if (lockRef.current) return;
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        const top = el.getBoundingClientRect().top;
        if (top - TRIGGER <= 0.5) current = id;
        else break;
      }
      setActive((prev) => (prev === current ? prev : current));
    };
    compute();
    window.addEventListener("scroll", compute, { passive: true });
    window.addEventListener("resize", compute);
    return () => {
      window.removeEventListener("scroll", compute);
      window.removeEventListener("resize", compute);
    };
  }, []);

  const onClick = (e, id) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (!el) return;
    const targetTop = Math.max(
      0,
      Math.round(el.getBoundingClientRect().top + window.scrollY - NAV_OFFSET)
    );
    setActive(id);
    lockRef.current = true;

    let stableFrames = 0;
    let lastY = window.scrollY;
    let raf = 0;
    let safety = 0;
    const release = () => {
      lockRef.current = false;
      cancelAnimationFrame(raf);
      clearTimeout(safety);
    };
    const tick = () => {
      const y = window.scrollY;
      const atTarget = Math.abs(y - targetTop) < 2;
      const stopped = y === lastY;
      lastY = y;
      stableFrames = stopped ? stableFrames + 1 : 0;
      if (atTarget && stableFrames >= 4) { release(); return; }
      raf = requestAnimationFrame(tick);
    };
    safety = setTimeout(release, 1500);
    window.scrollTo({ top: targetTop, behavior: "smooth" });
    raf = requestAnimationFrame(tick);
  };

  return (
    <aside className="toc" aria-label="Contents">
      <div className="toc-label mono">Contents</div>
      <ol className="toc-list">
        {items.map((it) => (
          <li key={it.id} className={"toc-item" + (active === it.id ? " is-active" : "")}>
            <a href={"#" + it.id} className="toc-link" onClick={(e) => onClick(e, it.id)}>
              <span className="toc-num mono">{it.num}</span>
              <span className="toc-text">{it.label}</span>
            </a>
          </li>
        ))}
      </ol>
    </aside>
  );
}

Object.assign(window, { LogoMark, Nav, Breadcrumb, Hero, Footer, LangSwitcher, TocSidebar, Gloss, ErrorCard, ErrorBoundary, LL_TIERS, LL_GLOSSARY, DDRAGON_VER, LL_PATCH });
