/* global React */

const BUILD_IMG = {
  "muscle-growth": "https://images.unsplash.com/photo-1574680096145-d05b474e2155?w=2400&q=80",
  hypertrophy: "https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=2400&q=80",
  "progressive-overload": "https://images.unsplash.com/photo-1517963879433-6ad2b056d712?w=2400&q=80",
  bulking: "https://images.unsplash.com/photo-1517836357463-d25dfeac3438?w=2400&q=80",
  cutting: "https://images.unsplash.com/photo-1526506118085-60ce8714f8c5?w=2400&q=80",
  "body-recomposition": "https://images.unsplash.com/photo-1605296867304-46d5465a13f1?w=2400&q=80",
  "body-composition": "https://images.unsplash.com/photo-1517344800994-80b20d62960e?w=2400&q=80",
  "physique-goals": "https://images.unsplash.com/photo-1517838277536-f5f99be501cd?w=2400&q=80",
};

const BUILD_L3 = {
  "muscle-growth": buildPage("01", "Muscle Growth", "Growth Log", "slow tissue", "Muscle growth is the patient work: enough hard training, enough food, enough recovery, and enough time for the body to answer.", ["12 guides", "Effort", "Recovery", "Time"], "Muscle is built by what you can repeat after the motivation leaves.", ["Stimulus", "Food", "Sleep", "Weeks"], [
    ["Set the stimulus", "Useful sets need enough effort to ask for change without turning every session into a contest."],
    ["Feed the week", "Food supports the adaptation, but the food details belong to the broader Fuel and Diet shelves."],
    ["Respect time", "Visible growth usually arrives late. The log has to outlast the mood."],
  ]),
  hypertrophy: buildPage("02", "Hypertrophy", "Growth Method", "sets that matter", "Hypertrophy is the training logic of growing muscle: sets, reps, effort, exercise choice, range, and fatigue managed well enough to continue.", ["12 guides", "Sets", "Reps", "Effort"], "The pump is a signal sometimes. The plan is the thing that has to survive.", ["Volume", "Effort", "Range", "Fatigue"], [
    ["Choose the target", "A growth-focused session needs to know what muscle is supposed to be doing the work."],
    ["Use enough effort", "Sets need to be challenging, but not every set needs to become theater."],
    ["Manage fatigue", "More work only helps if recovery can cash the check."],
  ]),
  "progressive-overload": buildPage("03", "Progressive Overload", "Overload Log", "one knob", "Progressive overload is how the work gets harder without getting reckless: load, reps, sets, tempo, range, rest, and cleaner control.", ["12 guides", "Load", "Reps", "Control"], "Progress is usually one knob, changed on purpose.", ["Load", "Reps", "Sets", "Range", "Tempo"], [
    ["Pick one knob", "Changing everything at once makes it hard to know what actually worked."],
    ["Keep the rep honest", "More weight with worse movement is not always progress."],
    ["Let recovery vote", "The body adapts between sessions, not only during the hard part."],
  ]),
  bulking: buildPage("04", "Bulking", "Gain Phase", "planned gain", "Bulking is a gaining phase, not a permission slip to stop paying attention. This page keeps the idea honest and the tradeoffs visible.", ["12 guides", "Gain", "Training", "Tradeoffs"], "A gain phase should have a reason, a rhythm, and an exit.", ["Reason", "Rate", "Training", "Exit"], [
    ["Know the reason", "A bulk makes the most sense when more body weight supports a clear training goal."],
    ["Watch the rate", "Faster is not automatically better, especially when the goal is useful muscle."],
    ["Keep the exit visible", "A phase should not turn into a permanent fog."],
  ]),
  cutting: buildPage("05", "Cutting", "Cut Phase", "careful reduction", "Cutting is a fat-loss phase with training still in the picture. This page keeps it careful, sane, and clear about the recovery cost.", ["12 guides", "Deficit", "Training", "Recovery"], "A cut that breaks training, mood, or health is telling you something.", ["Deficit", "Strength", "Recovery", "Exit"], [
    ["Protect the floor", "Training, sleep, mood, and energy are not side notes during a cut."],
    ["Keep it temporary", "A cut is a phase. It should not become the only way to feel in control."],
    ["Ask early", "Medical history, medication, disordered eating history, or real anxiety around food changes the next step."],
  ]),
  "body-recomposition": buildPage("06", "Body Recomposition", "Recomp Notebook", "two-way change", "Body recomposition is the hope of gaining muscle and losing fat at the same time. It can happen, but it needs honest expectations.", ["12 guides", "Muscle", "Fat Loss", "Patience"], "Recomp asks for patience because the win is often quiet before it is visible.", ["Strength", "Protein", "Time", "Signals"], [
    ["Watch more than weight", "Scale weight can stay still while strength, measurements, photos, or clothes change."],
    ["Match the candidate", "Beginners, returners, and people with room to improve basics often have the cleanest runway."],
    ["Keep expectations sober", "Two goals moving at once usually means slower visible feedback."],
  ]),
  "body-composition": buildPage("07", "Body Composition", "Measurement Room", "read the signals", "Body composition is measurement literacy: scale, photos, tape, clothes, strength, water swings, timelines, and not over-reading noise.", ["12 guides", "Scale", "Photos", "Timelines"], "Measurements are useful when they inform the work. They are dangerous when they become the room.", ["Scale", "Tape", "Photos", "Strength", "Clothes"], [
    ["Use several signals", "No single measure deserves the whole story."],
    ["Expect noise", "Water, salt, stress, sleep, and training can blur short-term feedback."],
    ["Protect the person", "If measurement makes life smaller or harsher, the measurement system needs to change."],
  ]),
  "physique-goals": buildPage("08", "Physique Goals", "Goal Board", "aesthetic aim", "Physique goals are aesthetic goals discussed honestly: genetics, proportions, comparison, training choices, and keeping the goal humane.", ["12 guides", "Aesthetics", "Genetics", "Comparison"], "A good physique goal should guide training without turning the body into an enemy.", ["Shape", "Genetics", "Comparison", "Standards"], [
    ["Name the controllable", "Training can influence muscle, posture, skill, and presentation. It cannot rewrite genetics."],
    ["Watch comparison", "Someone else's body is a poor coach for your week."],
    ["Keep the life intact", "The goal has to leave room for food, people, rest, and a normal mind."],
  ]),
};

