// M05 — Blog index + post detail page
const BlogIndex = ({ setPage, openPost }) => {
  const [cat, setCat] = React.useState('All');
  const cats = ['All', 'Engineering', 'AI', 'Design', 'Payments', 'Studio'];
  const filtered = cat === 'All' ? POSTS : POSTS.filter(p => p.category === cat);

  return (
    <div className="page">
      {/* Hero */}
      <section style={{padding:'56px 0 60px', borderBottom:'1px solid var(--line)', position:'relative', overflow:'hidden'}}>
        <div aria-hidden style={{position:'absolute', top:-200, left:-100, width:500, height:500, background:'radial-gradient(circle, rgba(212,255,58,0.06), transparent 60%)', filter:'blur(40px)'}}/>
        <div className="container" style={{position:'relative'}}>
          <div className="eyebrow" style={{marginBottom:24}}><span className="dot"/>The Atoms Journal · 47 essays</div>
          <h1 style={{fontSize:'clamp(48px,8vw,120px)', lineHeight:0.92, letterSpacing:'-0.045em', fontWeight:500, marginBottom:28, maxWidth:1100}}>
            Field notes from <span className="serif" style={{color:'var(--accent)'}}>active</span> builds.
          </h1>
          <p style={{fontSize:'clamp(17px,1.6vw,21px)', lineHeight:1.5, color:'var(--ink-2)', maxWidth:720}}>
            Engineering essays, post-mortems, and the occasional half-baked idea — written by the team while they're still close enough to the work to remember the details.
          </p>
        </div>
      </section>

      {/* Filters */}
      <section style={{padding:'40px 0 20px', position:'sticky', top:68, zIndex:30, background:'rgba(10,10,10,0.85)', backdropFilter:'blur(18px)', borderBottom:'1px solid var(--line)'}}>
        <div className="container" style={{display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:16}}>
          <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
            {cats.map(c => (
              <button key={c} onClick={()=>setCat(c)} style={{
                padding:'7px 14px',borderRadius:999,fontSize:13,
                border:'1px solid', borderColor: cat===c ? 'var(--accent)' : 'var(--line)',
                color: cat===c ? '#0a0a0a' : 'var(--ink-2)',
                background: cat===c ? 'var(--accent)' : 'transparent'
              }}>{c} <span className="mono" style={{fontSize:10,opacity:0.6,marginLeft:4}}>{c==='All' ? POSTS.length : POSTS.filter(p=>p.category===c).length}</span></button>
            ))}
          </div>
          <div style={{display:'flex',alignItems:'center',gap:10,padding:'7px 12px',borderRadius:8,background:'var(--bg-2)',border:'1px solid var(--line)',width:280}}>
            <span style={{color:'var(--ink-3)',fontSize:13}}>⌕</span>
            <input placeholder="Search posts…" style={{flex:1,background:'transparent',border:0,outline:'none',color:'var(--ink)',fontSize:13,fontFamily:'var(--sans)'}}/>
          </div>
        </div>
      </section>

      {/* Featured */}
      <section style={{padding:'60px 0 40px'}}>
        <div className="container">
          <div className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:20}}>● FEATURED</div>
          <article onClick={()=>openPost(filtered[0])} className="card clickable" style={{padding:0,overflow:'hidden',display:'grid',gridTemplateColumns:'1.2fr 1fr'}}>
            <div style={{aspectRatio:'4/3', position:'relative', background:`linear-gradient(135deg, ${filtered[0].cover}33, #0a0a0a 80%)`, borderRight:'1px solid var(--line)'}}>
              <svg style={{position:'absolute',inset:0,width:'100%',height:'100%'}} preserveAspectRatio="xMidYMid slice">
                <defs>
                  <pattern id="featpat" width="40" height="40" patternUnits="userSpaceOnUse">
                    <path d="M0 20 L40 20 M20 0 L20 40" stroke={filtered[0].cover} strokeWidth="0.4" opacity="0.25"/>
                  </pattern>
                </defs>
                <rect width="100%" height="100%" fill="url(#featpat)"/>
                <text x="32" y="44" fontFamily="JetBrains Mono" fontSize="13" fill={filtered[0].cover} opacity="0.7" letterSpacing="0.08em">JOURNAL · ESSAY №01</text>
              </svg>
            </div>
            <div style={{padding:'40px 44px',display:'flex',flexDirection:'column',justifyContent:'center',gap:18}}>
              <div style={{display:'flex',gap:8}}>
                <Tag accent>Featured</Tag>
                <Tag>{filtered[0].category}</Tag>
                <Tag>{filtered[0].read}</Tag>
              </div>
              <h2 style={{fontSize:'clamp(28px,3.4vw,42px)',letterSpacing:'-0.03em',fontWeight:500,lineHeight:1.05}}>{filtered[0].title}</h2>
              <p style={{fontSize:16,color:'var(--ink-2)',lineHeight:1.55}}>{filtered[0].excerpt}</p>
              <div style={{display:'flex',alignItems:'center',gap:12,marginTop:6}}>
                <span style={{width:32,height:32,borderRadius:'50%',background:`linear-gradient(135deg, ${filtered[0].cover}55, ${filtered[0].cover}22)`,border:`1px solid ${filtered[0].cover}44`}}/>
                <div>
                  <div style={{fontSize:13,fontWeight:500}}>{filtered[0].author}</div>
                  <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em'}}>{filtered[0].date.toUpperCase()}</div>
                </div>
              </div>
            </div>
          </article>
        </div>
      </section>

      {/* Grid */}
      <section style={{padding:'40px 0 80px'}}>
        <div className="container">
          <div className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:20}}>ALL ESSAYS</div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(320px,1fr))',gap:24}}>
            {filtered.slice(1).concat(filtered).concat(filtered).slice(0,9).map((p,i) => (
              <article key={i} onClick={()=>openPost(p)} className="card clickable" style={{padding:0,overflow:'hidden',display:'flex',flexDirection:'column'}}>
                <div style={{aspectRatio:'16/10',position:'relative',background:`linear-gradient(135deg, ${p.cover}33, #0a0a0a 80%)`,borderBottom:'1px solid var(--line)'}}>
                  <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                    <span className="mono" style={{fontSize:14, color:p.cover, letterSpacing:'0.08em', opacity:0.7}}>{p.category.toUpperCase()}</span>
                  </div>
                </div>
                <div style={{padding:'22px 24px 24px',display:'flex',flexDirection:'column',gap:10,flex:1}}>
                  <div style={{display:'flex',gap:6,marginBottom:4}}>
                    <Tag>{p.category}</Tag>
                    <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',alignSelf:'center'}}>{p.read}</span>
                  </div>
                  <h3 style={{fontSize:18,letterSpacing:'-0.015em',fontWeight:500,lineHeight:1.25,flex:1}}>{p.title}</h3>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',paddingTop:14,borderTop:'1px solid var(--line)',marginTop:8}}>
                    <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em'}}>{p.author.toUpperCase()} · {p.date}</div>
                    <span style={{color:'var(--ink-3)'}}>{Icon.arrow()}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
          <div style={{textAlign:'center',marginTop:40}}>
            <button className="btn btn-ghost">Load more</button>
          </div>
        </div>
      </section>
    </div>
  );
};

const BlogPost = ({ post, setPage, openPost }) => {
  const p = post || POSTS[0];
  return (
    <div className="page">
      {/* Hero */}
      <section style={{padding:'56px 0 60px', borderBottom:'1px solid var(--line)', position:'relative', overflow:'hidden'}}>
        <div aria-hidden style={{position:'absolute', top:-200, right:-100, width:600, height:600, background:`radial-gradient(circle, ${p.cover}1a, transparent 60%)`, filter:'blur(40px)'}}/>
        <div className="container" style={{position:'relative', maxWidth:880}}>
          <button onClick={()=>setPage('blog')} className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:32,display:'inline-flex'}}>← JOURNAL</button>
          <div style={{display:'flex',gap:8,marginBottom:24}}>
            <Tag>{p.category}</Tag>
            <Tag>{p.read}</Tag>
            <span className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em',alignSelf:'center'}}>{p.date.toUpperCase()}</span>
          </div>
          <h1 style={{fontSize:'clamp(40px,6vw,80px)',lineHeight:0.98,letterSpacing:'-0.04em',fontWeight:500,marginBottom:28}}>
            {p.title}
          </h1>
          <p style={{fontSize:'clamp(18px,1.8vw,24px)',lineHeight:1.45,color:'var(--ink-2)',marginBottom:32,letterSpacing:'-0.005em'}}>
            {p.excerpt}
          </p>
          <div style={{display:'flex',alignItems:'center',gap:14,paddingTop:24,borderTop:'1px solid var(--line)'}}>
            <span style={{width:44,height:44,borderRadius:'50%',background:`linear-gradient(135deg, ${p.cover}55, ${p.cover}22)`,border:`1px solid ${p.cover}66`,display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--mono)',fontSize:13,fontWeight:600,color:p.cover}}>{p.author.split(' ').map(w=>w[0]).join('')}</span>
            <div style={{flex:1}}>
              <div style={{fontSize:14,fontWeight:500}}>{p.author}</div>
              <div className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em'}}>{['ENGINEERING LEAD','AI ENGINEER','BACKEND LEAD','PRODUCT DESIGNER'][POSTS.indexOf(p) % 4]}</div>
            </div>
            <button className="btn btn-ghost" style={{padding:'8px 14px',fontSize:12}}>Share</button>
            <button className="btn btn-ghost" style={{padding:'8px 14px',fontSize:12}}>★ Save</button>
          </div>
        </div>
      </section>

      {/* Hero image */}
      <section style={{padding:'60px 0'}}>
        <div className="container" style={{maxWidth:1080}}>
          <Placeholder label={`cover · ${p.title.toLowerCase().slice(0,40)}`} code={`P.0${POSTS.indexOf(p)+1}`} color={`${p.cover}33`} ratio="16/9"/>
        </div>
      </section>

      {/* Body */}
      <section style={{padding:'20px 0 80px'}}>
        <div className="container" style={{display:'grid',gridTemplateColumns:'200px minmax(0,1fr) 240px',gap:48,alignItems:'start'}}>
          {/* TOC */}
          <aside style={{position:'sticky',top:140}}>
            <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.08em',marginBottom:14,paddingBottom:10,borderBottom:'1px solid var(--line)'}}>ON THIS PAGE</div>
            <ul style={{listStyle:'none',display:'flex',flexDirection:'column',gap:8}}>
              {['The setup','Six rules','Rule 1 · Demo before merge','Rule 2 · Feature flags everywhere','Rule 3 · Ship one slice','Lessons','What\'s next'].map((s,i) => (
                <li key={s}><a style={{fontSize:13,color: i===2 ? 'var(--accent)' : 'var(--ink-3)', display:'flex', gap:8}}>
                  <span className="mono" style={{fontSize:10,opacity:0.5}}>0{i+1}</span>{s}
                </a></li>
              ))}
            </ul>
          </aside>

          {/* Article */}
          <article style={{display:'flex',flexDirection:'column',gap:24,fontSize:17,lineHeight:1.7,color:'var(--ink-2)',maxWidth:720,margin:'0 auto'}}>
            <p style={{fontSize:20,lineHeight:1.55,color:'var(--ink)',letterSpacing:'-0.005em'}}>
              Most rewrites die. Of the four I've personally been through, two shipped — and one of those shipped 11 months late. The other two were quietly killed when someone calculated how much it had cost to not ship features for a year.
            </p>
            <p>
              When this client came to us, the codebase was 14 years old: a PHP 5.6 monolith with parts written by people who had since become CTOs at other companies, then left, then become VCs. Page loads averaged 3.2 seconds. The team had stopped trying to add features and was instead just trying to keep the lights on.
            </p>

            <h2 style={{fontSize:32,letterSpacing:'-0.025em',fontWeight:500,color:'var(--ink)',marginTop:24,lineHeight:1.15}}>Six rules</h2>
            <p>
              We rewrote it in 9 weeks. Here's what we did differently — and the rules we followed religiously.
            </p>

            <div style={{padding:'24px 28px',borderLeft:'2px solid var(--accent)',background:'rgba(212,255,58,0.04)',margin:'8px 0',borderRadius:'0 8px 8px 0'}}>
              <div className="mono" style={{fontSize:10,color:'var(--accent)',letterSpacing:'0.08em',marginBottom:10}}>RULE №01</div>
              <div style={{fontSize:22,fontWeight:500,color:'var(--ink)',letterSpacing:'-0.015em',lineHeight:1.3}}>Demo before merge, every time.</div>
            </div>

            <p>
              Every PR demoed to the broader team before it merged. Five-minute demos, async over Loom, with one engineer and the product owner watching. No exceptions. This sounds slow until you compare it to the cost of finding out three sprints later that what you built isn't what was needed.
            </p>

            <Placeholder label="figure · pr demo cadence" code="FIG.01" color="#1a1a1c" ratio="16/9"/>

            <p>
              Most rewrites fail because the team disappears into a branch for six months and emerges with something that's both 3 months late and not what anyone wanted. Demo-before-merge solves both problems by forcing weekly contact with reality.
            </p>

            <h2 style={{fontSize:32,letterSpacing:'-0.025em',fontWeight:500,color:'var(--ink)',marginTop:24,lineHeight:1.15}}>Lessons</h2>
            <p>
              If we did it again — and we will — three things change. We'd retrofit the test harness in week 0 not week 4. We'd push back harder on scope creep in week 6. And we'd keep an "outside reviewer" engineer rotating in monthly who hadn't seen the code for two weeks, to catch the things we'd stopped seeing.
            </p>

            <div style={{padding:'24px 28px',borderRadius:10,border:'1px solid var(--line)',background:'var(--bg-2)',marginTop:8}}>
              <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.08em',marginBottom:14}}>TL;DR</div>
              <ul style={{listStyle:'none',display:'flex',flexDirection:'column',gap:8,fontSize:15,color:'var(--ink)'}}>
                {['Demo before merge','Feature flags from day 1','Ship one slice all the way through','Track velocity weekly','Pay down test debt early','Bring in an outside reviewer monthly'].map(r => (
                  <li key={r} style={{display:'flex',alignItems:'center',gap:10}}>
                    <span style={{color:'var(--accent)'}}>{Icon.check()}</span>{r}
                  </li>
                ))}
              </ul>
            </div>
          </article>

          {/* Right rail */}
          <aside style={{position:'sticky',top:140,display:'flex',flexDirection:'column',gap:16}}>
            <div className="card" style={{padding:'18px 20px'}}>
              <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.08em',marginBottom:14}}>SHARE</div>
              <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
                {['X','LinkedIn','Bluesky','Copy link'].map(s => (
                  <button key={s} style={{padding:'5px 10px',borderRadius:6,fontSize:11,border:'1px solid var(--line)',color:'var(--ink-3)',fontFamily:'var(--mono)',letterSpacing:'0.04em'}}>{s}</button>
                ))}
              </div>
            </div>
            <div className="card" style={{padding:'18px 20px',background:'linear-gradient(135deg, rgba(212,255,58,0.06), transparent)'}}>
              <div className="mono" style={{fontSize:10,color:'var(--accent)',letterSpacing:'0.08em',marginBottom:10}}>NEWSLETTER</div>
              <div style={{fontSize:14,fontWeight:500,marginBottom:8}}>The Atoms</div>
              <div style={{fontSize:12,color:'var(--ink-3)',lineHeight:1.55,marginBottom:14}}>One essay, one tool, every other Friday.</div>
              <input placeholder="you@company.com" style={{width:'100%',padding:'8px 10px',borderRadius:6,background:'var(--bg-3)',border:'1px solid var(--line)',color:'var(--ink)',fontSize:12,fontFamily:'var(--sans)',outline:'none',marginBottom:8}}/>
              <button className="btn btn-primary" style={{width:'100%',justifyContent:'center',padding:'7px 10px',fontSize:12}}>Subscribe</button>
            </div>
          </aside>
        </div>
      </section>

      {/* Author bio */}
      <section style={{padding:'60px 0',borderTop:'1px solid var(--line)',borderBottom:'1px solid var(--line)',background:'var(--bg-2)'}}>
        <div className="container" style={{maxWidth:880}}>
          <div style={{display:'grid',gridTemplateColumns:'80px 1fr auto',gap:20,alignItems:'center'}}>
            <span style={{width:80,height:80,borderRadius:'50%',background:`linear-gradient(135deg, ${p.cover}66, ${p.cover}22)`,border:`1px solid ${p.cover}66`,display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--mono)',fontSize:22,fontWeight:600,color:p.cover}}>{p.author.split(' ').map(w=>w[0]).join('')}</span>
            <div>
              <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:6}}>WRITTEN BY</div>
              <div style={{fontSize:22,fontWeight:500,letterSpacing:'-0.015em',marginBottom:6}}>{p.author}</div>
              <div style={{fontSize:14,color:'var(--ink-2)',maxWidth:520,lineHeight:1.55}}>
                Engineering lead at SolidAtoms. Writes about systems, builds, and the gap between shipped and finished.
              </div>
            </div>
            <button className="btn btn-ghost" style={{padding:'8px 14px',fontSize:12}}>View profile {Icon.arrow()}</button>
          </div>
        </div>
      </section>

      {/* Related */}
      <section style={{padding:'80px 0'}}>
        <div className="container">
          <div className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:20}}>KEEP READING</div>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:24}}>
            {POSTS.filter(x=>x.id!==p.id).slice(0,3).map(np => (
              <article key={np.id} onClick={()=>{openPost(np);window.scrollTo({top:0})}} className="card clickable" style={{padding:0,overflow:'hidden'}}>
                <div style={{aspectRatio:'16/10',background:`linear-gradient(135deg, ${np.cover}33, #0a0a0a 80%)`,borderBottom:'1px solid var(--line)',position:'relative'}}>
                  <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
                    <span className="mono" style={{fontSize:13,color:np.cover,letterSpacing:'0.08em',opacity:0.7}}>{np.category.toUpperCase()}</span>
                  </div>
                </div>
                <div style={{padding:'20px 22px'}}>
                  <div style={{display:'flex',gap:8,marginBottom:10}}>
                    <Tag>{np.category}</Tag>
                    <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',alignSelf:'center'}}>{np.read}</span>
                  </div>
                  <h4 style={{fontSize:17,fontWeight:500,letterSpacing:'-0.015em',lineHeight:1.3}}>{np.title}</h4>
                </div>
              </article>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { BlogIndex, BlogPost });
