// ============ Landing page (marketing) ============
const LandingPage = ({ setRoute, setAuthRoute, lang, setLang }) => {
  const { t } = useI18n();
  const { mode, setMode, accent, setAccent } = useTheme();
  const [billing, setBilling] = useState('annual');
  const [faqOpen, setFaqOpen] = useState(0);

  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior:'smooth', block:'start' });
  };

  const goSignup = () => { setAuthRoute('signup'); setRoute('login'); };
  const goSignin = () => { setAuthRoute('login'); setRoute('login'); };

  const proPrice = billing==='annual' ? 14 : 19;

  const faqs = [
    { q: 'How do you store my data?', a: 'Your trades and journal entries are encrypted at rest and in transit. We run on AWS with bank-grade security. You own your data and can export it anytime.' },
    { q: 'Can I connect my broker?', a: 'Manual entry and CSV import are available today. Broker auto-sync for IBKR, TD, and MT5 is on the roadmap for Q2 2026.' },
    { q: 'Is the Free tier really free forever?', a: 'Yes. Free includes 1 account, 30 trades/month, 3 strategies, and basic stats — no credit card, no time limit. Pro unlocks everything for $14/mo annual.' },
    { q: "What's your refund policy?", a: '14-day full refund on Pro, no questions asked. Email support@edgebook.app and we process it the same day.' },
    { q: 'How does multi-account tracking work?', a: 'Each account has its own equity curve, risk rules, and goals. Switch between them from the top nav or view the All-accounts rollup for portfolio totals.' },
    { q: 'Do you support prop firm challenges?', a: 'Yes. Create a prop_challenge account with your firm\'s max daily loss, total loss, and profit target — we track your progress against each rule in real time.' },
    { q: 'Can I export my data to other platforms?', a: 'Export to CSV or JSON anytime from Settings → Account. Your journal entries export as Markdown.' },
    { q: 'Do you generate tax reports?', a: 'We generate a realized P&L summary by tax year that your accountant can use directly. Full Form 8949 / Form 4797 support is on the Pro roadmap.' },
  ];

  const testimonials = [
    { quote: "I finally see what's actually working. Spent 6 months on Excel before this.", author:'Day trader, Bayanzurkh' },
    { quote: 'The challenge progress bars saved me from a daily-loss violation last week.', author:'FTMO trader' },
    { quote: 'Pre-trade plan mode broke my FOMO habit in 2 weeks.', author:'Crypto trader, Binance' },
    { quote: 'I love that I can journal in Mongolian.', author:'MSE swing trader' },
  ];

  return (
    <div>
      {/* Top nav */}
      <div className="lp-nav">
        <div className="nav-logo" style={{cursor:'pointer'}} onClick={()=>window.scrollTo({top:0,behavior:'smooth'})}>
          <span className="nav-logo-mark">E</span>
          <span style={{fontWeight:600,fontSize:15}}>Edgebook</span>
        </div>
        <div className="lp-nav-links">
          <div className="lp-nav-link" onClick={()=>scrollTo('features')}>{'Features'}</div>
          <div className="lp-nav-link" onClick={()=>scrollTo('pricing')}>{'Pricing'}</div>
          <div className="lp-nav-link" onClick={()=>scrollTo('faq')}>{'FAQ'}</div>
          <div className="lp-nav-link" onClick={()=>scrollTo('changelog')}>{'Changelog'}</div>
        </div>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          <div className="lang-pill">
            <button className={lang==='en'?'on':''} onClick={()=>setLang('en')}>EN</button>
            <button className={lang==='mn'?'on':''} onClick={()=>setLang('mn')}>MN</button>
          </div>
          <div className="lp-nav-link" onClick={goSignin}>{t('sign_in')}</div>
          <button className="lp-btn-primary" style={{padding:'9px 18px',fontSize:13.5}} onClick={goSignup}>{'Get started free'}</button>
        </div>
      </div>

      {/* Hero */}
      <section className="lp-hero">
        <div className="lp-container">
          <h1 className="lp-h1">{'Every edge starts with honest review.'}</h1>
          <p className="lp-sub">{'A private journal for serious traders — log setups, review mistakes, and build the discipline that compounds.'}</p>
          <div className="lp-cta-row">
            <button className="lp-btn-primary" onClick={goSignup}>{'Get started free'}</button>
            <button className="lp-btn-ghost">{'Watch 2-min demo'}</button>
          </div>
          <div className="lp-trust">★★★★★ 4.8 · 12,847 traders · 3.2M trades logged</div>
          <div style={{marginTop:56,maxWidth:1000,marginLeft:'auto',marginRight:'auto',transform:'perspective(1400px) rotateX(3deg)',transformOrigin:'50% 0'}}>
            <HeroMockup/>
          </div>
        </div>
      </section>

      {/* Problems */}
      <section className="lp-section">
        <div className="lp-container">
          <h2 className="lp-section-title">{'Most traders fail because:'}</h2>
          <div className="lp-problems">
            <div className="lp-problem"><div className="lp-problem-icon">📓</div><div style={{fontWeight:600,fontSize:17,marginBottom:6}}>{'No system to track what works'}</div><div className="muted" style={{fontSize:14,lineHeight:1.5}}>{'Winning setups get forgotten; losing ones get repeated.'}</div></div>
            <div className="lp-problem"><div className="lp-problem-icon">🧠</div><div style={{fontWeight:600,fontSize:17,marginBottom:6}}>{'Repeat the same mistakes invisibly'}</div><div className="muted" style={{fontSize:14,lineHeight:1.5}}>{'Without a record, every bad habit feels like a surprise.'}</div></div>
            <div className="lp-problem"><div className="lp-problem-icon">📊</div><div style={{fontWeight:600,fontSize:17,marginBottom:6}}>{'Excel sheets are messy and incomplete'}</div><div className="muted" style={{fontSize:14,lineHeight:1.5}}>{'Formulas break. Data gets lost. No one updates them.'}</div></div>
          </div>
        </div>
      </section>

      {/* Features */}
      <section id="features" className="lp-section">
        <div className="lp-container">
          <h2 className="lp-section-title">{'Built for serious traders.'}</h2>
          <div style={{marginTop:56}}>
            {[
              { eb:'Dashboard', h: 'All your accounts, one source of truth', c: 'Multi-account tracking with prop firm support — personal, funded, paper — all in one equity curve or split per account.', visual:'dashboard' },
              { eb:'Log trade', h: 'Pre-trade plan + post-trade reflection', c: 'Plan setups before you take them, reflect on execution after. Every trade becomes data that compounds.', visual:'logtrade' },
              { eb:'Calendar', h: 'See your good days, fix your bad days', c: 'Heatmap your P&L by day, week, and year. Best day, worst day, day-of-week patterns — all visible at a glance.', visual:'calendar' },
              { eb:'Playbook', h: "Track each strategy's edge separately", c: 'Per-strategy win rate, expectancy, and trade volume so you know exactly where your edge lives.', visual:'playbook' },
              { eb:'Journal', h: 'Honest reflection compounds', c: 'Daily market observations, lessons learned, tomorrow\'s plan. Mood, emotion, and tilt tracked over time.', visual:'journal' },
              { eb:'Prop firm', h: 'Know your challenge limits in real time', c: 'Max daily loss, max total loss, profit target — live progress bars so you never violate a rule by accident.', visual:'prop' },
            ].map((f,i) => (
              <div key={i} className={'lp-feat ' + (i%2===1?'reverse':'')}>
                <div>
                  <div className="lp-feat-eyebrow">{f.eb}</div>
                  <div className="lp-feat-title">{f.h}</div>
                  <div className="lp-feat-copy">{f.c}</div>
                </div>
                <div className="lp-feat-visual"><FeatureVisual kind={f.visual}/></div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* How */}
      <section className="lp-section">
        <div className="lp-container">
          <h2 className="lp-section-title">{'How it works'}</h2>
          <div className="lp-steps">
            <div className="lp-step"><div className="lp-step-num">1</div><div style={{fontWeight:600,fontSize:17,marginBottom:6}}>{'Log your trades'}</div><div className="muted" style={{fontSize:14,lineHeight:1.5}}>{'Manual or CSV import. Takes 15 seconds per trade.'}</div></div>
            <div className="lp-step"><div className="lp-step-num">2</div><div style={{fontWeight:600,fontSize:17,marginBottom:6}}>{'Review your stats'}</div><div className="muted" style={{fontSize:14,lineHeight:1.5}}>{'Analytics, calendar, playbook. Spot patterns in hours, not months.'}</div></div>
            <div className="lp-step"><div className="lp-step-num">3</div><div style={{fontWeight:600,fontSize:17,marginBottom:6}}>{'Refine your edge'}</div><div className="muted" style={{fontSize:14,lineHeight:1.5}}>{'Discipline plus journal. Compound the good, kill the bad.'}</div></div>
          </div>
        </div>
      </section>

      {/* Pricing */}
      <section id="pricing" className="lp-section">
        <div className="lp-container">
          <h2 className="lp-section-title">{'Simple pricing. Cancel anytime.'}</h2>
          <div className="lp-pricing-toggle-wrap">
            <div className="seg">
              <button className={billing==='monthly'?'on':''} onClick={()=>setBilling('monthly')}>{'Monthly'}</button>
              <button className={billing==='annual'?'on':''} onClick={()=>setBilling('annual')}>{'Annual'}</button>
            </div>
            {billing==='annual' && <span className="badge badge-win" style={{fontSize:11.5}}>Save 26%</span>}
          </div>
          <div className="lp-pricing">
            <div className="lp-price-card">
              <div className="lp-price-name">{'Free'}</div>
              <div className="lp-price-value">$0 <span>forever</span></div>
              <div className="lp-price-tag">{'For traders just getting started'}</div>
              <ul className="lp-price-list">
                <li>1 trading account</li><li>30 trades per month</li><li>3 strategies</li>
                <li>Basic stats (Net P&L, Win rate)</li><li>Equity curve & calendar</li><li>5 journal entries / month</li>
              </ul>
              <button className="btn" style={{justifyContent:'center',width:'100%',height:40,fontWeight:500}} onClick={goSignup}>{'Get started'}</button>
            </div>
            <div className="lp-price-card highlight">
              <div className="lp-price-badge">Most popular</div>
              <div className="lp-price-name">{'Pro'}</div>
              <div className="lp-price-value">${proPrice}<span>/mo</span></div>
              <div className="lp-price-tag">{billing==='annual' ? '$168 billed annually' : '$19/mo billed monthly'} — {'For traders who want their edge'}</div>
              <ul className="lp-price-list">
                <li>Everything in Free, plus:</li>
                <li>Unlimited accounts (incl. prop firm tracking)</li>
                <li>Unlimited trades & strategies</li>
                <li>Full analytics + Expectancy KPI</li>
                <li>Calendar Year heatmap</li>
                <li>CSV import</li>
                <li>Screenshot upload (multiple per trade)</li>
                <li>Live risk warnings + Pre-trade plan mode</li>
                <li>Notifications (in-app + email)</li>
                <li>Emotion 7-point + Tilt score</li>
                <li>Daily journal (unlimited)</li>
                <li>Priority support</li>
                <li>Coming: AI insights, broker auto-sync</li>
              </ul>
              <button className="lp-btn-primary" style={{justifyContent:'center',width:'100%',padding:'12px 20px'}} onClick={goSignup}>{'Start 14-day trial'}</button>
              <div className="muted tiny" style={{textAlign:'center',marginTop:10}}>{'No credit card required'}</div>
            </div>
          </div>
          <div className="muted tiny" style={{textAlign:'center',marginTop:32}}>All plans include · Bank-grade encryption · GDPR compliant · Cancel anytime</div>
        </div>
      </section>

      {/* Testimonials */}
      <section className="lp-section">
        <div className="lp-container">
          <h2 className="lp-section-title">{'From the beta'}</h2>
          <div className="lp-testimonials">
            {testimonials.map((tm,i) => (
              <div key={i} className="lp-testimonial">
                <div className="lp-quote">"{tm.quote}"</div>
                <div style={{display:'flex',alignItems:'center',gap:10,marginTop:16}}>
                  <div className="lp-avatar">{tm.author.slice(0,1)}</div>
                  <div className="muted" style={{fontSize:13}}>{tm.author}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section id="faq" className="lp-section">
        <div className="lp-container">
          <h2 className="lp-section-title">{'Frequently asked'}</h2>
          <div className="lp-faq">
            {faqs.map((f,i) => (
              <div key={i} className="lp-faq-item" onClick={()=>setFaqOpen(faqOpen===i?-1:i)}>
                <div className="lp-faq-q">
                  <span>{f.q}</span>
                  <Icon name={faqOpen===i?'chevron-down':'chevron-right'} size={16}/>
                </div>
                {faqOpen===i && <div className="lp-faq-a">{f.a}</div>}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Final CTA */}
      <section className="lp-final">
        <div className="lp-container">
          <h2 className="lp-section-title" style={{marginBottom:14}}>{'Start tracking your edge today.'}</h2>
          <div className="lp-section-sub" style={{marginBottom:32}}>{"Free forever. Pro when you're ready."}</div>
          <button className="lp-btn-primary" onClick={goSignup}>{'Get started free'}</button>
        </div>
      </section>

      {/* Footer */}
      <footer className="lp-footer">
        <div className="lp-footer-cols">
          <div>
            <div className="nav-logo" style={{marginBottom:12}}><span className="nav-logo-mark">E</span><span style={{fontWeight:600,fontSize:15}}>Edgebook</span></div>
            <div className="muted" style={{fontSize:13,marginBottom:14,maxWidth:260,lineHeight:1.5}}>{'The trader\'s journal for serious review.'}</div>
            <div className="lang-pill"><button className={lang==='en'?'on':''} onClick={()=>setLang('en')}>EN</button><button className={lang==='mn'?'on':''} onClick={()=>setLang('mn')}>MN</button></div>
          </div>
          <div className="lp-footer-col"><h4>Product</h4><a>Features</a><a>Pricing</a><a>Changelog</a><a>Roadmap</a></div>
          <div className="lp-footer-col"><h4>Resources</h4><a>Docs</a><a>Blog</a><a>Help</a><a>API</a></div>
          <div className="lp-footer-col"><h4>Company</h4><a>About</a><a>Contact</a><a>Careers</a></div>
          <div className="lp-footer-col"><h4>Legal</h4><a>Privacy</a><a>Terms</a><a>Cookies</a></div>
        </div>
        <div className="lp-footer-bottom">© 2026 Edgebook. All rights reserved.</div>
      </footer>
    </div>
  );
};

// ----- Hero mockup: miniature dashboard -----
const HeroMockup = () => {
  const { fmtCur } = useI18n();
  const eqData = EQUITY.map(e=>e.equity);
  const min = Math.min(...eqData), max = Math.max(...eqData);
  const span = max - min || 1;
  const w = 800, h = 160;
  const pts = eqData.map((v,i) => `${(i*w/(eqData.length-1)).toFixed(0)},${(h - ((v-min)/span)*h*0.9 - 10).toFixed(0)}`).join(' ');
  return (
    <div style={{background:'var(--card)',border:'1px solid var(--border)',borderRadius:14,overflow:'hidden',boxShadow:'0 30px 80px -20px rgba(0,0,0,.5)'}}>
      {/* Fake window chrome */}
      <div style={{display:'flex',alignItems:'center',gap:8,padding:'10px 14px',borderBottom:'1px solid var(--border)',background:'var(--card-2)'}}>
        <div style={{width:10,height:10,borderRadius:999,background:'#ef4444'}}/>
        <div style={{width:10,height:10,borderRadius:999,background:'#f59e0b'}}/>
        <div style={{width:10,height:10,borderRadius:999,background:'#10b981'}}/>
        <div style={{marginLeft:16,fontSize:11,color:'var(--text-3)',fontFamily:'JetBrains Mono,monospace'}}>edgebook.app / dashboard</div>
      </div>
      {/* KPI strip */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:0,padding:16,borderBottom:'1px solid var(--border)'}}>
        {[['Net P&L','+$15,262','up'],['Win Rate','54%','up'],['Profit Factor','1.78','up'],['Avg R','+0.45R','up']].map(([l,v,d],i)=>(
          <div key={i} style={{padding:'0 14px',borderRight:i<3?'1px solid var(--border)':'none'}}>
            <div className="tiny muted" style={{textTransform:'uppercase',letterSpacing:'0.08em',fontSize:10}}>{l}</div>
            <div className={'mono ' + (d==='up'?'up':'dn')} style={{fontSize:20,fontWeight:600,marginTop:4}}>{v}</div>
          </div>
        ))}
      </div>
      {/* Mini chart */}
      <div style={{padding:16}}>
        <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{display:'block'}}>
          <defs>
            <linearGradient id="lpHeroGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.35"/>
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
            </linearGradient>
          </defs>
          <polygon points={`0,${h} ${pts} ${w},${h}`} fill="url(#lpHeroGrad)"/>
          <polyline points={pts} fill="none" stroke="var(--accent)" strokeWidth="2"/>
        </svg>
      </div>
    </div>
  );
};

const FeatureVisual = ({ kind }) => {
  if (kind === 'dashboard') {
    return (
      <div style={{display:'flex',flexDirection:'column',gap:10}}>
        {['Main','FTMO 100k','Apex Funded','Binance'].map((n,i)=>(
          <div key={n} style={{display:'flex',alignItems:'center',gap:10,padding:'10px 12px',background:'var(--card-2)',borderRadius:8}}>
            <div style={{width:24,height:24,borderRadius:6,background:['#10b981','#f59e0b','#3b82f6','#8b5cf6'][i]}}/>
            <div style={{flex:1,fontWeight:500,fontSize:13}}>{n}</div>
            <div className={'mono ' + ([0,1,2,0][i]===0?'up':'dn')} style={{fontSize:13,fontWeight:600}}>{['+$4,231','−$820','+$1,284','+$312'][i]}</div>
          </div>
        ))}
      </div>
    );
  }
  if (kind === 'logtrade') {
    return (
      <div style={{display:'flex',flexDirection:'column',gap:10}}>
        <div style={{display:'flex',gap:8}}><div className="seg"><button className="on">Plan</button><button>Executed</button></div></div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
          <div><div className="tiny muted">Ticker</div><div className="mono" style={{fontSize:16,fontWeight:600}}>NVDA</div></div>
          <div><div className="tiny muted">Direction</div><div><span className="badge badge-long">LONG</span></div></div>
          <div><div className="tiny muted">Entry</div><div className="mono">$118.40</div></div>
          <div><div className="tiny muted">Stop</div><div className="mono">$117.20</div></div>
          <div><div className="tiny muted">R:R</div><div className="mono up">1 : 3.00</div></div>
          <div><div className="tiny muted">Risk</div><div className="mono">$240 (1.0%)</div></div>
        </div>
        <div className="muted tiny" style={{marginTop:4,padding:8,background:'var(--card-2)',borderRadius:6}}>"Break of 15m ORB high with vol &gt; 1.5× avg"</div>
      </div>
    );
  }
  if (kind === 'calendar') {
    return (
      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:4}}>
        {Array.from({length:35}).map((_,i)=>{
          const v = Math.sin(i*1.3)*2;
          const isWin = v > 0.2, isLoss = v < -0.2;
          return <div key={i} style={{aspectRatio:'1',borderRadius:4,background:isWin?'rgba(16,185,129,'+(0.2+Math.abs(v)*0.3)+')':isLoss?'rgba(239,68,68,'+(0.2+Math.abs(v)*0.3)+')':'var(--card-2)'}}/>;
        })}
      </div>
    );
  }
  if (kind === 'playbook') {
    return (
      <div style={{display:'flex',flexDirection:'column',gap:10}}>
        {[['ORB Breakout','62%','+$3,840'],['VWAP Reversal','54%','+$1,220'],['Support Bounce','48%','−$340']].map(([n,wr,net],i)=>(
          <div key={n} style={{padding:'10px 12px',background:'var(--card-2)',borderRadius:8}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <div style={{fontWeight:500,fontSize:13}}>{n}</div>
              <div className={'mono ' + (net.startsWith('+')?'up':'dn')} style={{fontSize:13,fontWeight:600}}>{net}</div>
            </div>
            <div className="bar" style={{marginTop:8}}><span style={{width:wr,background:'var(--accent)'}}/></div>
            <div className="tiny muted" style={{marginTop:4}}>Win rate {wr}</div>
          </div>
        ))}
      </div>
    );
  }
  if (kind === 'journal') {
    return (
      <div style={{fontSize:13,lineHeight:1.55}}>
        <div className="muted tiny" style={{marginBottom:8}}>TUE · APR 21</div>
        <div style={{fontWeight:500,marginBottom:6}}>Market observations</div>
        <div className="muted" style={{marginBottom:10}}>Gap up open on NVDA earnings beat. Tape was heavy in megacaps. ORB held clean on /NQ...</div>
        <div style={{fontWeight:500,marginBottom:6}}>Lessons learned</div>
        <div className="muted">Didn't size up the second NVDA setup even though R:R was there. Need to trust the process more.</div>
      </div>
    );
  }
  if (kind === 'prop') {
    return (
      <div style={{display:'flex',flexDirection:'column',gap:16}}>
        {[['Max daily loss','$320 / $5,000','6%','#10b981'],['Max total loss','$1,240 / $10,000','12%','#f59e0b'],['Profit target','$7,500 / $10,000','75%','#10b981']].map(([l,v,pct,c])=>(
          <div key={l}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:6}}>
              <div style={{fontWeight:500,fontSize:13}}>{l}</div>
              <div className="mono tiny muted">{v}</div>
            </div>
            <div className="bar"><span style={{width:pct,background:c}}/></div>
          </div>
        ))}
      </div>
    );
  }
  return null;
};

window.LandingPage = LandingPage;
