/* global React, Icon */
// FitMyRecipe — landing sections
(function(){
const e = React.createElement;

/* ---------------- NAV ---------------- */
function Nav(){
  const toggleMenu = (ev)=>{ const n=document.getElementById('nav'); const open=n.classList.toggle('menu-open'); ev.currentTarget.setAttribute('aria-expanded', open?'true':'false'); };
  const closeMenu = ()=>{ const n=document.getElementById('nav'); if(!n) return; n.classList.remove('menu-open'); const b=n.querySelector('.nav-burger'); if(b) b.setAttribute('aria-expanded','false'); };
  return e('nav', { className:'nav', id:'nav' },
    e('a', { className:'wordmark', href:'#top', 'aria-label':'FitMyRecipe' },
      e('img',{className:'logo-img', src:'assets/logo-mark.png', alt:'FitMyRecipe'})),
    e('div', { className:'nav-links', onClick:closeMenu },
      e('a',{href:'#how'},'How it works'),
      e('a',{href:'#chef'},'The chef'),
      e('a',{href:'#nutrition'},'Nutrition'),
      e('a',{href:'#gallery'},'Before & after'),
      e('a',{href:'journal.html'},'Journal'),
      e('a',{href:'#premium'},'Premium')),
    e('div', { className:'nav-cta' },
      e('a',{className:'btn btn-primary', href:'#download'}, 'Get early access', e(Icon.arrowR,{size:17})),
      e('button',{className:'nav-burger', type:'button', 'aria-label':'Toggle menu', 'aria-expanded':'false', 'aria-controls':'nav', onClick:toggleMenu},
        e('svg',{width:22,height:22,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:2,strokeLinecap:'round'},
          e('line',{x1:4,y1:7,x2:20,y2:7}), e('line',{x1:4,y1:12,x2:20,y2:12}), e('line',{x1:4,y1:17,x2:20,y2:17}))))
  );
}

/* ---------------- MARQUEE ---------------- */
function Marquee(){
  const items = [
    ['link','Paste a link'], ['image','Drop a screenshot'], ['camera','Snap a photo'],
    ['wand','Upgrade in seconds'], ['flame','Keep the flavor'], ['trendUp','Hit your macros']
  ];
  const row = (key)=> e('div',{className:'track', key},
    [...items, ...items].map((it,i)=> e('span',{className:'m', key:i}, e(Icon[it[0]],{size:20}), it[1],
      e('span',{style:{color:'var(--gold-soft)', margin:'0 -28px 0 26px'}},'·'))));
  return e('div',{className:'marquee'}, row('a'));
}

/* ---------------- HOW IT WORKS ---------------- */
function HowItWorks(){
  const steps = [
    { n:'Step 01', ic:'image', t:'Save it', d:'Paste a link, drop a screenshot, or snap a photo. Our AI pulls out the ingredients, steps and nutrition for you.', thumb:'assets/hero-before.jpg' },
    { n:'Step 02', ic:'wand',  t:'Upgrade it', d:'Choose a goal — healthier, lighter, higher-protein or more filling. We rebuild the recipe and keep the flavor you love.', thumb:'assets/hero-after.jpg' },
    { n:'Step 03', ic:'flame', t:'Cook it', d:'Follow step-by-step Cook Mode with built-in timers, then share a beautiful branded recipe card.', thumb:'assets/g-salmon-after.jpg' },
  ];
  return e('section', { className:'container sec-pad', id:'how' },
    e('div', { className:'head center reveal' },
      e('span',{className:'overline'},'How it works'),
      e('h2',null,'Three taps from ', e('em',{className:'f',style:{fontStyle:'italic',color:'var(--burgundy)'}},'saved'),' to ', e('em',{className:'f',style:{fontStyle:'italic',color:'var(--burgundy)'}},'upgraded'),'.'),
      e('p',null,'No retyping, no guesswork. FitMyRecipe does the heavy lifting so you can just cook.')),
    e('div', { className:'steps' },
      steps.map((s,i)=> e('div',{className:'step reveal sc d'+(i+1), key:i},
        e('span',{className:'glow'}),
        e('img',{className:'step-thumb', src:s.thumb, alt:''}),
        e('div',{className:'num'}, s.n),
        e('div',{className:'s-ic'}, e(Icon[s.ic],{size:28})),
        e('h3',null,s.t),
        e('p',null,s.d)
      )))
  );
}

/* ---------------- NUTRITION / MACROS ---------------- */
function MacroLine({ k, v, u, w, bar }){
  return e('div',{className:'macro-line'},
    e('div',{className:'ml-top'}, e('span',{className:'ml-k'},k), e('span',{className:'ml-v'}, v, e('span',{className:'u'},u))),
    e('div',{className:'bar '+bar}, e('i',{style:{'--w':w+'%'}})));
}
function Nutrition(){
  const R=78, CIRC=2*Math.PI*R, PCT=0.85;
  return e('section',{className:'nutri sec-pad', id:'nutrition'},
    e('div',{className:'container'},
      e('div',{className:'head reveal'},
        e('span',{className:'overline'},'Honest nutrition'),
        e('h2',null,'See exactly what ', e('em',{style:{fontStyle:'italic',color:'var(--burgundy)'}},'changed'),'.'),
        e('p',null,'Every upgrade comes with an estimated before-and-after — and a confidence badge, because we never pretend to be more precise than we are.')),
      e('div',{className:'nutri-grid'},
        // compare card
        e('div',{className:'compare reveal sc'},
          e('div',{className:'compare-row'},
            e('div',{className:'compare-col orig'},
              e('span',{className:'tag t-orig floaty'},'Original'),
              e('div',{className:'macro-list'},
                e(MacroLine,{k:'Calories',v:'560',u:'',w:90,bar:'b-cal'}),
                e(MacroLine,{k:'Protein',v:'32',u:'g',w:42,bar:'b-pro'}),
                e(MacroLine,{k:'Fiber',v:'4',u:'g',w:18,bar:'b-fib'}),
                e(MacroLine,{k:'Fat',v:'24',u:'g',w:80,bar:'b-fat'}))),
            e('div',{className:'compare-col up'},
              e('span',{className:'tag t-up floaty'},'Higher-protein'),
              e('div',{className:'macro-list'},
                e(MacroLine,{k:'Calories',v:'430',u:'',w:62,bar:'b-cal'}),
                e(MacroLine,{k:'Protein',v:'48',u:'g',w:78,bar:'b-pro'}),
                e(MacroLine,{k:'Fiber',v:'11',u:'g',w:55,bar:'b-fib'}),
                e(MacroLine,{k:'Fat',v:'14',u:'g',w:40,bar:'b-fat'}))))),
        // confidence + points
        e('div',{className:'confidence reveal d2'},
          e('div',{style:{display:'flex',alignItems:'center',gap:'26px',flexWrap:'wrap'}},
            e('div',{className:'conf-badge', style:{'--circ':CIRC,'--off':CIRC*(1-PCT)}},
              e('svg',{viewBox:'0 0 168 168'},
                e('defs',null,e('linearGradient',{id:'goldgrad',x1:0,y1:0,x2:1,y2:1},
                  e('stop',{offset:0,stopColor:'#F0D469'}),e('stop',{offset:1,stopColor:'#B0892A'}))),
                e('circle',{className:'track',cx:84,cy:84,r:R}),
                e('circle',{className:'prog',cx:84,cy:84,r:R})),
              e('div',{className:'ctr'}, e('div',null, e('div',{className:'pct'},'85%'), e('div',{className:'lbl'},'Confidence')))),
            e('div',{style:{flex:'1 1 200px'}},
              e('p',{style:{fontFamily:'var(--display)',fontSize:'22px',color:'var(--forest)',lineHeight:1.3,margin:0}},
                'High confidence on this one.'),
              e('p',{style:{fontSize:'15px',color:'var(--fg-2)',margin:'8px 0 0'}},
                'Estimates improve as you confirm ingredients — you stay in control.'))),
          e('div',{className:'nutri-points'},
            [['Real whole-food swaps','Greek yogurt for cream, whole-wheat pasta, extra chicken — small changes, same comfort.'],
             ['Macros built around your goal','Protein and fiber up, calories and fat down. Tuned to the goal you picked.'],
             ['Always an estimate, never a promise','Each number ships with a confidence read. No fake precision, ever.']].map((p,i)=>
              e('div',{className:'np',key:i},
                e('div',{className:'check'}, e(Icon.check,{size:14})),
                e('div',{className:'nt'}, e('b',null,p[0]), e('p',null,p[1]))))))
      )
    )
  );
}

/* ---------------- MEET THE CHEF ---------------- */
function ChefSection(){
  return e('section',{className:'chef container', id:'chef'},
    e('div',{className:'chef-grid'},
      e('div',{className:'chef-photo reveal sc'},
        e('img',{className:'sprig-c', src:'assets/sprig.png', alt:''}),
        e('div',{className:'frame'},
          e('img',{src:'assets/chef-main.jpg', alt:'Sofia, the FitMyRecipe macro chef, in her kitchen'})),
        e('div',{className:'chef-quote floaty'},
          e('div',{className:'q'},'“You shouldn’t have to choose between the food you love and the goals you have.”'),
          e('div',{className:'who'},
            e('img',{src:'assets/chef-avatar.jpg', alt:'Sofia, the FitMyRecipe AI macro chef'}),
            e('div',null, e('div',{className:'nm'},'Sofia'), e('div',{className:'rl'},'Your AI macro chef'))))),
      e('div',{className:'chef-copy reveal d2'},
        e('span',{className:'overline'},'Meet your macro chef'),
        e('h2',null,'A chef in your pocket — ', e('em',null,'who actually gets your goals'),'.'),
        e('p',null,'Meet Sofia, the AI macro chef inside FitMyRecipe. She learns the food you love, then quietly rebuilds it to fit you — more protein, fewer empty calories, the same comfort on the plate.'),
        e('p',null,'No lectures, no bland “diet” food. Just your recipes, made to fit your life.'),
        e('div',{className:'chef-stats'},
          e('div',{className:'st'}, e('div',{className:'v'},'4'), e('div',{className:'k'},'ways to upgrade')),
          e('div',{className:'st'}, e('div',{className:'v'},'Any'), e('div',{className:'k'},'link, photo or screenshot')),
          e('div',{className:'st'}, e('div',{className:'v'},'Honest'), e('div',{className:'k'},'macros, every time'))),
        e('div',{className:'chef-sign'},
          e('img',{src:'assets/chef-avatar.jpg', alt:'Sofia, the FitMyRecipe AI macro chef'}),
          e('div',null, e('div',{className:'nm'},'Sofia'), e('div',{className:'rl'},'Your AI macro chef · FitMyRecipe')))))
  );
}

/* ---------------- GALLERY ---------------- */
const DISHES = [
  { t:'Loaded Veggie Chicken Pizza', m:'Pizza night · Healthier', before:'assets/g-pizza-before.jpg', after:'assets/g-pizza-after.jpg',
    d:[['+18g protein','up'],['3× veggies','up'],['−210 cal','dn']] },
  { t:'Teriyaki Salmon Power Bowl', m:'Lunch · Higher-protein', before:'assets/g-salmon-before.jpg', after:'assets/g-salmon-after.jpg',
    d:[['+14g protein','up'],['+9g fiber','up'],['quinoa swap','up']] },
  { t:'Grilled Chicken Smashburger', m:'Dinner · Lighter', before:'assets/g-burger-before.jpg', after:'assets/g-burger-after.jpg',
    d:[['+12g protein','up'],['−260 cal','dn'],['leaner cut','up']] },
  { t:'Blueberry Protein Pancakes', m:'Breakfast · More filling', before:'assets/g-pancakes-before.jpg', after:'assets/g-pancakes-after.jpg',
    d:[['+15g protein','up'],['less sugar','dn'],['+6g fiber','up']] },
];
function Gallery(){
  return e('section',{className:'container sec-pad', id:'gallery'},
    e('div',{className:'head reveal'},
      e('span',{className:'overline'},'Before & after'),
      e('h2',null,'The same dish, ', e('em',{style:{fontStyle:'italic',color:'var(--burgundy)'}},'made to fit you'),'.'),
      e('p',null,'Hover any dish to watch the original transform. Real flavor in, heavy stuff out.')),
    e('div',{className:'gallery'},
      DISHES.map((d,i)=> e('div',{className:'g-card reveal sc d'+(i%2+1), key:i},
        e('div',{className:'g-media'},
          e('img',{className:'g-before', src:d.before, alt:'Original '+d.t}),
          e('img',{className:'g-up', src:d.after, alt:'Upgraded '+d.t}),
          e('span',{className:'g-divider'}),
          e('div',{className:'g-flags'},
            e('span',{className:'g-flag b'},'Original'),
            e('span',{className:'g-flag a'}, 'Upgraded'))),
        e('div',{className:'g-body'},
          e('div',null, e('h3',null,d.t), e('div',{className:'g-meta'},d.m)),
          e('div',{className:'g-deltas'}, d.d.map((x,j)=> e('span',{className:'g-d '+x[1], key:j}, x[0])))))))
  );
}

/* ---------------- PREMIUM ---------------- */
function Premium(){
  const feats = [
    'Unlimited recipe upgrades',
    'All four goals — healthier, lighter, higher-protein, more filling',
    'Personalized to your preferences & dislikes',
    'Cook Mode with timers + branded share cards',
  ];
  return e('section',{className:'premium container', id:'premium'},
    e('div',{className:'premium-card reveal sc'},
      e('img',{className:'leaf-art', src:'assets/sprig.png', alt:''}),
      e('div',{className:'premium-grid'},
        e('div',null,
          e('span',{className:'overline'},'FitMyRecipe Premium'),
          e('h2',null,'Premium AI. ', e('em',null,'Personal results.'), ' Everyday cooking.'),
          e('p',{className:'p-lede'},'Go unlimited. Upgrade any recipe toward your goal, tuned to what you like and skip what you don’t.'),
          e('div',{className:'feat'},
            feats.map((f,i)=> e('div',{className:'f',key:i}, e('span',{className:'crn'}, e(Icon.crown,{size:15})), f)))),
        e('div',{className:'price-card'},
          e('div',{className:'crown-top'}, e(Icon.crown,{size:18}), 'PREMIUM'),
          e('div',{className:'price'}, e('span',{className:'amt'},'$6.99'), e('span',{className:'per'},'/ month')),
          e('div',{className:'price-note'},'or $49 / year — save 40%'),
          e('a',{className:'btn btn-primary btn-lg', href:'#download'},'Start 7-day free trial', e(Icon.arrowR,{size:18})),
          e('div',{className:'trial'},'Cancel anytime. No commitment.')))
    )
  );
}

/* ---------------- EARLY ACCESS (launching soon) ---------------- */
// Form delivery: POSTs to the Cloudflare Pages Function /api/waitlist, which emails
// the signup to info@fitmyrecipe.com via Brevo (see functions/api/waitlist.js).
const FORM_ENDPOINT = '/api/waitlist';
function CTA(){
  const [mode,setMode]=React.useState('waitlist');
  const [email,setEmail]=React.useState('');
  const [status,setStatus]=React.useState('idle'); // idle | sending | sent | error
  const submit=async(ev)=>{
    ev.preventDefault();
    if(!email.trim()) return;
    setStatus('sending');
    try{
      const r=await fetch(FORM_ENDPOINT,{ method:'POST', headers:{'Content-Type':'application/json','Accept':'application/json'}, body:JSON.stringify({ email:email.trim(), plan:mode, _subject:`New ${mode==='beta'?'beta tester application':'early access signup'} — FitMyRecipe` }) });
      setStatus(r.ok ? 'sent' : 'error');
    }catch(_){ setStatus('error'); }
  };
  const isBeta = mode==='beta';
  return e('section',{className:'cta early', id:'download'},
    e('img',{className:'phone-peek reveal', src:'assets/screen-home.png', alt:'', style:{left:'-3%',bottom:'-6%',transform:'rotate(-9deg)'}}),
    e('img',{className:'phone-peek reveal', src:'assets/screen-recipe-detail.png', alt:'', style:{right:'-3%',top:'-2%',transform:'rotate(9deg)'}}),
    e('div',{className:'container'},
      e('div',{className:'reveal'},
        e('span',{className:'overline'},'Coming soon · Track. Fuel. Perform.'),
        e('h2',{style:{marginTop:'16px'}},'Be first ', e('em',null,'to the table'),'.'),
        e('p',null,'FitMyRecipe opens its doors soon. Join the waitlist for early access — or apply to the private beta and help shape the app before everyone else.'),
        e('div',{style:{display:'flex',justifyContent:'center',marginTop:'30px'}},
          e('div',{className:'early-tabs', role:'tablist'},
            e('button',{className:'early-tab'+(!isBeta?' on':''), onClick:()=>{setMode('waitlist');setStatus('idle');}},'Early access'),
            e('button',{className:'early-tab'+(isBeta?' on':''), onClick:()=>{setMode('beta');setStatus('idle');}},'Beta tester'))),
        status==='sent'
          ? e('div',{className:'early-success'},
              e('span',{className:'ck'}, e(Icon.check,{size:15})),
              isBeta ? 'Application received — we’ll be in touch about the beta.' : 'You’re on the list! Watch your inbox for an invite.')
          : e('form',{className:'early-form', onSubmit:submit},
              e('input',{type:'email', required:true, placeholder:'you@email.com', value:email, disabled:status==='sending', 'aria-label':'Email address', onChange:(ev)=>setEmail(ev.target.value)}),
              e('button',{className:'btn btn-primary btn-lg', type:'submit', disabled:status==='sending'}, status==='sending' ? 'Sending…' : (isBeta?'Apply for the beta':'Request early access'), status!=='sending' && e(Icon.arrowR,{size:18}))),
        e('div',{className:'early-note'}, status==='error'
          ? e('span',{style:{color:'var(--burgundy)'}}, 'Hmm, that didn’t send — please email ', e('a',{href:'mailto:info@fitmyrecipe.com', style:{color:'var(--burgundy)', textDecoration:'underline'}},'info@fitmyrecipe.com'), '.')
          : (isBeta
            ? 'Limited beta spots · we read every application personally.'
            : 'No spam — just your invite the moment we open the doors.')),
        e('div',{style:{marginTop:'38px'}},
          e('span',{className:'overline', style:{display:'block', marginBottom:'14px'}},'Launching on'),
          e('div',{className:'store-row', style:{justifyContent:'center'}},
            e('span',{className:'store soon'}, e(Icon.apple,{size:26}), e('div',null, e('div',{className:'s-small'},'Coming soon to'), e('div',{className:'s-big'},'App Store'))),
            e('span',{className:'store soon'}, e(Icon.play,{size:24}), e('div',null, e('div',{className:'s-small'},'Coming soon to'), e('div',{className:'s-big'},'Google Play')))))
      ))
  );
}
/* ---------------- JOURNAL (home preview) ---------------- */
function articleMeta(a){
  return e('div',{className:'jr-meta'},
    e('span',null,a.category), e('span',{className:'dot'}), e('span',null,a.readMin+' min read'));
}
function JournalSection(){
  const all = window.journalSorted || window.JOURNAL || [];
  const feature = all[0];
  const rest = all.slice(1,4);
  if(!feature) return null;
  return e('section',{className:'journal sec-pad', id:'journal'},
    e('div',{className:'container'},
      e('div',{className:'head-row reveal'},
        e('div',{className:'head'},
          e('span',{className:'overline'},'Kitchen Science'),
          e('h2',null,'The ', e('em',{style:{fontStyle:'italic',color:'var(--burgundy)'}},'Journal'))),
        e('a',{className:'link-more', href:'journal.html'}, 'Read the journal', e(Icon.arrowR,{size:18}))),
      e('p',{className:'reveal', style:{fontSize:'19px', color:'var(--fg-2)', maxWidth:'56ch', margin:'18px 0 0'}},
        'The science of making food better — how ingredients behave, transform and interact, translated into swaps you can actually cook.'),
      e('div',{className:'jr-grid'},
        e('a',{className:'jr-feature reveal sc ac-'+feature.accent, href:'article.html?a='+feature.slug},
          e('div',{className:'ph'}, e('img',{src:feature.thumb, alt:feature.title})),
          e('div',{className:'body'},
            e('span',{className:'cat-pill'}, e('span',{className:'d'}), feature.category),
            e('h3',null, feature.title),
            e('p',null, feature.dek),
            articleMeta(feature))),
        e('div',{className:'jr-list'},
          rest.map((a,i)=> e('a',{className:'jr-card reveal d'+(i+1)+' ac-'+a.accent, href:'article.html?a='+a.slug, key:a.slug},
            e('div',{className:'ph'}, e('img',{src:a.thumb, alt:a.title})),
            e('div',{className:'body'},
              e('span',{className:'cat-pill'}, e('span',{className:'d'}), a.category),
              e('h4',null, a.title),
              articleMeta(a)))))))
  );
}

function Footer(){
  return e('footer',{className:'footer'},
    e('div',{className:'container footer-grid'},
      e('a',{className:'wordmark',href:'#top','aria-label':'FitMyRecipe'},
        e('img',{className:'logo-img', src:'assets/logo-mark.png', alt:'FitMyRecipe'})),
      e('div',{className:'f-links'},
        e('a',{href:'#how'},'How it works'),
        e('a',{href:'#nutrition'},'Nutrition'),
        e('a',{href:'journal.html'},'Journal'),
        e('a',{href:'#premium'},'Premium'),
        e('a',{href:'privacy.html'},'Privacy'),
        e('a',{href:'terms.html'},'Terms'),
        e('a',{href:'mailto:info@fitmyrecipe.com'},'Contact')),
      e('div',{className:'copy'},'© 2026 FitMyRecipe. Save any recipe. Upgrade it when you want.'))
  );
}

Object.assign(window, { Nav, Marquee, HowItWorks, ChefSection, JournalSection, Nutrition, Gallery, Premium, CTA, Footer });
})();
