/* BLOG — engineering notes / ADR / open-source.
   Posts loaded from /api/blog (public, published only) and /api/blog/post/:slug.
   Body uses Markdown-light: "## H" → h2, "- " → list item (grouped), other lines → paragraph. */

function fmtDate(s) {
  const d = new Date(s);
  return d.toLocaleDateString('ru-RU', { year: 'numeric', month: 'long', day: 'numeric' });
}

function parseSlug() {
  const m = window.location.pathname.match(/^\/blog\/([^\/]+)\/?$/);
  return m ? decodeURIComponent(m[1]) : null;
}

// Parse Markdown-light body into blocks for safe React rendering.
// Headings:   lines starting with "## "  → { type:'h', text }
// List items: lines starting with "- "   → grouped into { type:'ul', items }
// Other:      non-empty lines            → { type:'p', text }
// Empty lines act as separators (end of list group).
function parseBody(text) {
  const lines = String(text || '').split(/\r?\n/);
  const blocks = [];
  let listBuf = null;
  const flushList = () => { if (listBuf) { blocks.push({ type: 'ul', items: listBuf }); listBuf = null; } };
  for (const raw of lines) {
    const line = raw.trim();
    if (!line) { flushList(); continue; }
    if (/^##\s+/.test(line)) {
      flushList();
      blocks.push({ type: 'h', text: line.replace(/^##\s+/, '') });
    } else if (/^[-*]\s+/.test(line)) {
      if (!listBuf) listBuf = [];
      listBuf.push(line.replace(/^[-*]\s+/, ''));
    } else {
      flushList();
      blocks.push({ type: 'p', text: line });
    }
  }
  flushList();
  return blocks;
}

function BlogHeader() {
  return (
    <header style={{
      padding: '36px 0',
      borderBottom: '1px solid var(--line)',
      marginBottom: 48,
    }}>
      <div className="container" style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16}}>
        <a href="/" className="nav-logo">
          <span className="mark"><img src="/assets/scutoid.png" alt=""/></span>
          <span>D-one <span style={{color:'var(--ink-2)'}}>studio</span></span>
        </a>
        <div style={{display: 'flex', gap: 16, alignItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-2)'}}>
          <a href="/blog" style={{color: 'var(--ink-1)'}}>/ blog</a>
          <a href="/#cases">/ кейсы</a>
          <a href="/#contact">/ контакт</a>
        </div>
      </div>
    </header>
  );
}

function BlogIndex() {
  const [posts, setPosts] = React.useState(null); // null = loading
  React.useEffect(() => {
    fetch('/api/blog', { credentials: 'same-origin' })
      .then(r => r.ok ? r.json() : Promise.reject(r))
      .then(d => setPosts(d.posts || []))
      .catch(() => setPosts([]));
  }, []);

  return (
    <React.Fragment>
      <BlogHeader/>
      <div className="container blog-container">
        <div className="section-head">
          <h2>Инженерные заметки. <span className="italic">ADR, разборы, open-source.</span></h2>
          <div className="num">/ BLOG</div>
        </div>
        {posts === null ? (
          <div style={{padding: '80px 0', color: 'var(--ink-2)', fontFamily: 'var(--font-mono)', fontSize: 13}}>Загрузка…</div>
        ) : posts.length === 0 ? (
          <div style={{padding: '80px 0', color: 'var(--ink-2)'}}>
            Заметок пока нет. Скоро появятся.
          </div>
        ) : (
          <div className="blog-list">
            {posts.map(p => (
              <a key={p.slug} href={'/blog/' + p.slug} className="blog-card">
                <div className="blog-card-meta">
                  <span>{fmtDate(p.date)}</span>
                  <span className="blog-card-tags">{(p.tags || []).map(t => '#' + t).join(' ')}</span>
                </div>
                <h3 className="blog-card-title">{p.title}</h3>
                <p className="blog-card-excerpt">{p.excerpt}</p>
                <span className="blog-card-read">читать →</span>
              </a>
            ))}
          </div>
        )}
      </div>
    </React.Fragment>
  );
}

function BlogPost({ slug }) {
  const [state, setState] = React.useState({ loading: true, post: null });

  React.useEffect(() => {
    setState({ loading: true, post: null });
    fetch('/api/blog/post/' + encodeURIComponent(slug), { credentials: 'same-origin' })
      .then(r => r.ok ? r.json() : Promise.reject(r))
      .then(d => {
        setState({ loading: false, post: d.post });
        if (d.post && d.post.title) document.title = d.post.title + ' — D-one studio';
      })
      .catch(() => setState({ loading: false, post: null }));
  }, [slug]);

  if (state.loading) {
    return (
      <React.Fragment>
        <BlogHeader/>
        <div className="container" style={{padding: '80px 0', color: 'var(--ink-2)', fontFamily: 'var(--font-mono)', fontSize: 13}}>Загрузка…</div>
      </React.Fragment>
    );
  }
  if (!state.post) {
    return (
      <React.Fragment>
        <BlogHeader/>
        <div className="container" style={{padding: '120px 0', textAlign: 'center'}}>
          <h2 style={{fontSize: 48, letterSpacing: '-0.03em'}}>Заметка не найдена</h2>
          <p style={{color: 'var(--ink-2)', marginTop: 16}}>
            <a href="/blog">← все заметки</a>
          </p>
        </div>
      </React.Fragment>
    );
  }
  const post = state.post;
  const blocks = parseBody(post.body);
  return (
    <React.Fragment>
      <BlogHeader/>
      <article className="container blog-container blog-post">
        <a href="/blog" className="blog-back">← все заметки</a>
        <div className="blog-post-meta">
          <span>{fmtDate(post.date)}</span>
          <span>{(post.tags || []).map(t => '#' + t).join(' ')}</span>
        </div>
        <h1 className="blog-post-title">{post.title}</h1>
        <div className="blog-post-body">
          {blocks.map((b, i) => {
            if (b.type === 'h') return <h2 key={i}>{b.text}</h2>;
            if (b.type === 'p') return <p key={i}>{b.text}</p>;
            if (b.type === 'ul') return <ul key={i}>{b.items.map((it, j) => <li key={j}>{it}</li>)}</ul>;
            return null;
          })}
        </div>
        <div className="blog-post-cta">
          Понравился разбор? Можем сделать такое для вашего продукта.<br/>
          <a href="/#contact" className="btn-primary" style={{marginTop: 16, padding: '14px 22px'}}>Обсудить проект</a>
        </div>
      </article>
    </React.Fragment>
  );
}

function BlogApp() {
  React.useEffect(() => {
    document.body.classList.add('native-cursor');
    return () => document.body.classList.remove('native-cursor');
  }, []);

  const slug = parseSlug();
  return slug ? <BlogPost slug={slug}/> : <BlogIndex/>;
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.Fragment>
    <div className="bg-stage"/>
    <div className="bg-grid"/>
    <div className="bg-noise"/>
    <BlogApp/>
  </React.Fragment>
);
