/* Blog post — standalone page, served at /blog/:slug (clean URLs) */

const { useState, useEffect } = React;

/* ── Inline Header ── */
const BPHeader = () => {
  const [scrolled, setScrolled] = React.useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);
  return (
    <header className={`fixed top-0 inset-x-0 z-40 border-b transition-colors duration-300 ${scrolled ? 'bg-bone/95 backdrop-blur-md border-sand/60' : 'bg-bone/95 backdrop-blur-md border-sand/60'}`}>
      <div className="max-w-[1280px] mx-auto px-6 md:px-10 h-16 flex items-center justify-between">
        <a href="/" className="flex items-center gap-2.5 text-ink">
          <svg width="26" height="26" viewBox="0 0 56 56" aria-hidden="true">
            <circle cx="28" cy="28" r="24" fill="none" stroke="#1F4E4D" strokeWidth="2.2" opacity=".65"/>
            <path d="M28 4 A24 24 0 0 1 52 28" fill="none" stroke="#E8745C" strokeWidth="3" strokeLinecap="round"/>
            <circle cx="28" cy="28" r="3.4" fill="#1F1D1A"/>
          </svg>
          <span className="font-serif text-[22px] tracking-display font-medium">
            Conceive <em className="italic font-normal opacity-75">Iberia</em>
          </span>
        </a>
        <nav className="hidden md:flex items-center gap-7 text-[13.5px] text-inksoft">
          <a href="/" className="hover:text-teal transition-colors">Home</a>
          <a href="/#/blog" className="hover:text-teal transition-colors">Blog</a>
          <a href="/resources" className="hover:text-teal transition-colors">Guides</a>
          <a href="/#/quiz" className="inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-[13px] font-medium bg-ink text-bone hover:bg-teal transition-colors">
            Take the quiz
          </a>
        </nav>
      </div>
    </header>
  );
};

/* ── Inline Footer ── */
const BPFooter = () => (
  <footer className="border-t border-sand/60 bg-teal text-bone mt-0">
    <div className="max-w-[1280px] mx-auto px-6 md:px-10 py-14 flex flex-col md:flex-row justify-between gap-8 text-[13.5px]">
      <div>
        <a href="/" className="flex items-center gap-2 text-bone">
          <svg width="20" height="20" viewBox="0 0 56 56" aria-hidden="true">
            <circle cx="28" cy="28" r="24" fill="none" stroke="#FBF9F5" strokeWidth="2.5" opacity=".55"/>
            <path d="M28 4 A24 24 0 0 1 52 28" fill="none" stroke="#E8745C" strokeWidth="3.4" strokeLinecap="round"/>
            <circle cx="28" cy="28" r="3.8" fill="#FBF9F5"/>
          </svg>
          <span className="font-serif text-[20px] tracking-display">Conceive <em className="italic font-normal">Iberia</em></span>
        </a>
        <p className="mt-3 text-bone/65 max-w-xs leading-relaxed">Free, unbiased IVF clinic matching for American patients in Spain.</p>
      </div>
      <div className="flex gap-12 text-bone/70">
        <div>
          <div className="font-medium text-bone mb-3">Explore</div>
          <ul className="space-y-2">
            <li><a href="/#/how-it-works" className="hover:text-bone transition-colors">How it works</a></li>
            <li><a href="/#/quiz" className="hover:text-bone transition-colors">Take the quiz</a></li>
            <li><a href="/#/calculator" className="hover:text-bone transition-colors">Cost calculator</a></li>
            <li><a href="/#/concierge" className="hover:text-bone transition-colors">Concierge</a></li>
          </ul>
        </div>
        <div>
          <div className="font-medium text-bone mb-3">Resources</div>
          <ul className="space-y-2">
            <li><a href="/#/blog" className="hover:text-bone transition-colors">Blog</a></li>
            <li><a href="/resources" className="hover:text-bone transition-colors">IVF Guides</a></li>
            <li><a href="/best-ivf-clinics-spain" className="hover:text-bone transition-colors">Best clinics</a></li>
            <li><a href="/ivf-spain-cost" className="hover:text-bone transition-colors">Cost guide</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div className="border-t border-bone/15 px-6 md:px-10 py-4 max-w-[1280px] mx-auto flex justify-between text-[12px] text-bone/40">
      <span>© 2026 Conceive Iberia</span>
      <span>Madrid · Barcelona · Valencia · Alicante · Marbella</span>
    </div>
  </footer>
);

