/* global React */

const RECOVER_IMG = {
  "rest-days": "https://images.unsplash.com/photo-1519823551278-64ac92734fb1?w=2400&q=80",
  "sleep-for-recovery": "https://images.unsplash.com/photo-1511295742362-92c96b1cf484?w=2400&q=80",
  soreness: "https://images.unsplash.com/photo-1518611012118-696072aa579a?w=2400&q=80",
  deloads: "https://images.unsplash.com/photo-1517344884509-a0c97ec11bcc?w=2400&q=80",
  "foam-rolling-soft-tissue": "https://images.unsplash.com/photo-1599058917212-d750089bc07e?w=2400&q=80",
  "injury-prevention": "https://images.unsplash.com/photo-1576678927484-cc907957088c?w=2400&q=80",
  "active-recovery": "https://images.unsplash.com/photo-1515377905703-c4788e51af15?w=2400&q=80",
  "return-to-training": "https://images.unsplash.com/photo-1522898467493-49726bf28798?w=2400&q=80",
};

const RECOVER_L3 = {
  "rest-days": recoverPage("01", "Rest Days", "Rest Field Notes", "do less on purpose", "Rest days are not empty days. They are where hard work gets room to land, soreness gets context, and the next useful session stays possible.", ["12 guides", "Easy days", "Guilt", "Readiness"], "Rest is a training variable, not an apology.", ["Stop", "Notice", "Sleep", "Walk", "Return"], [
    ["Give rest a job", "A rest day can reduce fatigue, restore attention, and keep the next session from becoming a negotiation."],
    ["Drop the guilt", "Doing less is not the same as quitting. Sometimes it is the most disciplined part of the week."],
    ["Keep it simple", "A walk, a nap, a normal meal, and a quieter evening often do more than a complicated recovery ritual."],
  ]),
  "sleep-for-recovery": recoverPage("02", "Sleep for Recovery", "Sleep Recovery", "the baseline lever", "Sleep is the recovery tool most people skip because it does not feel like a tool. This page keeps it tied to training, fatigue, and readiness.", ["12 guides", "Consistency", "Late workouts", "Caffeine"], "Recovery gets expensive when sleep is missing.", ["Schedule", "Caffeine", "Late Session", "Nap", "Travel"], [
    ["Start with consistency", "The body likes a repeatable sleep window more than a perfect bedtime that only happens twice."],
    ["Watch late inputs", "Late caffeine, late screens, late stress, and late hard sessions can all change the recovery bill."],
    ["Stay in the fitness lane", "This is not a medical sleep page. It is the training-side reminder that sleep changes what the body can absorb."],
  ]),
  soreness: recoverPage("03", "Soreness", "Soreness Notes", "information not score", "Soreness can be normal, useful, annoying, or a warning to slow down. It is information, not proof that a workout mattered.", ["12 guides", "DOMS", "Signals", "Back off"], "Soreness is a message. Pain changes the conversation.", ["DOMS", "New Work", "Easy Move", "Pain", "Back Off"], [
    ["Separate soreness from pain", "Normal muscle soreness and sharp, worsening, or movement-changing pain are not the same thing."],
    ["Notice what changed", "New movements, more volume, more range, and longer breaks from training can all make soreness louder."],
    ["Do not chase it", "A useful workout does not need to make stairs dramatic for three days."],
  ]),
  deloads: recoverPage("04", "Deloads", "Lighter Week", "pull back to continue", "A deload is a planned reduction in training stress. It is not laziness. It is a way to keep the work from outrunning recovery.", ["12 guides", "Volume", "Intensity", "Fatigue"], "A lighter week can be the reason the harder weeks keep working.", ["Less Load", "Less Volume", "More Sleep", "Technique", "Return"], [
    ["Lower one thing", "A deload can reduce load, sets, intensity, or complexity without abandoning the habit."],
    ["Read the signs", "Flat performance, cranky joints, poor sleep, and low motivation can all belong in the review."],
    ["Come back clearer", "The point is not to lose momentum. The point is to stop fatigue from steering the plan."],
  ]),
  "foam-rolling-soft-tissue": recoverPage("05", "Foam Rolling & Soft Tissue", "Soft Tissue Shelf", "relief without magic", "Foam rolling, massage tools, and soft-tissue work can help some people feel better. They are not magic, and they do not replace care when pain is real.", ["12 guides", "Foam rolling", "Massage tools", "Relief"], "Feeling better can count without pretending the tool fixed everything.", ["Roll", "Breathe", "Move", "Notice", "Ask"], [
    ["Use it for relief", "Temporary relief can be useful when it helps you move easier and calm the system down."],
    ["Avoid magic claims", "A tool can change sensation without solving the underlying training, load, sleep, or pain issue."],
    ["Know when to stop", "Numbness, sharp pain, swelling, or worsening symptoms deserve a qualified professional, not more pressure."],
  ]),
  "injury-prevention": recoverPage("06", "Injury Prevention", "Risk Literacy", "smarter boundaries", "Injury prevention is load management, warm-ups, technique, pain literacy, and the humility to stop before a small problem owns the month.", ["12 guides", "Load", "Technique", "Pain literacy"], "The bravest training choice is sometimes stopping early.", ["Warm Up", "Load", "Technique", "Pain", "Ask"], [
    ["Manage load", "A body can tolerate a lot when the increase is gradual and the recovery has room."],
    ["Respect pain", "Sharp, worsening, unstable, numb, or movement-changing pain is not a mindset problem."],
    ["Ask sooner", "Getting help early can keep a small issue from becoming the whole season."],
  ]),
  "active-recovery": recoverPage("07", "Active Recovery", "Easy Movement", "easy still means easy", "Active recovery is easy movement that supports the week without sneaking in another workout. Walking, gentle cycling, mobility, and light sessions all have to stay honest.", ["12 guides", "Walking", "Mobility", "Easy cardio"], "Active recovery stops being recovery when it starts trying to prove something.", ["Walk", "Cycle", "Mobility", "Light", "Stop"], [
    ["Keep it easy", "The work should leave you feeling better, not like you accidentally trained again."],
    ["Match the fatigue", "Some days want a walk. Some days want nothing. The body gets a vote."],
    ["Use simple movement", "Easy movement can reduce stiffness and help the day feel less locked up."],
  ]),
  "return-to-training": recoverPage("08", "Return to Training", "Reentry Plan", "come back sensibly", "Coming back after illness, travel, time off, soreness, or a small setback should be boring. This page is about sensible re-entry and knowing when to ask for help.", ["12 guides", "Time off", "Illness", "Reentry"], "The comeback works better when the first week does not try to repay every missed session.", ["Start Small", "Check Pain", "Lower Load", "Watch Energy", "Build Back"], [
    ["Shrink the first step", "The first session back should confirm readiness, not test your entire identity."],
    ["Avoid repayment training", "Missed workouts do not need to be paid back in one dramatic week."],
    ["Know the boundary", "Pain, illness complications, post-injury questions, or medical uncertainty belong with a qualified professional."],
  ]),
};

