const { Button, Badge, Breadcrumbs, Callout } = window.ZaviFxDesignSystem_f15c31;

const CAT_ART = {
  SEO: 'radial-gradient(120% 100% at 78% 12%,#FFB870 0%,rgba(255,184,112,0) 58%),linear-gradient(150deg,#D93A12,#7A1F08)',
  Development: 'radial-gradient(110% 90% at 20% 20%,#8FB4FF 0%,rgba(143,180,255,0) 60%),linear-gradient(150deg,#1B2540,#0A0F1C)',
  'Link Building': 'radial-gradient(110% 90% at 80% 80%,#FFD79A 0%,rgba(255,215,154,0) 55%),linear-gradient(150deg,#8A4A12,#2C1607)',
  'UI/UX': 'radial-gradient(110% 90% at 30% 15%,#F2A0C4 0%,rgba(242,160,196,0) 60%),linear-gradient(150deg,#3B1230,#150612)',
  Branding: 'radial-gradient(120% 90% at 70% 20%,#FFC463 0%,rgba(255,196,99,0) 55%),linear-gradient(150deg,#4A2A08,#171008)',
  Performance: 'radial-gradient(110% 90% at 25% 80%,#7EE0C0 0%,rgba(126,224,192,0) 55%),linear-gradient(150deg,#0C3129,#04120F)',
  Content: 'radial-gradient(110% 90% at 75% 25%,#C9B6FF 0%,rgba(201,182,255,0) 58%),linear-gradient(150deg,#241A47,#0C0818)',
  'E-commerce': 'radial-gradient(110% 90% at 20% 25%,#FF9E7A 0%,rgba(255,158,122,0) 58%),linear-gradient(150deg,#5A1B0C,#1C0805)',
  Social: 'radial-gradient(110% 90% at 80% 30%,#9AD6FF 0%,rgba(154,214,255,0) 58%),linear-gradient(150deg,#0E2A44,#050F1A)',
  Analytics: 'radial-gradient(110% 90% at 30% 75%,#B9F0A0 0%,rgba(185,240,160,0) 55%),linear-gradient(150deg,#1B3312,#080F05)',
  Strategy: 'radial-gradient(120% 100% at 50% 10%,#FFCF8A 0%,rgba(255,207,138,0) 60%),linear-gradient(150deg,#3A2A12,#120D06)',
};
const art = (c) => CAT_ART[c] || CAT_ART.SEO;

function Cover({ cat, tall }) {
  return (
    <div className="zx-cover" data-tall={tall ? '' : undefined} style={{ background: art(cat) }}>
      <span className="zx-cover__grid" aria-hidden="true" />
      <span className="zx-cover__cat">{cat}</span>
      <img src={window.ASSETS + 'logo-zavifx-white.png'} alt="" className="zx-cover__mark" aria-hidden="true" />
    </div>
  );
}

function readSlug() {
  const h = location.hash.slice(1);
  return h.startsWith('insights/') ? h.slice(9) : null;
}