/* ── Markdown Renderer (mirrors blog.jsx) ── */
const MarkdownRenderer = ({ content }) => {
  const lines = content.split('\n');
  const elements = [];
  let i = 0;
  let kc = 0;
  const key = (p) => `${p}-${kc++}`;

  while (i < lines.length) {
    const line = lines[i];
    if (line.trim() === '') { i++; continue; }

    if (line.startsWith('# ')) {
      elements.push(<h1 key={key('h1')} className="font-serif text-[38px] leading-[0.95] tracking-display text-ink mb-5">{line.slice(2)}</h1>);
      i++; continue;
    }
    if (line.startsWith('## ')) {
      elements.push(<h2 key={key('h2')} className="font-serif text-[26px] md:text-[30px] tracking-display leading-tight text-ink mt-12 mb-4">{line.slice(3)}</h2>);
      i++; continue;
    }
    if (line.startsWith('### ')) {
      elements.push(<h3 key={key('h3')} className="font-serif text-[20px] md:text-[22px] tracking-display leading-tight text-ink mt-8 mb-3">{line.slice(4)}</h3>);
      i++; continue;
    }
    if (line.startsWith('**') && line.endsWith('**') && line.length > 4) {
      elements.push(<p key={key('bold')} className="font-semibold text-[16px] text-ink mt-6 mb-2">{line.slice(2, -2)}</p>);
      i++; continue;
    }

    // Inline image
    if (/^!\[.*?\]\(.*?\)/.test(line)) {
      const m = line.match(/^!\[(.*?)\]\((.*?)\)/);
      if (m) {
        elements.push(
          <figure key={key('img')} className="my-10">
            <img src={m[2]} alt={m[1]} className="w-full rounded-2xl object-cover" style={{maxHeight:'420px'}} loading="lazy"/>
            {m[1] && <figcaption className="mt-2.5 text-center text-[13px] text-inksoft/50 italic">{m[1]}</figcaption>}
          </figure>
        );
      }
      i++; continue;
    }

    // Table
    if (line.includes('|') && line.trim().startsWith('|')) {
      const tableLines = [];
      while (i < lines.length && lines[i].includes('|')) { tableLines.push(lines[i]); i++; }
      const headerCells = tableLines[0].split('|').filter(c => c.trim() !== '');
      const bodyRows = tableLines.slice(2).map(r => r.split('|').filter(c => c.trim() !== ''));
      elements.push(
        <div key={key('table')} className="my-8 overflow-x-auto rounded-xl border border-sand">
          <table className="w-full text-[14px]">
            <thead><tr className="bg-cream">{headerCells.map((c, ci) => <th key={ci} className="text-left px-4 py-3 font-semibold text-ink border-b border-sand">{c.trim().replace(/\*\*/g,'')}</th>)}</tr></thead>
            <tbody>{bodyRows.map((row, ri) => <tr key={ri} className={ri%2===0?'bg-bone':'bg-cream/50'}>{row.map((cell, ci) => <td key={ci} className="px-4 py-3 text-inksoft border-b border-sand/60">{cell.trim().replace(/\*\*/g,'')}</td>)}</tr>)}</tbody>
          </table>
        </div>
      );
      continue;
    }

    // Bullet list
    if (line.startsWith('- ') || line.startsWith('* ')) {
      const items = [];
      while (i < lines.length && (lines[i].startsWith('- ') || lines[i].startsWith('* '))) {
        items.push(lines[i].slice(2)); i++;
      }
      elements.push(
        <ul key={key('ul')} className="my-4 space-y-2 pl-0">
          {items.map((item, idx) => {
            const parts = item.split(/\*\*(.*?)\*\*/g);
            return <li key={idx} className="flex gap-3 text-[15.5px] text-inksoft leading-relaxed"><span className="mt-2 flex-shrink-0 w-1.5 h-1.5 rounded-full bg-teal"/><span>{parts.map((p,pi) => pi%2===1 ? <strong key={pi} className="text-ink font-semibold">{p}</strong> : p)}</span></li>;
          })}
        </ul>
      );
      continue;
    }

    // Numbered list
    if (/^\d+\. /.test(line)) {
      const items = [];
      while (i < lines.length && /^\d+\. /.test(lines[i])) { items.push(lines[i].replace(/^\d+\. /,'')); i++; }
      elements.push(
        <ol key={key('ol')} className="my-4 space-y-2 pl-0">
          {items.map((item, idx) => {
            const parts = item.split(/\*\*(.*?)\*\*/g);
            return <li key={idx} className="flex gap-4 text-[15.5px] text-inksoft leading-relaxed"><span className="flex-shrink-0 w-6 h-6 mt-0.5 rounded-full bg-teal/10 text-teal text-[12px] font-mono font-semibold flex items-center justify-center">{idx+1}</span><span>{parts.map((p,pi) => pi%2===1 ? <strong key={pi} className="text-ink font-semibold">{p}</strong> : p)}</span></li>;
          })}
        </ol>
      );
      continue;
    }

    const parts = line.split(/\*\*(.*?)\*\*/g);
    elements.push(<p key={key('p')} className="text-[16px] leading-[1.75] text-inksoft my-3">{parts.map((p,pi) => pi%2===1 ? <strong key={pi} className="text-ink font-semibold">{p}</strong> : p)}</p>);
    i++;
  }
  return <div>{elements}</div>;
};

