// screens/category.jsx — flexible category/hub template for many routes
const CATEGORIES = {
  '/recipes': {
    eyebrow: 'Everything we cook',
    title: 'All recipes, tested.',
    sub: '8,420 recipes — each one cooked at least three times in a real home kitchen before publishing. Filter by what you have, what you have time for, or what you’re craving.',
    chips: ['All', 'Weeknight', 'Baking', 'One-pan', 'Vegetarian', 'Air fryer', '30 min', 'Crowd-pleaser'],
    sub_links: [
      { label: 'By course',     count: '12 courses' },
      { label: 'By cuisine',    count: '34 cuisines' },
      { label: 'By technique',  count: '28 techniques' },
      { label: 'By diet',       count: '9 diets' },
    ],
    faqs: [
      { q: 'How do you test a recipe?', a: 'Every recipe is cooked at least three times by the assigned editor and one tester in a separate kitchen. We weigh — not measure — ingredients, photograph the final result unedited, and publish only when both passes succeed on the same day.' },
      { q: 'Do you accept user-submitted recipes?', a: 'Not at the moment. Every recipe on inspirecipe is developed and tested in-house by a named editor. We may open a guest-editor program in 2027.' },
      { q: 'Why don’t you have a 1,200-word headnote?', a: 'Because nobody reads them. Our editors write 60–90 word headnotes — just enough to know what the recipe is, what it tastes like, and why it’s worth making. The rest of the page is recipe.' },
    ],
  },
  '/collections': {
    eyebrow: 'Curated editorial sets',
    title: 'Collections',
    sub: 'Hand-picked recipe sets built by our editors around a single idea — a holiday, a season, a technique, a mood. Updated as the year unfolds.',
    isCollections: true,
  },
  '/cuisines': {
    eyebrow: 'Atlas of flavor',
    title: 'Cuisines of the world',
    sub: 'Local techniques, local ingredients, tested by local cooks. Pick a region to drill into.',
    isCuisines: true,
  },
  '/quick': {
    eyebrow: '30 minutes or less',
    title: 'Quick & Easy',
    sub: 'Real dinners — not assemblies — that get from fridge to plate in 30 minutes or less. Tested to actually work on a Tuesday.',
    chips: ['All', '15 min', '20 min', '30 min', 'One-pan', 'Sheet pan', 'No-cook', 'Pantry'],
    faqs: [
      { q: 'Is "30 minutes" honest?', a: 'Yes. The time on the page is the editor’s actual stopwatch from the first knife cut to the plate, including the unavoidable bits (preheating, boiling water) but not optional rest time.' },
      { q: 'Do these need a stocked pantry?', a: 'We tag the Pantry-friendly ones explicitly. Most of the rest assume olive oil, salt, pepper, garlic, lemon, and one fresh herb. We don’t consider those a "stocked pantry".' },
    ],
  },
  '/methods': {
    eyebrow: 'Learn one thing well',
    title: 'Methods',
    sub: 'Master a technique once and unlock dozens of recipes. Brown butter. Pan sauces. Reverse-sear. Lamination. Each method is a guide and a tested example recipe.',
    chips: ['All', 'Baking', 'Roasting', 'Searing', 'Braising', 'Frying', 'Fermenting', 'Pastry'],
    isMethods: true,
  },
  '/trending': {
    eyebrow: 'This week',
    title: 'Trending recipes',
    sub: 'What our readers are cooking right now, updated every Monday morning. Ranked by completed cook-throughs, not pageviews.',
    chips: ['All', 'This week', 'This month', 'Past 3 months', 'All time'],
  },
  '/new': {
    eyebrow: 'Hot off the test kitchen',
    title: 'New this week',
    sub: 'Recipes published in the last 7 days. We publish 4–6 new tested recipes a week — no more, no less.',
  },
  '/seasonal': {
    eyebrow: 'Cook the calendar',
    title: 'In season now',
    sub: 'Recipes built around what is at its peak right now in the Northern Hemisphere. Tap a locale flag to see what is in season where you live.',
    chips: ['Spring', 'Summer', 'Autumn', 'Winter'],
  },
  '/baking': {
    eyebrow: 'Weights, not cups',
    title: 'Baking',
    sub: 'Cookies, breads, cakes, pastry. Every baking recipe published in grams, tested in three ovens (gas, electric, convection), with troubleshooting notes on every page.',
    chips: ['All', 'Cookies', 'Breads', 'Cakes', 'Pastry', 'Pies & tarts', 'No-bake'],
  },
  '/one-pan': {
    eyebrow: 'Less dishes, more flavor',
    title: 'One-pan recipes',
    sub: 'Sheet-pan, skillet, Dutch oven, and slow-cooker dinners. No second pot to scrub.',
    chips: ['All', 'Sheet pan', 'Skillet', 'Dutch oven', 'Slow cooker'],
  },
  '/by-diet': {
    eyebrow: 'Filtered by what you eat',
    title: 'By diet',
    sub: 'Vegetarian. Vegan. Gluten-free. Dairy-free. Pescatarian. Low-carb. High-protein. Every recipe filtered honestly — not by removing an ingredient, but by testing the modified version.',
    chips: ['Vegetarian', 'Vegan', 'Gluten-free', 'Dairy-free', 'Pescatarian', 'Low-carb', 'High-protein'],
  },
  '/by-ingredient': {
    eyebrow: 'Use what you have',
    title: 'By ingredient',
    sub: 'Open the fridge, pick the thing about to turn, and find a recipe. Browse by hero ingredient.',
    chips: ['Chicken', 'Beef', 'Pork', 'Fish', 'Egg', 'Tofu', 'Tomato', 'Eggplant', 'Mushroom', 'Lemon', 'Chocolate', 'Butter'],
  },
};

