/* global React */

const DIET_IMG = {
  frameworks: "https://images.unsplash.com/photo-1490645935967-10de6ba17061?w=2400&q=80",
  calories: "https://images.unsplash.com/photo-1556740758-90de374c12ad?w=2400&q=80",
  macros: "https://images.unsplash.com/photo-1498837167922-ddd27525d352?w=2400&q=80",
  "meal-planning": "https://images.unsplash.com/photo-1543352634-873e17d2a088?w=2400&q=80",
  "plant-based": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?w=2400&q=80",
  fasting: "https://images.unsplash.com/photo-1504754524776-8f4f37790ca0?w=2400&q=80",
  "popular-diet-types": "https://images.unsplash.com/photo-1466637574441-749b8f19452f?w=2400&q=80",
};

const DIET_L3 = {
  frameworks: dietPage("01", "Frameworks", "Diet Frameworks", "rules and tradeoffs", "Eating frameworks are maps, not verdicts. This chapter looks at why people choose rules, what the rules simplify, and what they quietly make harder.", ["12 guides", "Rules", "Tradeoffs", "Fit"], "A framework should make the week clearer, not make the person smaller.", [
    ["The idea", "A framework gives eating a shape. It reduces decisions by naming a few priorities and letting the rest of the day organize around them."],
    ["The tradeoff", "Every framework edits reality. It can make one choice easier while making flexibility, social eating, or training energy harder."],
    ["Where it breaks", "The problem usually starts when the framework stops being a tool and starts becoming a test of character."],
    ["Use it well", "Read what the framework asks from your real life before you ask your real life to obey it."],
  ], ["Method", "Cost", "Flexibility", "Repeatability"], [
    ["Clarify the rule", "Name the actual rule, not the marketing promise."],
    ["Watch the cost", "Look for the part of life the method makes harder."],
    ["Keep an exit", "A good framework can be adjusted without feeling like failure."],
  ]),
  calories: dietPage("02", "Calories", "Energy Balance", "the numbers underneath", "Calories are a way of describing energy, not a personality score. This chapter keeps the concept useful without turning eating into a courtroom.", ["12 guides", "Energy", "Portions", "Context"], "The number can explain the pattern. It should not become the whole story.", [
    ["The idea", "Calories help explain why body weight changes over time. They are a measurement of energy, not a moral category."],
    ["The tradeoff", "The number can clarify patterns, but it can also crowd out hunger, satisfaction, training needs, and ordinary judgment."],
    ["Where it breaks", "It breaks when precision becomes the goal and the person disappears behind the math."],
    ["Use it well", "Use calories as a temporary lens when you need clarity, then bring the rest of life back into the frame."],
  ], ["Energy", "Portion", "Pattern", "Pressure"], [
    ["Use the wide lens", "Look at weeks and patterns instead of treating one meal like evidence."],
    ["Keep the body present", "Hunger, energy, sleep, training, and mood still count."],
    ["Avoid fake precision", "Most food math is an estimate. Treat it like one."],
  ]),
  macros: dietPage("03", "Macros", "Protein, Carbs, Fat", "what each lever changes", "Macros are the big levers inside the plate. This chapter explains what protein, carbs, and fat are doing before they become a tracking ritual.", ["12 guides", "Protein", "Carbs", "Fat"], "Macros are useful when they explain the meal, not when they replace it.", [
    ["The idea", "Macros describe the major jobs food can do: repair, energy, satisfaction, and structure."],
    ["The tradeoff", "Tracking macros can sharpen awareness, but it can also make every meal feel like a puzzle."],
    ["Where it breaks", "It breaks when the numbers look right but the eating pattern feels brittle, joyless, or impossible to repeat."],
    ["Use it well", "Start with the plate. Use the numbers only when the plate stops making sense."],
  ], ["Protein", "Carbs", "Fat", "Fit"], [
    ["Ask the job", "What does this meal need to do for the day ahead?"],
    ["Respect training", "Training days often need enough protein, enough carbs, and enough total food."],
    ["Keep meals normal", "A good macro approach should still look like food."],
  ]),
  "meal-planning": dietPage("04", "Meal Planning", "Planning Without Prison", "fewer food decisions", "Meal planning is not a performance of control. This chapter is about repeatable defaults, flexible backup plans, and eating that survives normal life.", ["12 guides", "Defaults", "Flexibility", "Weeks"], "The point is not a perfect plan. The point is fewer decisions when the day gets loud.", [
    ["The idea", "A useful meal plan removes friction from the week. It gives the next meal somewhere to land."],
    ["The tradeoff", "Too much planning can make food feel fragile. Too little planning makes every meal a new negotiation."],
    ["Where it breaks", "It breaks when the plan only works for the imaginary version of your week."],
    ["Use it well", "Plan anchors, not scripts. Leave enough room for appetite, people, and timing."],
  ], ["Anchor", "Fallback", "Leftovers", "Room"], [
    ["Pick anchors", "Choose repeatable meals that carry the week."],
    ["Build fallbacks", "Have a late-day option that does not need inspiration."],
    ["Leave room", "A plan should bend before it breaks."],
  ]),
  "plant-based": dietPage("05", "Plant-Based", "Mostly Plants", "values and practicality", "Plant-based eating can be an ethic, a preference, a health pattern, or a practical default. This chapter keeps the philosophy honest and the week livable.", ["12 guides", "Plants", "Protein", "Practicality"], "Mostly plants works best when it is satisfying enough to keep.", [
    ["The idea", "Plant-based eating shifts the center of the plate toward plants. It can be strict, flexible, values-led, or simply practical."],
    ["The tradeoff", "It can add fiber, variety, and intention. It can also require more planning around protein, convenience, restaurants, and family meals."],
    ["Where it breaks", "It breaks when the label gets more attention than the meals, or when the food is technically compliant but not satisfying."],
    ["Use it well", "Make protein, pleasure, and convenience part of the philosophy from the beginning."],
  ], ["Plants", "Protein", "Convenience", "Values"], [
    ["Name the version", "Vegan, vegetarian, mostly plants, or plant-forward are not the same week."],
    ["Plan protein", "Protein deserves a real plan, not wishful thinking."],
    ["Keep pleasure", "Food still has to taste like something you want to eat."],
  ]),
  fasting: dietPage("06", "Fasting", "Time Windows", "structure and hunger", "Fasting deserves its own chapter because it changes the day before it changes the plate. This page looks at structure, hunger, training, safety, and pressure.", ["12 guides", "Time", "Hunger", "Caution"], "Fasting is a structure. It is not proof that you are disciplined.", [
    ["The idea", "Fasting narrows the eating window. For some people, that lowers decision fatigue. For others, it raises pressure."],
    ["The tradeoff", "The clock can simplify eating, but it can also collide with training, sleep, family meals, medication, or hunger cues."],
    ["Where it breaks", "It breaks when hunger becomes a contest, or when a time rule makes the rest of health harder."],
    ["Use it well", "Treat fasting as an optional structure, not a virtue. Ask a qualified professional first if food rules carry medical or emotional risk."],
  ], ["Window", "Training", "Hunger", "Caution"], [
    ["Check the reason", "Know whether you want structure, simplicity, appetite control, or something else."],
    ["Watch training", "Hard sessions may not pair well with a rigid window."],
    ["Protect safety", "Medical conditions, pregnancy, medication, or a history of disordered eating change the conversation."],
  ]),
  "popular-diet-types": dietPage("07", "Popular Diet Types", "The Big Comparison", "labels, promises, and costs", "High-protein, Mediterranean, keto, low-carb, paleo, whole-food, anti-inflammatory, and clean eating all make different promises. This hub reads the promise against the tradeoff.", ["16 guides", "Comparison", "Labels", "Tradeoffs"], "A diet label is only useful after you know what it asks from your week.", [
    ["The idea", "Popular diet types are shorthand. They help people find a starting point, a community, or a rule set."],
    ["The tradeoff", "The shorthand can hide major differences: strictness, cost, food access, training energy, social friction, and medical fit."],
    ["Where it breaks", "It breaks when the label becomes an identity and every normal exception starts to feel like a confession."],
    ["Use it well", "Compare the rule, the cost, the evidence, the pressure, and the way it fits an ordinary week."],
  ], ["High Protein", "Mediterranean", "Keto", "Low Carb", "Paleo", "Whole Food", "Anti-Inflammatory", "Clean Eating"], [
    ["Read the promise", "What does this diet claim to make easier?"],
    ["Read the restriction", "What does it remove, limit, or make socially expensive?"],
    ["Read the fit", "Does it match your training, health needs, budget, and actual meals?"],
  ], true),
};

