/* Blog page shell: index + individual posts. Uses hash-based routing: #/blog, #/blog/post-slug */

const { useState: useStateB, useEffect: useEffectB } = React;

function useBlogRoute() {
  const [hash, setHash] = useStateB(window.location.hash || '');
  useEffectB(() => {
    const onChange = () => {
      setHash(window.location.hash || '');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  // returns { view: 'home'|'index'|'post', slug }
  if (hash.startsWith('#/blog/')) return { view: 'post', slug: hash.replace('#/blog/', '') };
  if (hash === '#/blog') return { view: 'index' };
  return { view: 'home' };
}

function BlogIndex() {
  return (
    <div className="relative">
      <div className="absolute inset-0 hero-grid pointer-events-none" aria-hidden="true"></div>
      <div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
        <div className="aurora aurora-a" style={{ opacity: 0.5 }}></div>
        <div className="aurora aurora-b" style={{ opacity: 0.4 }}></div>
      </div>

      <section className="relative pt-32 md:pt-40 pb-14">
        <div className="max-w-6xl mx-auto px-6 md:px-8">
          <div className="eyebrow mb-4 reveal">INSIGHTS & RESOURCES</div>
          <h1 className="h-display text-[48px] sm:text-[64px] lg:text-[76px] text-ink reveal">
            Notes from the <span style={{ color: '#5EEAD4' }}>intake layer.</span>
          </h1>
          <p className="mt-6 text-[17px] md:text-[18px] text-muted max-w-2xl reveal">
            Practical writing on intake automation, missed-call recovery, bilingual systems, and the operational mechanics of running a family-based immigration firm.
          </p>
        </div>
      </section>

      <div className="max-w-6xl mx-auto px-6 md:px-8"><div className="scanner"></div></div>

      <section className="relative py-16 md:py-20">
        <div className="max-w-6xl mx-auto px-6 md:px-8">
          {/* Featured (first post) */}
          <a href={`#/blog/${BLOG[0].id}`} className="block reveal group">
            <div className="glass glass-hover p-6 md:p-10 grid lg:grid-cols-[1fr_1.2fr] gap-8 lg:gap-12 items-center">
              <div className="aspect-[16/10] rounded-xl overflow-hidden relative" style={{ background: 'linear-gradient(135deg, rgba(94,234,212,0.15), rgba(167,139,250,0.15))', border: '1px solid rgba(255,255,255,0.05)' }}>
                <FeaturedGraphic seed={0} />
              </div>
              <div>
                <div className="flex items-center gap-3 font-mono text-[11px] text-faint uppercase tracking-wider">
                  <span style={{ color: '#5EEAD4' }}>● FEATURED</span>
                  <span>{BLOG[0].category}</span>
                  <span>·</span>
                  <span>{BLOG[0].readTime}</span>
                </div>
                <h2 className="mt-4 h-display text-[30px] md:text-[36px] text-ink group-hover:text-white transition-colors">
                  {BLOG[0].title}
                </h2>
                <p className="mt-4 text-[15.5px] leading-relaxed text-muted max-w-xl">{BLOG[0].dek}</p>
                <div className="mt-6 flex items-center gap-4">
                  <span className="font-mono text-[12px] text-faint">{BLOG[0].date}</span>
                  <span className="inline-flex items-center gap-1.5 text-[13.5px]" style={{ color: '#5EEAD4' }}>
                    Read article <Icon.Arrow size={14} />
                  </span>
                </div>
              </div>
            </div>
          </a>

          {/* Rest of posts */}
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5 mt-8">
            {BLOG.slice(1).map((post, i) => (
              <a key={post.id} href={`#/blog/${post.id}`} className="glass glass-hover p-6 block reveal group">
                <div className="aspect-[16/10] rounded-lg overflow-hidden mb-5 relative" style={{ background: 'linear-gradient(135deg, rgba(94,234,212,0.10), rgba(167,139,250,0.10))', border: '1px solid rgba(255,255,255,0.05)' }}>
                  <FeaturedGraphic seed={i + 1} />
                </div>
                <div className="flex items-center gap-3 font-mono text-[10.5px] text-faint uppercase tracking-wider">
                  <span style={{ color: '#5EEAD4' }}>{post.category}</span>
                  <span>·</span>
                  <span>{post.readTime}</span>
                </div>
                <h3 className="mt-3 h-display text-[20px] text-ink leading-snug">{post.title}</h3>
                <p className="mt-3 text-[14px] leading-relaxed text-muted line-clamp-3">{post.dek}</p>
                <div className="mt-5 pt-4 border-t border-white/5 flex items-center justify-between">
                  <span className="font-mono text-[11px] text-faint">{post.date}</span>
                  <span className="inline-flex items-center gap-1.5 text-[13px]" style={{ color: '#5EEAD4' }}>
                    Read <Icon.Arrow size={13} />
                  </span>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      <FinalCTA />
      <Footer />
    </div>
  );
}

function FeaturedGraphic({ seed = 0 }) {
  // Abstract generative-style glyph per post, consistent with brand.
  const palettes = [
    ['#5EEAD4', '#A78BFA'],
    ['#A78BFA', '#5EEAD4'],
    ['#5EEAD4', '#F59E0B'],
    ['#F59E0B', '#5EEAD4'],
    ['#A78BFA', '#F59E0B'],
    ['#5EEAD4', '#A78BFA'],
  ];
  const [a, b] = palettes[seed % palettes.length];
  const patterns = [
    // concentric rings
    (<g key="0">
      {[...Array(8)].map((_, i) => (
        <circle key={i} cx="50%" cy="50%" r={`${6 + i * 5}%`} fill="none" stroke={a} strokeWidth="1" opacity={0.15 + i * 0.05} />
      ))}
      <circle cx="50%" cy="50%" r="4%" fill={a} opacity="0.8"/>
    </g>),
    // grid of dots
    (<g key="1">
      {[...Array(10)].map((_, r) => [...Array(14)].map((_, c) => (
        <circle key={`${r}-${c}`} cx={`${(c + 1) * 6.5}%`} cy={`${(r + 1) * 9}%`} r="1" fill={c % 3 === 0 ? b : a} opacity={0.25 + (Math.sin(r * c) + 1) * 0.2} />
      )))}
    </g>),
    // waveform
    (<g key="2">
      {[...Array(40)].map((_, i) => {
        const h = 20 + Math.abs(Math.sin(i * 0.5)) * 50;
        return <rect key={i} x={`${i * 2.4 + 2}%`} y={`${50 - h/2}%`} width="1%" height={`${h}%`} fill={i % 4 === 0 ? b : a} opacity="0.55" rx="1"/>
      })}
    </g>),
    // diagonal lines
    (<g key="3">
      {[...Array(20)].map((_, i) => (
        <line key={i} x1={`${i * 6 - 20}%`} y1="0%" x2={`${i * 6 + 10}%`} y2="100%" stroke={i % 3 === 0 ? b : a} strokeWidth="1" opacity="0.35"/>
      ))}
    </g>),
    // hex lattice-ish
    (<g key="4">
      {[...Array(6)].map((_, r) => [...Array(9)].map((_, c) => (
        <polygon key={`${r}-${c}`}
          points={`${c*12 + (r%2)*6},${r*18 + 10} ${c*12 + 5 + (r%2)*6},${r*18 + 6} ${c*12 + 10 + (r%2)*6},${r*18 + 10} ${c*12 + 10 + (r%2)*6},${r*18 + 16} ${c*12 + 5 + (r%2)*6},${r*18 + 20} ${c*12 + (r%2)*6},${r*18 + 16}`}
          fill="none" stroke={(r+c) % 3 === 0 ? b : a} strokeWidth="0.5" opacity="0.5"/>
      )))}
    </g>),
    // orbit
    (<g key="5">
      <ellipse cx="50%" cy="50%" rx="45%" ry="18%" fill="none" stroke={a} strokeWidth="1" opacity="0.4"/>
      <ellipse cx="50%" cy="50%" rx="30%" ry="42%" fill="none" stroke={b} strokeWidth="1" opacity="0.4"/>
      <ellipse cx="50%" cy="50%" rx="40%" ry="40%" fill="none" stroke={a} strokeWidth="1" opacity="0.2"/>
      <circle cx="50%" cy="50%" r="5%" fill={b} opacity="0.8"/>
    </g>),
  ];
  return (
    <svg viewBox="0 0 100 62.5" preserveAspectRatio="xMidYMid slice" className="absolute inset-0 w-full h-full">
      {patterns[seed % patterns.length]}
    </svg>
  );
}

function BlogPost({ slug }) {
  const post = BLOG.find(p => p.id === slug);
  if (!post) {
    return (
      <div className="min-h-[70vh] flex items-center justify-center">
        <div className="text-center">
          <div className="eyebrow mb-3">404</div>
          <div className="h-display text-[32px]">Post not found.</div>
          <a href="#/blog" className="mt-6 inline-flex items-center gap-2 btn-ghost rounded-full px-5 py-2.5 text-[14px]">
            <Icon.Arrow size={14} style={{ transform: 'rotate(180deg)' }} /> Back to blog
          </a>
        </div>
      </div>
    );
  }

  // Other posts to suggest
  const more = BLOG.filter(p => p.id !== slug).slice(0, 3);

  return (
    <div className="relative">
      <div className="absolute top-0 inset-x-0 h-[420px] overflow-hidden pointer-events-none" aria-hidden="true">
        <div className="aurora aurora-a" style={{ opacity: 0.35 }}></div>
        <div className="aurora aurora-b" style={{ opacity: 0.3 }}></div>
      </div>

      <article className="relative max-w-3xl mx-auto px-6 md:px-8 pt-32 md:pt-36 pb-16">
        <a href="#/blog" className="inline-flex items-center gap-2 font-mono text-[12px] text-muted hover:text-ink transition-colors mb-10">
          <span style={{ transform: 'rotate(180deg)', display: 'inline-block' }}><Icon.Arrow size={14} /></span>
          Back to all posts
        </a>

        <div className="flex items-center gap-3 font-mono text-[11px] text-faint uppercase tracking-wider mb-6">
          <span style={{ color: '#5EEAD4' }}>{post.category}</span>
          <span>·</span>
          <span>{post.date}</span>
          <span>·</span>
          <span>{post.readTime}</span>
        </div>

        <h1 className="h-display text-[36px] md:text-[52px] text-ink leading-[1.05]">{post.title}</h1>
        <p className="mt-6 text-[18px] md:text-[20px] leading-relaxed text-muted">{post.dek}</p>

        <div className="mt-10 aspect-[16/8] rounded-xl overflow-hidden relative" style={{ background: 'linear-gradient(135deg, rgba(94,234,212,0.15), rgba(167,139,250,0.15))', border: '1px solid rgba(255,255,255,0.05)' }}>
          <FeaturedGraphic seed={BLOG.findIndex(p => p.id === slug)} />
        </div>

        <div className="mt-12 space-y-6">
          {post.body.map((block, i) => {
            if (block.type === 'h2') {
              return <h2 key={i} className="h-display text-[26px] md:text-[30px] text-ink mt-10 mb-0">{block.text}</h2>;
            }
            if (block.type === 'callout') {
              return (
                <div key={i} className="my-10 glass p-6 md:p-7 relative">
                  <div className="absolute left-0 top-6 bottom-6 w-[2px] rounded-full" style={{ background: 'linear-gradient(to bottom, #5EEAD4, #A78BFA)' }}></div>
                  <p className="pl-4 text-[16.5px] md:text-[17.5px] leading-relaxed text-ink italic">{block.text}</p>
                </div>
              );
            }
            return <p key={i} className="text-[16.5px] md:text-[17px] leading-[1.75] text-ink/85">{block.text}</p>;
          })}
        </div>

        {/* End of article CTA */}
        <div className="mt-16 glass p-7 md:p-9">
          <div className="font-mono text-[11px] tracking-wider uppercase text-faint mb-2">NEXT STEP</div>
          <h3 className="h-display text-[24px] md:text-[28px]">
            See these ideas running on a real firm's call pattern.
          </h3>
          <p className="mt-2 text-[15px] text-muted">30-minute demo. No pitch deck.</p>
          <div className="mt-5 flex flex-wrap gap-3">
            <a href="#final-cta" onClick={() => { window.location.hash = ''; }} className="btn-primary inline-flex items-center gap-2 rounded-full px-5 py-3 text-[14px]">
              Book a demo <Icon.Arrow size={15} />
            </a>
            <a href="#/blog" className="btn-ghost inline-flex items-center gap-2 rounded-full px-5 py-3 text-[14px]">
              More posts
            </a>
          </div>
        </div>
      </article>

      {/* More posts */}
      <section className="relative py-16 md:py-24 border-t border-white/5">
        <div className="max-w-6xl mx-auto px-6 md:px-8">
          <div className="flex items-baseline justify-between mb-10">
            <h3 className="h-display text-[24px] md:text-[28px]">Keep reading</h3>
            <a href="#/blog" className="font-mono text-[12px] text-muted hover:text-ink transition-colors">All posts →</a>
          </div>
          <div className="grid md:grid-cols-3 gap-5">
            {more.map((p) => {
              const idx = BLOG.findIndex(x => x.id === p.id);
              return (
                <a key={p.id} href={`#/blog/${p.id}`} className="glass glass-hover p-5 block">
                  <div className="aspect-[16/10] rounded-lg overflow-hidden mb-4 relative" style={{ background: 'linear-gradient(135deg, rgba(94,234,212,0.10), rgba(167,139,250,0.10))', border: '1px solid rgba(255,255,255,0.05)' }}>
                    <FeaturedGraphic seed={idx} />
                  </div>
                  <div className="font-mono text-[10.5px] text-faint uppercase tracking-wider" style={{ color: '#5EEAD4' }}>{p.category}</div>
                  <div className="mt-2 h-display text-[17px] leading-snug text-ink">{p.title}</div>
                  <div className="mt-3 font-mono text-[11px] text-faint">{p.date} · {p.readTime}</div>
                </a>
              );
            })}
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}

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