// Cuisines tile data (for the /cuisines page)
const CUISINE_TILES = [
  { name: 'Italian',       count: 184, tone: 'cream',  examples: ['Carbonara', 'Risotto', 'Cacio e pepe'] },
  { name: 'Japanese',      count: 162, tone: 'sea',    examples: ['Donburi', 'Ramen', 'Karaage'] },
  { name: 'Korean',        count: 138, tone: 'warm',   examples: ['Bibimbap', 'Gochujang chicken'] },
  { name: 'Indonesian',    count: 122, tone: 'warm',   examples: ['Nasi goreng', 'Rendang', 'Sate'] },
  { name: 'French',        count: 156, tone: 'butter', examples: ['Coq au vin', 'Tarte', 'Soupe'] },
  { name: 'Mexican',       count: 144, tone: 'warm',   examples: ['Mole', 'Tacos', 'Pozole'] },
  { name: 'Thai',          count: 128, tone: 'green',  examples: ['Pad krapow', 'Tom kha'] },
  { name: 'Indian',        count: 152, tone: 'warm',   examples: ['Dal', 'Biryani', 'Tikka'] },
  { name: 'Chinese',       count: 168, tone: 'cocoa',  examples: ['Mapo tofu', 'Dumplings'] },
  { name: 'Spanish',       count:  94, tone: 'butter', examples: ['Paella', 'Tortilla'] },
  { name: 'Levantine',     count: 108, tone: 'herb',   examples: ['Shakshuka', 'Tabbouleh'] },
  { name: 'Vietnamese',    count:  86, tone: 'green',  examples: ['Pho', 'Banh mi', 'Goi cuon'] },
];

// Collection tiles
const COLLECTION_TILES = [
  { name: 'Sunday Roasts',        count: 24, tone: 'warm',   blurb: 'The kind of meal that anchors a weekend.' },
  { name: 'Cookies Worth Making', count: 18, tone: 'butter', blurb: 'Brown butter, chilled dough, salt on top.' },
  { name: 'Pasta Without Recipes', count: 14, tone: 'cream', blurb: 'Five techniques. Endless variations.' },
  { name: 'Lunchbox',             count: 32, tone: 'herb',   blurb: 'Holds up by noon. Tastes better cold.' },
  { name: 'Dinner Party, 1 Hour', count: 12, tone: 'berry',  blurb: 'Three courses, one hour, no panic.' },
  { name: 'Pantry to Plate',      count: 28, tone: 'cream',  blurb: 'Whatever is already in your kitchen.' },
];