function dietPage(n, title, label, accent, lede, meta, quote, chapters, marks, checks, comparison = false) {
  return { n, title, label, accent, lede, meta, quote, chapters, marks, checks, comparison, tabs: dietTabs(title, comparison), library: dietLibrary(title, comparison) };
}

function dietTabs(title, comparison) {
  return comparison
    ? [{ id: "types", nm: "Types", ct: 6 }, { id: "tradeoffs", nm: "Tradeoffs", ct: 5 }, { id: "fit", nm: "Fit", ct: 5 }]
    : [{ id: "idea", nm: "Idea", ct: 4 }, { id: "tradeoffs", nm: "Tradeoffs", ct: 4 }, { id: "practice", nm: "Practice", ct: 4 }];
}

function dietLibrary(title, comparison) {
  const lower = title.toLowerCase();
  if (comparison) {
    return {
      types: [
        ["01", "How to compare popular diet types.", "A plain way to read labels, promises, rules, and costs.", "Compare", "8 min"],
        ["02", "How to understand high-protein diets.", "What the emphasis helps, what it does not solve, and where it can get narrow.", "High protein", "7 min"],
        ["03", "How to understand Mediterranean-style eating.", "The pattern, the appeal, and the gap between tradition and branding.", "Mediterranean", "7 min"],
        ["04", "How to understand keto.", "The carb restriction, the promise, the friction, and the caution flags.", "Keto", "8 min"],
        ["05", "How to understand low-carb eating.", "A broader label than keto, with its own useful questions.", "Low carb", "6 min"],
        ["06", "How to understand paleo.", "The premise, the modern reality, and the practical tradeoffs.", "Paleo", "6 min"],
      ],
      tradeoffs: [
        ["07", "How to read the restriction in any diet.", "What the diet limits, what that changes, and what it costs.", "Restriction", "6 min"],
        ["08", "How to spot moral language around food.", "Clean, cheat, good, bad, and the words that make eating smaller.", "Language", "5 min"],
        ["09", "How to judge a diet's social cost.", "Restaurants, family meals, travel, and the parts no macro chart sees.", "Social", "6 min"],
        ["10", "How to judge a diet's training fit.", "Energy, recovery, appetite, and hard sessions under stricter rules.", "Training", "6 min"],
        ["11", "How to avoid making a diet your identity.", "A label can help until it starts answering questions it should not answer.", "Identity", "5 min"],
      ],
      fit: [
        ["12", "How to choose a diet type without rushing.", "A slower checklist before adopting a public label.", "Choice", "6 min"],
        ["13", "How to compare whole-food approaches.", "Useful defaults, vague claims, and the difference between pattern and purity.", "Whole food", "6 min"],
        ["14", "How to understand anti-inflammatory diet claims.", "What the phrase can mean and why medical context matters.", "Claims", "7 min"],
        ["15", "How to leave a diet that no longer fits.", "Changing course without turning the previous choice into failure.", "Exit", "5 min"],
        ["16", "How to ask a professional about diet types.", "Questions for clinicians, dietitians, medication, symptoms, and risk.", "Ask", "6 min"],
      ],
    };
  }
  return {
    idea: [
      ["01", `How to understand ${lower}.`, `The central idea behind ${lower}, without the sales pitch.`, "Idea", "6 min"],
      ["02", `How to know what ${lower} is trying to solve.`, "Decision fatigue, body composition, energy, identity, convenience, or control.", "Purpose", "6 min"],
      ["03", `How to read the promise behind ${lower}.`, "What sounds appealing and what still has to be true in real life.", "Promise", "5 min"],
      ["04", `How to separate the method from the marketing.`, "The useful rule is usually quieter than the headline.", "Marketing", "5 min"],
    ],
    tradeoffs: [
      ["05", `How to see the tradeoffs in ${lower}.`, "What gets easier, what gets harder, and what the method asks from your week.", "Tradeoff", "6 min"],
      ["06", `How to notice when ${lower} is becoming pressure.`, "The signs that a useful structure is starting to crowd the room.", "Pressure", "5 min"],
      ["07", `How to keep ${lower} from taking over social life.`, "Restaurants, family meals, travel, and enough flexibility to eat with people.", "Social", "5 min"],
      ["08", `How to know when ${lower} needs professional input.`, "Medical conditions, medication, pregnancy, disordered eating history, and real uncertainty.", "Caution", "6 min"],
    ],
    practice: [
      ["09", `How to try ${lower} for a normal week.`, "A small test that watches energy, mood, training, hunger, and friction.", "Test", "6 min"],
      ["10", `How to adjust ${lower} without calling it failure.`, "Changing the rule when the rule stops fitting the life.", "Adjust", "5 min"],
      ["11", `How to keep ${lower} flexible.`, "Rules that bend enough to survive ordinary days.", "Flex", "5 min"],
      ["12", `How to decide if ${lower} is worth keeping.`, "A practical review after the first stretch of real use.", "Review", "5 min"],
    ],
  };
}