function buildPage(n, title, label, accent, lede, meta, quote, marks, checks) {
  return { n, title, label, accent, lede, meta, quote, marks, checks, tabs: buildTabs(), library: buildLibrary(title) };
}

function buildTabs() {
  return [{ id: "start", nm: "Start", ct: 4 }, { id: "progress", nm: "Progress", ct: 4 }, { id: "checks", nm: "Checks", ct: 4 }];
}

function buildLibrary(title) {
  const lower = title.toLowerCase();
  return {
    start: [
      ["01", `How to start with ${lower}.`, `A plain first pass at ${lower} without turning the goal into noise.`, "Start", "5 min"],
      ["02", `How to know what ${lower} is asking from you.`, "Time, effort, recovery, patience, and the part people skip.", "Ask", "6 min"],
      ["03", `How to set a sane ${lower} goal.`, "Specific enough to train for, loose enough to stay human.", "Goal", "5 min"],
      ["04", `How to avoid rushing ${lower}.`, "Why speed is usually the promise that makes the plan worse.", "Pace", "5 min"],
    ],
    progress: [
      ["05", `How to track ${lower} without over-reading it.`, "Signals, noise, short timelines, and what deserves attention.", "Track", "6 min"],
      ["06", `How to adjust training for ${lower}.`, "A practical look at the training lever without rewriting the whole week.", "Training", "6 min"],
      ["07", `How to use recovery for ${lower}.`, "Sleep, rest days, fatigue, and why adaptation needs space.", "Recovery", "5 min"],
      ["08", `How to keep ${lower} moving when progress slows.`, "The pause, the review, and the small change that beats panic.", "Plateau", "6 min"],
    ],
    checks: [
      ["09", `How to tell if ${lower} is becoming pressure.`, "When the goal starts taking up too much room.", "Pressure", "5 min"],
      ["10", `How to compare ${lower} advice online.`, "Promises, timelines, bodies, lighting, and the missing context.", "Advice", "5 min"],
      ["11", `How to talk to a coach or clinician about ${lower}.`, "Questions for personal risk, pain, medical history, or food anxiety.", "Ask", "6 min"],
      ["12", `How to decide if ${lower} still fits.`, "A slower review before doubling down or walking away.", "Review", "5 min"],
    ],
  };
}