function ArticleView({ post, go, open }) {
  const related = window.POSTS.filter((p) => p.slug !== post.slug && p.cat === post.cat).slice(0, 2);
  const more = window.POSTS.filter((p) => p.slug !== post.slug && !related.includes(p)).slice(0, 3 - related.length);
  React.useEffect(() => { window.scrollTo(0, 0); }, [post.slug]);
  return (
    <article className="zx-art">
      <div className="zx-container zx-art__head" data-reveal>
        <Breadcrumbs items={[{ label: 'Insights', href: '#insights' }, { label: post.cat }, { label: post.title.slice(0, 28) + '…' }]} />
        <span className="zx-art__cat">{post.cat}</span>
        <h1 className="zx-art__title">{post.title}</h1>
        <p className="zx-art__lede">{post.excerpt}</p>
        <div className="zx-art__meta">
          <span>{new Date(post.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
          <span aria-hidden="true">·</span><span>{post.read} min read</span>
          <span aria-hidden="true">·</span><span>ZaviFx editorial team</span>
        </div>
      </div>
      <div className="zx-container"><Cover cat={post.cat} tall /></div>
      <div className="zx-container zx-art__body">
        <nav className="zx-art__toc" aria-label="On this page">
          <span>On this page</span>
          <ol>{post.body.map((s, i) => <li key={i}><a href={'#h' + i} onClick={(e) => { e.preventDefault(); const el = document.getElementById('h' + i); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 96, behavior: 'smooth' }); }}>{s[0]}</a></li>)}</ol>
        </nav>
        <div className="zx-prose">
          {post.body.map((sec, i) => (
            <section key={i}>
              <h2 id={'h' + i}>{sec[0]}</h2>
              {sec.slice(1).map((para, j) => <p key={j} dangerouslySetInnerHTML={{ __html: para }} />)}
              {i === 1 && <Callout variant="note">Working through this yourself? We publish the same checklists we use internally — no gated PDFs.</Callout>}
            </section>
          ))}
          <div className="zx-art__cta">
            <div>
              <strong>Want this reviewed on your site?</strong>
              <p>A 30-minute consultation and a written summary of what we would prioritise.</p>
            </div>
            <Button onClick={() => go('contact')}>Book a Free Consultation</Button>
          </div>
        </div>
      </div>
      <div className="zx-container zx-art__rel">
        <h2>Keep reading</h2>
        <div className="zx-art__relgrid">
          {[...related, ...more].map((p) => <PostCard key={p.slug} post={p} open={open} />)}
        </div>
      </div>
    </article>
  );
}

function PostCard({ post, open, feature }) {
  return (
    <a className="zx-post" data-feature={feature ? '' : undefined} href={'#insights/' + post.slug}
      onClick={(e) => { e.preventDefault(); open(post.slug); }} data-tilt>
      <Cover cat={post.cat} />
      <div className="zx-post__body">
        <span className="zx-post__cat">{post.cat}</span>
        <h3 className="zx-post__title"><span>{post.title}</span></h3>
        <p className="zx-post__ex">{post.excerpt}</p>
        <span className="zx-post__meta">{post.read} min read
          <i className="zx-post__go" aria-hidden="true">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M3.5 8h9M8.5 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </i>
        </span>
      </div>
    </a>
  );
}

function BlogPage({ go }) {
  const [slug, setSlug] = React.useState(readSlug());
  const [cat, setCat] = React.useState('All');
  React.useEffect(() => {
    const on = () => setSlug(readSlug());
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  const open = (s) => { location.hash = 'insights/' + s; setSlug(s); };
  const post = slug && window.POSTS.find((p) => p.slug === slug);
  if (post) return <ArticleView post={post} go={go} open={open} />;

  const cats = ['All', ...Array.from(new Set(window.POSTS.map((p) => p.cat)))];
  const list = cat === 'All' ? window.POSTS : window.POSTS.filter((p) => p.cat === cat);
  const [lead, ...rest] = list;
  return (
    <>
      <header className="zx-container zx-blog__head" data-reveal>
        <span className="zx-blog__eyebrow">Insights</span>
        <h1 className="zx-blog__h1">Notes on search, websites and growth</h1>
        <p className="zx-blog__intro">Practical write-ups from live client work — technical SEO, WordPress performance, design systems and paid media. Written by the people doing the work, not gated behind a form.</p>
        <div className="zx-blog__filters" role="tablist">
          {cats.map((c) => (
            <button key={c} type="button" role="tab" aria-selected={c === cat} className="zx-filter__pill" data-on={c === cat ? '' : undefined} onClick={() => setCat(c)}>
              {c}<em>{c === 'All' ? window.POSTS.length : window.POSTS.filter((p) => p.cat === c).length}</em>
            </button>
          ))}
        </div>
      </header>
      <div className="zx-container zx-blog__grid" data-reveal>
        {lead && <PostCard post={lead} open={open} feature />}
        {rest.map((p) => <PostCard key={p.slug} post={p} open={open} />)}
      </div>
    </>
  );
}
Object.assign(window, { BlogPage, PostCard, Cover });