// Method tiles
const METHOD_TILES = [
  { name: 'Brown butter',          examples: 6, tone: 'butter' },
  { name: 'Pan sauce',             examples: 8, tone: 'warm' },
  { name: 'Reverse sear',          examples: 4, tone: 'cocoa' },
  { name: 'Lamination',            examples: 5, tone: 'cream' },
  { name: 'Tempering chocolate',   examples: 3, tone: 'cocoa' },
  { name: 'Quick pickles',         examples: 7, tone: 'green' },
  { name: 'Confit',                examples: 4, tone: 'butter' },
  { name: 'Risotto base',          examples: 6, tone: 'cream' },
];

const CategoryScreen = ({ slug, locale, onNavigate }) => {
  const cfg = CATEGORIES[slug] || CATEGORIES['/recipes'];
  const [activeChip, setActiveChip] = useState(0);
  const [sort, setSort] = useState('popular');
  const [view, setView] = useState('grid');

  // build a grid from TRENDING + QUICK_DINNERS, salted by chip selection
  const recipes = useMemo(() => {
    const all = [...TRENDING, ...QUICK_DINNERS.map(q => ({ ...q, author: 'Test kitchen', tag: q.tone })), ...TRENDING].slice(0, 12);
    return all;
  }, [slug, activeChip, sort]);

  return (
    <article>
      <CategoryBreadcrumb slug={slug} title={cfg.title} onNavigate={onNavigate} />
      <CategoryHero cfg={cfg} />

      {cfg.chips && (
        <CategoryFilterBar
          chips={cfg.chips} activeChip={activeChip} setActiveChip={setActiveChip}
          sort={sort} setSort={setSort} view={view} setView={setView}
        />
      )}

      {cfg.sub_links && (
        <div className="page" style={{ marginTop: 'var(--s-6)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }} className="sublinks-grid">
            {cfg.sub_links.map(s => (
              <a key={s.label} href="#" onClick={e=>e.preventDefault()} className="card"
                 style={{ padding: 'var(--s-5)', textDecoration: 'none', display: 'block' }}>
                <div className="display" style={{ fontSize: 19, color: 'var(--ink-strong)', marginBottom: 4 }}>{s.label}</div>
                <div className="row between">
                  <span style={{ fontSize: 13, color: 'var(--ink-mute)' }}>{s.count}</span>
                  <Icon name="arrowR" size={14} />
                </div>
              </a>
            ))}
          </div>
          <style>{`@media(max-width:880px){ .sublinks-grid{ grid-template-columns: 1fr 1fr !important; } }`}</style>
        </div>
      )}

      {cfg.isCuisines && <CuisineGrid onNavigate={onNavigate} />}
      {cfg.isCollections && <CollectionGrid onNavigate={onNavigate} />}
      {cfg.isMethods && <MethodGrid onNavigate={onNavigate} />}

      {!cfg.isCuisines && !cfg.isCollections && !cfg.isMethods && (
        <CategoryRecipeGrid recipes={recipes} locale={locale} onNavigate={onNavigate} />
      )}

      {cfg.faqs && <CategoryFaq faqs={cfg.faqs} />}
    </article>
  );
};

const CategoryBreadcrumb = ({ slug, title, onNavigate }) => (
  <div className="page" style={{ paddingTop: 'var(--s-5)' }}>
    <nav style={{ fontSize: 12, color: 'var(--ink-mute)', fontFamily: 'var(--font-mono)' }}>
      <a href="#/" onClick={e=>{e.preventDefault(); onNavigate('/');}} style={{ color: 'inherit' }}>/</a>
      <span style={{ margin: '0 6px', opacity: .5 }}>/</span>
      <span style={{ color: 'var(--ink-soft)' }}>{slug.replace(/^\//, '')}</span>
    </nav>
  </div>
);

const CategoryHero = ({ cfg }) => (
  <section className="section" style={{ paddingBottom: 'var(--s-6)' }}>
    <div className="page" style={{ maxWidth: 920 }}>
      <span className="eyebrow">{cfg.eyebrow}</span>
      <h1 className="display" style={{ fontSize: 'clamp(36px, 5vw, 64px)', margin: '10px 0 16px' }}>{cfg.title}</h1>
      <p style={{ fontSize: 'clamp(15px, 1.3vw, 19px)', color: 'var(--ink-soft)', lineHeight: 1.55, maxWidth: 720, margin: 0 }}>
        {cfg.sub}
      </p>
    </div>
  </section>
);

const CategoryFilterBar = ({ chips, activeChip, setActiveChip, sort, setSort, view, setView }) => (
  <div className="page" style={{
    position: 'sticky', top: 68, zIndex: 20,
    background: 'color-mix(in oklab, var(--bg) 88%, transparent)',
    backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
    paddingTop: 14, paddingBottom: 14, marginBottom: 'var(--s-4)',
    borderBottom: '1px solid var(--line)',
  }}>
    <div className="row between" style={{ gap: 12, flexWrap: 'wrap' }}>
      <div className="row wrap" style={{ gap: 6, flex: 1, minWidth: 0 }}>
        {chips.map((c, i) => (
          <button key={c} className={`chip ${activeChip === i ? 'is-active' : 'chip-outline'}`}
                  onClick={()=>setActiveChip(i)}
                  style={{ cursor: 'pointer' }}>{c}</button>
        ))}
      </div>
      <div className="row" style={{ gap: 8 }}>
        <select value={sort} onChange={e=>setSort(e.target.value)}
                style={{
                  appearance: 'none', font: 'inherit', fontSize: 13, fontWeight: 500,
                  padding: '6px 28px 6px 12px', borderRadius: 999,
                  background: 'var(--bg-elevated)', color: 'var(--ink)',
                  border: '1px solid var(--line-strong)', cursor: 'pointer',
                  backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E")`,
                  backgroundRepeat: 'no-repeat', backgroundPosition: 'right 10px center',
                }}>
          <option value="popular">Most popular</option>
          <option value="new">Newest</option>
          <option value="quick">Quick first</option>
          <option value="rating">Top rated</option>
        </select>
        <div className="row" style={{ background: 'var(--bg-elevated)', border: '1px solid var(--line-strong)', borderRadius: 999, padding: 3 }}>
          {['grid', 'list'].map(v => (
            <button key={v} onClick={()=>setView(v)} aria-label={v}
                    style={{
                      width: 28, height: 28, borderRadius: 999, border: 0,
                      background: view === v ? 'var(--ink-strong)' : 'transparent',
                      color: view === v ? 'var(--bg)' : 'var(--ink-soft)',
                      display: 'grid', placeItems: 'center', cursor: 'pointer',
                    }}>
              <Icon name={v} size={13} />
            </button>
          ))}
        </div>
      </div>
    </div>
  </div>
);

const CategoryRecipeGrid = ({ recipes, locale, onNavigate }) => (
  <div className="page" style={{ paddingBlock: 'var(--s-6)' }}>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }} className="cat-grid">
      {recipes.map((r, i) => (
        <RecipeCard key={i} recipe={r} locale={locale}
                    onClick={()=>onNavigate(`/${locale}/r/${RECIPE.slug}`)} />
      ))}
    </div>
    <div style={{ textAlign: 'center', marginTop: 'var(--s-8)' }}>
      <button className="btn btn-ghost">Load more · 8,408 remaining</button>
    </div>
    <style>{`
      @media(max-width:1000px){ .cat-grid{ grid-template-columns: repeat(3, 1fr) !important; } }
      @media(max-width:760px){ .cat-grid{ grid-template-columns: 1fr 1fr !important; } }
    `}</style>
  </div>
);

const CuisineGrid = ({ onNavigate }) => (
  <div className="page" style={{ paddingBlock: 'var(--s-6)' }}>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }} className="cuisine-grid">
      {CUISINE_TILES.map(c => (
        <a key={c.name} href="#" onClick={e=>e.preventDefault()} className="card"
           style={{ overflow: 'hidden', textDecoration: 'none', display: 'block' }}>
          <Photo tone={c.tone} ratio="4/3" radius="0" label={c.name.toLowerCase()} />
          <div style={{ padding: 'var(--s-4)' }}>
            <div className="row between">
              <h3 className="display" style={{ fontSize: 19, color: 'var(--ink-strong)', margin: 0 }}>{c.name}</h3>
              <span className="num" style={{ fontSize: 12, color: 'var(--ink-mute)' }}>{c.count}</span>
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 4 }}>
              {c.examples.slice(0,3).join(' · ')}
            </div>
          </div>
        </a>
      ))}
    </div>
    <style>{`
      @media(max-width:1000px){ .cuisine-grid{ grid-template-columns: repeat(3, 1fr) !important; } }
      @media(max-width:680px){ .cuisine-grid{ grid-template-columns: 1fr 1fr !important; } }
    `}</style>
  </div>
);