const dietPageKey = window.DIET_L3_PAGE || "frameworks";
const DIET_PAGE = DIET_L3[dietPageKey] || DIET_L3.frameworks;
const DIET_BASE = `/en/fitness/diet/${dietPageKey}/`;
const DIET_SLUG = (title) => window.howToArticleSlug(DIET_BASE, title);
const useDietArticles = window.useHubArticles || ((slugs) => ({
  articles: slugs.map((slug) => ({ slug, status: "stub", title: null })),
}));

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

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

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

function DietL3Crumb() {
  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/diet/">Diet</a><span className="sep">/</span>
          <span className="here">{DIET_PAGE.title}</span>
        </div>
        <div>Fitness - Diet - {DIET_PAGE.title}</div>
      </div>
    </div>
  );
}
window.DietL3Crumb = DietL3Crumb;

function DietL3Hero() {
  return (
    <section className="diet-book-hero">
      <div className="diet-book-img"><img src={DIET_IMG[dietPageKey] || DIET_IMG.frameworks} alt={`${DIET_PAGE.title} diet guide image`} /></div>
      <div className="diet-book-inner">
        <div className="diet-book-label">Chapter {DIET_PAGE.n} - Diet</div>
        <h1><DietLastWord text={DIET_PAGE.title} /></h1>
        <p>{DIET_PAGE.lede}</p>
        <div className="diet-book-meta">{DIET_PAGE.meta.map((item) => <span key={item}>{item}</span>)}</div>
      </div>
    </section>
  );
}
window.DietL3Hero = DietL3Hero;