const buildPageKey = window.BUILD_L3_PAGE || "muscle-growth";
const BUILD_PAGE = BUILD_L3[buildPageKey] || BUILD_L3["muscle-growth"];
const BUILD_BASE = `/en/fitness/build/${buildPageKey}/`;
const BUILD_SLUG = (title) => window.howToArticleSlug(BUILD_BASE, title);
const useBuildArticles = window.useHubArticles || ((slugs) => ({
  articles: slugs.map((slug) => ({ slug, status: "stub", title: null })),
}));

function buildFallbackArticle(article, row) {
  if (article && article.status === "published") return article;
  return { ...(article || {}), status: "stub", title: row?.[1] || null, meta_description: row?.[2] || "" };
}

function BuildLastWord({ text }) {
  const words = text.split(" ");
  return <React.Fragment>{words.slice(0, -1).join(" ")} <span>{words.slice(-1)}</span></React.Fragment>;
}

function BuildL3Header() {
  return (
    <header className="header">
      <div className="header-inner">
        <a className="logo" href="/en/">
          How To<span className="ampersand">:</span> <span style={{fontStyle:"italic"}}>Health</span> <span className="amp-roman">&amp;</span> <span style={{fontStyle:"italic"}}>Fitness</span>
          <small>The How To Co. - Edition 08</small>
        </a>
        <nav className="nav">
          <a href="/en/">Home</a>
          <a href="/en/health/">Health</a>
          <a href="/en/fitness/" className="active">Fitness</a>
          <a href="/en/#program">This Week</a>
          <a href="/en/#contributors">Contributors</a>
        </nav>
        <div className="header-right"><span>Search</span><span className="pill">Saved - 04</span></div>
      </div>
    </header>
  );
}
window.BuildL3Header = BuildL3Header;

function BuildL3Crumb() {
  return (
    <div className="tcrumb">
      <div className="tcrumb-inner">
        <div className="tcrumb-trail">
          <a href="/en/">How To: Health &amp; Fitness</a><span className="sep">/</span>
          <a href="/en/fitness/">Fitness</a><span className="sep">/</span>
          <a href="/en/fitness/build/">Build</a><span className="sep">/</span>
          <span className="here">{BUILD_PAGE.title}</span>
        </div>
        <div>Fitness - Build - {BUILD_PAGE.title}</div>
      </div>
    </div>
  );
}
window.BuildL3Crumb = BuildL3Crumb;

function BuildL3Hero() {
  return (
    <section className="build-log-hero">
      <div className="build-log-img"><img src={BUILD_IMG[buildPageKey] || BUILD_IMG["muscle-growth"]} alt={`${BUILD_PAGE.title} build guide image`} /></div>
      <div className="build-log-inner">
        <div>
          <div className="build-log-label">Build - {BUILD_PAGE.label}</div>
          <h1><BuildLastWord text={BUILD_PAGE.title} /></h1>
          <p>{BUILD_PAGE.lede}</p>
          <div className="build-log-meta">{BUILD_PAGE.meta.map((item) => <span key={item}>{item}</span>)}</div>
        </div>
        <aside>
          <span>No. {BUILD_PAGE.n}</span>
          <blockquote>{BUILD_PAGE.quote}</blockquote>
        </aside>
      </div>
    </section>
  );
}
window.BuildL3Hero = BuildL3Hero;