const CollectionGrid = ({ onNavigate }) => (
  <div className="page" style={{ paddingBlock: 'var(--s-6)' }}>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }} className="col-grid">
      {COLLECTION_TILES.map(c => (
        <a key={c.name} href="#" onClick={e=>e.preventDefault()} className="card"
           style={{ overflow: 'hidden', textDecoration: 'none', display: 'block' }}>
          <Photo tone={c.tone} ratio="5/3" radius="0" label={c.name.toLowerCase()} />
          <div style={{ padding: 'var(--s-5)' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>{c.count} recipes</div>
            <h3 className="display" style={{ fontSize: 22, color: 'var(--ink-strong)', margin: '0 0 4px' }}>{c.name}</h3>
            <p style={{ color: 'var(--ink-soft)', fontSize: 14, margin: 0 }}>{c.blurb}</p>
          </div>
        </a>
      ))}
    </div>
    <style>{`@media(max-width:880px){ .col-grid{ grid-template-columns: 1fr 1fr !important; } } @media(max-width:560px){ .col-grid{ grid-template-columns: 1fr !important; } }`}</style>
  </div>
);

const MethodGrid = ({ onNavigate }) => (
  <div className="page" style={{ paddingBlock: 'var(--s-6)' }}>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }} className="m-grid">
      {METHOD_TILES.map(m => (
        <a key={m.name} href="#" onClick={e=>e.preventDefault()} className="card"
           style={{ overflow: 'hidden', textDecoration: 'none', display: 'block' }}>
          <Photo tone={m.tone} ratio="1/1" radius="0" label={m.name.toLowerCase()} />
          <div style={{ padding: 'var(--s-4)' }}>
            <h3 className="display" style={{ fontSize: 17, color: 'var(--ink-strong)', margin: 0 }}>{m.name}</h3>
            <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 6 }}>{m.examples} tested recipes</div>
          </div>
        </a>
      ))}
    </div>
    <style>{`@media(max-width:880px){ .m-grid{ grid-template-columns: 1fr 1fr !important; } }`}</style>
  </div>
);