function recoverPage(n, title, label, accent, lede, meta, quote, marks, checks) {
  return { n, title, label, accent, lede, meta, quote, marks, checks, tabs: recoverTabs(), library: recoverLibrary(title) };
}

function recoverTabs() {
  return [{ id: "start", nm: "Start", ct: 4 }, { id: "signals", nm: "Signals", ct: 4 }, { id: "return", nm: "Return", ct: 4 }];
}

function recoverLibrary(title) {
  const lower = title.toLowerCase();
  return {
    start: [
      ["01", `How to start with ${lower}.`, `A plain first pass at ${lower} without making recovery complicated.`, "Start", "5 min"],
      ["02", `How to know when ${lower} matters.`, "The signs that the week is asking for more recovery attention.", "Signal", "5 min"],
      ["03", `How to keep ${lower} simple.`, "A few quiet defaults that help without turning recovery into a second sport.", "Simple", "4 min"],
      ["04", `How to avoid overdoing ${lower}.`, "When the recovery tool starts becoming another source of pressure.", "Restraint", "5 min"],
    ],
    signals: [
      ["05", `How to read soreness around ${lower}.`, "Normal soreness, new work, and when the signal needs more care.", "Soreness", "5 min"],
      ["06", `How to adjust training around ${lower}.`, "Lowering the dose without losing the habit.", "Adjust", "5 min"],
      ["07", `How to tell when easy should stay easy.`, "Recovery work should not quietly become more training.", "Easy", "4 min"],
      ["08", `How to know when to ask for help.`, "Pain, swelling, numbness, instability, medical context, and other caution flags.", "Ask", "6 min"],
    ],
    return: [
      ["09", `How to come back after a rough week.`, "A re-entry plan that does not try to repay missed sessions.", "Reentry", "5 min"],
      ["10", `How to use ${lower} with sleep and food.`, "The ordinary recovery base before the smaller tools.", "Base", "5 min"],
      ["11", `How to keep ${lower} from becoming avoidance.`, "The difference between wise restraint and drifting away from training.", "Balance", "5 min"],
      ["12", `How to decide if the plan is working.`, "Energy, readiness, pain, mood, performance, and what changed over time.", "Review", "5 min"],
    ],
  };
}