function BuildL3Workshop() {
  return (
    <section className="build-workshop">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 01</div>
          <h2 className="title">The working <span className="display italic" style={{color:"var(--accent)"}}>log.</span></h2>
          <div className="meta">What changes<br/>what stays slow</div>
        </div>
        <div className="build-workshop-grid">
          <div className="build-log-word">{BUILD_PAGE.accent}</div>
          <div className="build-log-checks">
            {BUILD_PAGE.checks.map((check, index) => (
              <article key={check[0]}>
                <span>{String(index + 1).padStart(2, "0")}</span>
                <div><h3>{check[0]}</h3><p>{check[1]}</p></div>
              </article>
            ))}
          </div>
        </div>
        <div className="build-log-marks">{BUILD_PAGE.marks.map((mark) => <span key={mark}>{mark}</span>)}</div>
      </div>
    </section>
  );
}
window.BuildL3Workshop = BuildL3Workshop;

function BuildL3Library() {
  const [tab, setTab] = React.useState(BUILD_PAGE.tabs[0].id);
  const rows = BUILD_PAGE.library[tab] || [];
  const slugs = React.useMemo(() => rows.map((row) => BUILD_SLUG(row[1])), [tab]);
  const { articles } = useBuildArticles(slugs);
  const total = BUILD_PAGE.tabs.reduce((sum, item) => sum + item.ct, 0);
  return (
    <section className="wlib build-log-library" id="library">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 02</div>
          <h2 className="title">Guide <span className="display italic" style={{color:"var(--accent)"}}>shelf.</span></h2>
          <div className="meta">{total} build guides<br/>curated by use</div>
        </div>
        <div className="wlib-tabs" role="tablist" aria-label={`${BUILD_PAGE.title} guide sections`}>
          {BUILD_PAGE.tabs.map((item) => (
            <button key={item.id} className={`wlib-tab ${tab === item.id ? "active" : ""}`} onClick={() => setTab(item.id)} type="button">
              {item.nm}<span className="ct">{item.ct}</span>
            </button>
          ))}
        </div>
        <div className="wlib-list">
          {articles.map((article, index) => (
            <FitnessArticleCard key={article.slug} article={buildFallbackArticle(article, rows[index])} rank={rows[index][0]} tag={rows[index][3]} time={rows[index][4]} variant="library" />
          ))}
        </div>
      </div>
    </section>
  );
}
window.BuildL3Library = BuildL3Library;

function BuildL3Start() {
  return (
    <section className="fstart build-log-start">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 03</div>
          <h2 className="title">Keep building <span className="display italic" style={{color:"var(--accent)"}}>slowly.</span></h2>
          <div className="meta">Eight rooms<br/>same goal shelf</div>
        </div>
        <div className="fstart-grid">
          {Object.entries(BUILD_L3).filter(([slug]) => slug !== buildPageKey).slice(0, 4).map(([slug, page]) => (
            <a key={slug} className="fstart-tile" href={`/en/fitness/build/${slug}/`}>
              <div className="s-num"><span>{page.title}</span><span className="arr">-&gt;</span></div>
              <h4>Open the <span className="it">{page.label.toLowerCase()}.</span></h4>
              <p>{page.lede}</p>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}
window.BuildL3Start = BuildL3Start;

function BuildL3Footer() {
  const SharedFooter = window.HowToFooter;
  return SharedFooter ? <SharedFooter screenLabel="07 Footer" /> : null;
}
window.BuildL3Footer = BuildL3Footer;

window.BUILD_L3 = BUILD_L3;