const CategoryFaq = ({ faqs }) => {
  const [open, setOpen] = useState(0);
  return (
    <section className="section" style={{ background: 'var(--bg-sunken)' }}>
      <div className="page" style={{ maxWidth: 820, margin: '0 auto' }}>
        <span className="eyebrow"><Icon name="sparkle" size={11} /> Answer-ready</span>
        <h2 className="display" style={{ fontSize: 'clamp(26px, 2.6vw, 36px)', margin: '8px 0 var(--s-6)' }}>
          Common questions
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {faqs.map((f, i) => (
            <div key={i} className="card" style={{
              padding: 'var(--s-5)',
              borderColor: open === i ? 'var(--accent)' : 'var(--line)',
            }}>
              <button onClick={()=>setOpen(open === i ? null : i)}
                      style={{ display: 'flex', width: '100%', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14, background: 'transparent', border: 0, padding: 0, font: 'inherit', textAlign: 'left', cursor: 'pointer', color: 'inherit' }}>
                <span className="display" style={{ fontSize: 17, fontWeight: 500, color: 'var(--ink-strong)' }}>{f.q}</span>
                <span style={{ flex: '0 0 auto', width: 26, height: 26, borderRadius: 999, background: open === i ? 'var(--accent)' : 'var(--bg-sunken)', color: open === i ? 'var(--accent-ink)' : 'var(--ink-soft)', display: 'grid', placeItems: 'center', transition: 'all .2s var(--ease)', transform: open === i ? 'rotate(45deg)' : 'rotate(0)' }}>
                  <Icon name="plus" size={11} stroke={2} />
                </span>
              </button>
              {open === i && <p style={{ margin: '12px 0 0', fontSize: 15, lineHeight: 1.6, color: 'var(--ink-soft)' }}>{f.a}</p>}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { CategoryScreen, CATEGORIES });