const recoverPageKey = window.RECOVER_L3_PAGE || "rest-days";
const RECOVER_PAGE = RECOVER_L3[recoverPageKey] || RECOVER_L3["rest-days"];
const RECOVER_BASE = `/en/fitness/recover/${recoverPageKey}/`;
const RECOVER_SLUG = (title) => window.howToArticleSlug(RECOVER_BASE, title);
const useRecoverArticles = window.useHubArticles || ((slugs) => ({
  articles: slugs.map((slug) => ({ slug, status: "stub", title: null })),
}));

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

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

function RecoverL3Header() {
  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.RecoverL3Header = RecoverL3Header;

function RecoverL3Crumb() {
  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/recover/">Recover</a><span className="sep">/</span>
          <span className="here">{RECOVER_PAGE.title}</span>
        </div>
        <div>Fitness - Recover - {RECOVER_PAGE.title}</div>
      </div>
    </div>
  );
}
window.RecoverL3Crumb = RecoverL3Crumb;

function RecoverL3Hero() {
  return (
    <section className="recover-manual-hero">
      <div className="recover-manual-img"><img src={RECOVER_IMG[recoverPageKey] || RECOVER_IMG["rest-days"]} alt={`${RECOVER_PAGE.title} recovery guide image`} /></div>
      <div className="recover-manual-inner">
        <div>
          <div className="recover-manual-label">Recover - {RECOVER_PAGE.label}</div>
          <h1><RecoverLastWord text={RECOVER_PAGE.title} /></h1>
          <p>{RECOVER_PAGE.lede}</p>
          <div className="recover-manual-meta">{RECOVER_PAGE.meta.map((item) => <span key={item}>{item}</span>)}</div>
        </div>
        <aside>
          <span>No. {RECOVER_PAGE.n}</span>
          <blockquote>{RECOVER_PAGE.quote}</blockquote>
        </aside>
      </div>
    </section>
  );
}
window.RecoverL3Hero = RecoverL3Hero;

function RecoverL3Manual() {
  return (
    <section className="recover-manual">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 01</div>
          <h2 className="title">Recovery <span className="display italic" style={{color:"var(--accent)"}}>manual.</span></h2>
          <div className="meta">Calm signals<br/>clear boundaries</div>
        </div>
        <div className="recover-manual-grid">
          <div className="recover-manual-word">{RECOVER_PAGE.accent}</div>
          <div className="recover-manual-checks">
            {RECOVER_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="recover-manual-marks">{RECOVER_PAGE.marks.map((mark) => <span key={mark}>{mark}</span>)}</div>
      </div>
    </section>
  );
}
window.RecoverL3Manual = RecoverL3Manual;

function RecoverL3Library() {
  const [tab, setTab] = React.useState(RECOVER_PAGE.tabs[0].id);
  const rows = RECOVER_PAGE.library[tab] || [];
  const slugs = React.useMemo(() => rows.map((row) => RECOVER_SLUG(row[1])), [tab]);
  const { articles } = useRecoverArticles(slugs);
  const total = RECOVER_PAGE.tabs.reduce((sum, item) => sum + item.ct, 0);
  return (
    <section className="wlib recover-manual-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} recovery guides<br/>curated by signal</div>
        </div>
        <div className="wlib-tabs" role="tablist" aria-label={`${RECOVER_PAGE.title} guide sections`}>
          {RECOVER_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={recoverFallbackArticle(article, rows[index])} rank={rows[index][0]} tag={rows[index][3]} time={rows[index][4]} variant="library" />
          ))}
        </div>
      </div>
    </section>
  );
}
window.RecoverL3Library = RecoverL3Library;

function RecoverL3Start() {
  return (
    <section className="fstart recover-manual-start">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 03</div>
          <h2 className="title">Keep recovering <span className="display italic" style={{color:"var(--accent)"}}>on purpose.</span></h2>
          <div className="meta">Eight rooms<br/>one calmer shelf</div>
        </div>
        <div className="fstart-grid">
          {Object.entries(RECOVER_L3).filter(([slug]) => slug !== recoverPageKey).slice(0, 4).map(([slug, page]) => (
            <a key={slug} className="fstart-tile" href={`/en/fitness/recover/${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.RecoverL3Start = RecoverL3Start;

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

window.RECOVER_L3 = RECOVER_L3;