/* ── Main App ── */
const App = () => {
  // Extract slug from /blog/slug
  const slug = window.location.pathname.replace(/^\/blog\/?/, '').replace(/\/$/, '');

  // Merge base articles (defined inline below) with window.EXTRA_ARTICLES
  const BASE_SLUGS = [
    'ivf-spain-vs-usa-comparison',
    'how-to-evaluate-fertility-marketplace',
    'complete-guide-ivf-spain-american-patients',
    'complete-guide-donor-egg-ivf-spain',
    'day-by-day-ivf-cycle-spain',
  ];

  // For the 5 original articles, redirect to the SPA hash route (they live in blog.jsx)
  // For all 26 new articles, render here
  const extraArticles = window.EXTRA_ARTICLES || [];
  const article = extraArticles.find(a => a.slug === slug);

  // Update page title + meta
  if (article) {
    document.title = `${article.title} — Conceive Iberia`;
    const metaDesc = document.getElementById('meta-desc');
    if (metaDesc) metaDesc.setAttribute('content', article.excerpt || '');
    const canonical = document.getElementById('canonical');
    if (canonical) canonical.setAttribute('href', `https://conceive-iberia.com/blog/${slug}`);
  }

  if (!article) {
    // If it's one of the original 5, redirect to SPA route
    if (BASE_SLUGS.includes(slug)) {
      window.location.replace(`/#/blog/${slug}`);
      return null;
    }
    return (
      <div className="min-h-screen bg-bone flex flex-col">
        <BPHeader/>
        <div className="flex-1 flex items-center justify-center pt-24">
          <div className="text-center px-6">
            <p className="text-inksoft mb-4">Article not found.</p>
            <a href="/#/blog" className="text-teal underline">Back to blog</a>
          </div>
        </div>
        <BPFooter/>
      </div>
    );
  }

  const otherArticles = extraArticles.filter(a => a.slug !== slug).slice(0, 3);

  return (
    <div className="min-h-screen bg-bone flex flex-col">
      <BPHeader/>

      {/* Cover image if present */}
      {article.cover && (
        <div className="pt-16">
          <div className="w-full h-[320px] md:h-[420px] overflow-hidden">
            <img src={article.cover} alt={article.title} className="w-full h-full object-cover" loading="eager"/>
          </div>
        </div>
      )}

      {/* Article header */}
      <section className={`px-6 md:px-10 pb-12 border-b border-sand ${article.cover ? 'pt-10' : 'pt-28'}`}>
        <div className="max-w-[760px] mx-auto">
          <a href="/#/blog" className="inline-flex items-center gap-2 text-[13px] text-teal mb-8 hover:underline">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="15 18 9 12 15 6"/>
            </svg>
            All articles
          </a>
          <div className="flex items-center gap-3 mb-5">
            <span className="text-[11px] uppercase tracking-[0.2em] text-teal font-medium">{article.tag}</span>
            <span className="w-1 h-1 rounded-full bg-sand"/>
            <span className="text-[13px] text-inksoft/60">{article.date}</span>
            <span className="w-1 h-1 rounded-full bg-sand"/>
            <span className="text-[13px] text-inksoft/60">{article.readTime}</span>
          </div>
          <h1 className="font-serif text-[38px] md:text-[52px] leading-[1.0] tracking-display text-ink mb-6">
            {article.title}
          </h1>
          <p className="text-[17px] text-inksoft leading-relaxed max-w-[640px]">{article.excerpt}</p>
        </div>
      </section>

      {/* Article body */}
      <section className="px-6 md:px-10 py-14 flex-1">
        <div className="max-w-[720px] mx-auto">
          <MarkdownRenderer content={article.content}/>

          {/* Bottom CTA */}
          <div className="mt-16 p-7 md:p-9 rounded-2xl bg-teal text-bone">
            <span className="font-mono text-[11px] tracking-[0.22em] uppercase text-bone/60">Ready to start?</span>
            <h3 className="mt-3 font-serif text-[28px] md:text-[34px] tracking-display leading-tight">
              Find your matched clinic in 5 minutes. Free.
            </h3>
            <p className="mt-3 text-[15px] text-bone/75 max-w-lg leading-relaxed">
              Answer 12 questions about your medical profile. We return 2–3 vetted Spanish clinics that genuinely fit — with a written rationale for each.
            </p>
            <div className="mt-6">
              <a href="/#/quiz" className="inline-flex items-center gap-2 rounded-full px-6 py-3.5 bg-coral text-ink font-medium text-[15px] hover:opacity-90 transition-opacity">
                Take the matching quiz
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* More articles */}
      {otherArticles.length > 0 && (
        <section className="px-6 md:px-10 pb-20 border-t border-sand pt-12">
          <div className="max-w-[1100px] mx-auto">
            <span className="font-mono text-[11px] tracking-[0.22em] uppercase text-inksoft/60">More reading</span>
            <h2 className="mt-3 font-serif text-[32px] tracking-display mb-8">More from the blog</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {otherArticles.map(a => (
                <a key={a.slug} href={`/blog/${a.slug}`} className="group p-6 rounded-2xl border border-sand hover:border-teal/40 transition-colors bg-cream">
                  {a.cover && <div className="w-full h-[140px] rounded-xl overflow-hidden mb-4"><img src={a.cover} alt={a.title} className="w-full h-full object-cover"/></div>}
                  <span className="text-[11px] uppercase tracking-[0.2em] text-teal/80">{a.tag}</span>
                  <h3 className="mt-2 font-serif text-[19px] tracking-display leading-tight group-hover:text-teal transition-colors">{a.title}</h3>
                  <p className="mt-2 text-[13.5px] text-inksoft/70 leading-relaxed line-clamp-3">{a.excerpt}</p>
                  <div className="mt-4 text-[12px] text-inksoft/50">{a.readTime}</div>
                </a>
              ))}
            </div>
          </div>
        </section>
      )}

      <BPFooter/>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