function DietL3Chapters() {
  return (
    <section className="diet-book-chapters">
      <div className="frame diet-book-chapter-grid">
        <aside>
          <div className="diet-book-label">{DIET_PAGE.label}</div>
          <blockquote>{DIET_PAGE.quote}</blockquote>
        </aside>
        <div className="diet-book-pages">
          {DIET_PAGE.chapters.map((chapter, index) => (
            <article key={chapter[0]}>
              <span>{String(index + 1).padStart(2, "0")}</span>
              <div><h2>{chapter[0]}</h2><p>{chapter[1]}</p></div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}
window.DietL3Chapters = DietL3Chapters;

function DietL3Lens() {
  return (
    <section className="diet-book-lens">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 02</div>
          <h2 className="title">Read the <span className="display italic" style={{color:"var(--accent)"}}>philosophy.</span></h2>
          <div className="meta">What to keep<br/>in the margin</div>
        </div>
        <div className="diet-book-spread">
          <div className="diet-book-word">{DIET_PAGE.accent}</div>
          <div className="diet-book-checks">
            {DIET_PAGE.checks.map((check) => (
              <article key={check[0]}><h3>{check[0]}</h3><p>{check[1]}</p></article>
            ))}
          </div>
        </div>
        <div className="diet-book-marks">
          {DIET_PAGE.marks.map((mark) => <span key={mark}>{mark}</span>)}
        </div>
      </div>
    </section>
  );
}
window.DietL3Lens = DietL3Lens;

function DietL3Library() {
  const [tab, setTab] = React.useState(DIET_PAGE.tabs[0].id);
  const rows = DIET_PAGE.library[tab] || [];
  const slugs = React.useMemo(() => rows.map((row) => DIET_SLUG(row[1])), [tab]);
  const { articles } = useDietArticles(slugs);
  const total = DIET_PAGE.tabs.reduce((sum, item) => sum + item.ct, 0);
  return (
    <section className="wlib diet-book-library" id="library">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 03</div>
          <h2 className="title">Guide <span className="display italic" style={{color:"var(--accent)"}}>shelf.</span></h2>
          <div className="meta">{total} philosophy guides<br/>curated by question</div>
        </div>
        <div className="wlib-tabs" role="tablist" aria-label={`${DIET_PAGE.title} guide sections`}>
          {DIET_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={dietFallbackArticle(article, rows[index])} rank={rows[index][0]} tag={rows[index][3]} time={rows[index][4]} variant="library" />
          ))}
        </div>
      </div>
    </section>
  );
}
window.DietL3Library = DietL3Library;

function DietFoodBridge() {
  return (
    <section className="diet-food-bridge">
      <div className="frame">
        <a className="diet-food-card" href="https://howtofoodedition.com/en/dietary/">
          <div>
            <div className="diet-book-label">For the food-guide side</div>
            <h2>Open the <span>Dietary</span> shelf.</h2>
          </div>
          <p>For food guides, pantry help, ingredients, recipes, and practical eating details, continue in HowTo: Food Edition.</p>
          <span>Visit Food Edition Dietary</span>
        </a>
      </div>
    </section>
  );
}
window.DietFoodBridge = DietFoodBridge;

function DietL3Start() {
  return (
    <section className="fstart diet-book-start">
      <div className="frame">
        <div className="sec-head">
          <div className="num">No. 04</div>
          <h2 className="title">Keep reading <span className="display italic" style={{color:"var(--accent)"}}>Diet.</span></h2>
          <div className="meta">Seven chapters<br/>in the same shelf</div>
        </div>
        <div className="fstart-grid">
          {Object.entries(DIET_L3).filter(([slug]) => slug !== dietPageKey).slice(0, 4).map(([slug, page]) => (
            <a key={slug} className="fstart-tile" href={`/en/fitness/diet/${slug}/`}>
              <div className="s-num"><span>{page.title}</span><span className="arr">-&gt;</span></div>
              <h4>Open <span className="it">{page.label.toLowerCase()}.</span></h4>
              <p>{page.lede}</p>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}
window.DietL3Start = DietL3Start;

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

window.DIET_L3 = DIET_L3;
