/* Blog app — list / detail of Muhammet Özekes's LinkedIn posts.
   Source: window.BLOG_POSTS (built from assets/muhammet_ozekes_posts.md). */

const PAGE_SIZE = 12;
const TR_MONTHS = ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran',
                   'Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];

function trDate(iso){
  const d = new Date(iso + 'T00:00:00');
  if (isNaN(d)) return iso;
  return `${d.getDate()} ${TR_MONTHS[d.getMonth()]} ${d.getFullYear()}`;
}

function shortDate(iso){
  const d = new Date(iso + 'T00:00:00');
  if (isNaN(d)) return iso;
  const pad = n => String(n).padStart(2,'0');
  return `${pad(d.getDate())}.${pad(d.getMonth()+1)}.${d.getFullYear()}`;
}

function readMinutes(body){
  const wpm = 200;
  const w = (body || '').split(/\s+/).filter(Boolean).length;
  return Math.max(1, Math.round(w / wpm));
}

function getSlugFromHash(){
  const m = (window.location.hash || '').match(/^#yazi\/(.+)$/);
  return m ? decodeURIComponent(m[1]) : null;
}

// Build a compact pagination sequence: 1 … current-1 current current+1 … last
function buildPageSeq(current, total){
  if (total <= 7){
    return Array.from({length: total}, (_, i) => i + 1);
  }
  const seq = [];
  const push = v => { if (seq[seq.length-1] !== v) seq.push(v); };
  push(1);
  if (current > 3) push('…');
  for (let i = Math.max(2, current-1); i <= Math.min(total-1, current+1); i++){
    push(i);
  }
  if (current < total - 2) push('…');
  push(total);
  return seq;
}

function BlogApp(){
  // Merge LinkedIn posts (BLOG_POSTS) with the longer pieces / law-blog
  // articles (YAZILAR), newest first. YAZILAR items may carry a `pdf` link
  // and a `topic` label instead of an inline body.
  const all = [...(window.BLOG_POSTS || []), ...(window.YAZILAR || [])]
    .sort((a, b) => (a.date < b.date ? 1 : (a.date > b.date ? -1 : 0)));
  const [search, setSearch] = React.useState('');
  const [page, setPage] = React.useState(1);
  const [slug, setSlug] = React.useState(getSlugFromHash);
  const listTopRef = React.useRef(null);
  const isInitial = React.useRef(true);

  React.useEffect(() => {
    const onHash = () => {
      setSlug(getSlugFromHash());
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Smooth-scroll the list back to its top whenever the page changes
  React.useEffect(() => {
    if (isInitial.current){ isInitial.current = false; return; }
    if (slug) return;
    const el = listTopRef.current;
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 90;
    window.scrollTo({ top, behavior: 'smooth' });
  }, [page]);

  // Detail view
  if (slug){
    const post = all.find(p => p.slug === slug);
    if (!post){
      return (
        <div className="container" style={{padding:'80px 0'}}>
          <p style={{fontFamily:'var(--serif)', fontSize:24, fontStyle:'italic'}}>
            Yazı bulunamadı.
          </p>
          <a href="#" onClick={(e)=>{e.preventDefault(); window.location.hash='';}}
             className="btn btn-ghost">← Tüm yazılara dön</a>
        </div>
      );
    }
    // PDF-linked pieces have no inline body: offer the file instead.
    if (post.pdf){
      const titleStr = window.tn ? window.tn(post.title) : post.title;
      return (
        <article className="post-detail">
          <div className="container">
            <a href="#" onClick={(e)=>{e.preventDefault(); window.location.hash='';}}
               className="post-back">← Tüm yazılar</a>
            <div className="post-meta-line">
              <span>{post.topic || 'Yazı'}</span>
              <span>{trDate(post.date)}</span>
            </div>
            <h1 className="post-title">{titleStr}</h1>
            <div className="post-body">
              <p><a href={post.pdf} target="_blank" rel="noopener"
                    className="btn btn-primary">PDF'i aç →</a></p>
            </div>
          </div>
        </article>
      );
    }
    const idx = all.indexOf(post);
    const prev = all[idx + 1]; // older
    const next = all[idx - 1]; // newer
    const titleStr = window.tn ? window.tn(post.title) : post.title;
    const bodyStr  = window.tn ? window.tn(post.body)  : post.body;
    const paragraphs = bodyStr.split(/\n\n+/).map(s => s.trim()).filter(Boolean);
    return (
      <article className="post-detail">
        <div className="container">
          <a href="#" onClick={(e)=>{e.preventDefault(); window.location.hash='';}}
             className="post-back">← Tüm yazılar</a>

          <div className="post-meta-line">
            <span>{post.topic || 'Not'}</span>
            <span>{trDate(post.date)}</span>
            <span>{readMinutes(bodyStr)} {window.t ? window.t('blog.read-min') : 'dk okuma'}</span>
            {post.edited && <span>· düzenlendi</span>}
          </div>

          <h1 className="post-title">{titleStr}</h1>

          <div className="post-body">
            {paragraphs.map((para, i) => <p key={i}>{para}</p>)}
          </div>

          <div className="post-nav">
            {next ? (
              <a href={`#yazi/${next.slug}`} className="post-nav-card">
                <span className="dir">← Yeni yazı</span>
                <span className="ttl">{window.tn ? window.tn(next.title) : next.title}</span>
              </a>
            ) : <span/>}
            {prev ? (
              <a href={`#yazi/${prev.slug}`} className="post-nav-card right">
                <span className="dir">Eski yazı →</span>
                <span className="ttl">{window.tn ? window.tn(prev.title) : prev.title}</span>
              </a>
            ) : <span/>}
          </div>
        </div>
      </article>
    );
  }

  // List view
  const filtered = search.trim()
    ? all.filter(p => {
        const s = search.toLowerCase();
        const t = (window.tn ? window.tn(p.title) : p.title) || '';
        const b = (window.tn ? window.tn(p.body)  : p.body)  || '';
        return t.toLowerCase().includes(s) || b.toLowerCase().includes(s);
      })
    : all;

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const paged = filtered.slice((safePage-1)*PAGE_SIZE, safePage*PAGE_SIZE);
  const pageSeq = buildPageSeq(safePage, totalPages);

  return (
    <React.Fragment>
      <div className="container">
        <div className="blog-search">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
          </svg>
          <input
            placeholder="Yazılarda ara…"
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
          />
          <span className="count">{filtered.length} yazı</span>
        </div>
      </div>

      <section className="archive" ref={listTopRef}>
        <div className="container">
          {paged.length === 0 ? (
            <div style={{padding:'80px 0', textAlign:'center'}}>
              <p style={{fontFamily:'var(--serif)', fontSize:24, fontStyle:'italic',
                         color:'var(--ink-mute)'}}>Bu aramaya uygun yazı bulunamadı.</p>
            </div>
          ) : (
            <div className="archive-list">
              {paged.map((p, i) => {
                const n = (safePage-1)*PAGE_SIZE + i + 1;
                const isPdf = !!p.pdf;
                const linkProps = isPdf
                  ? { href: p.pdf, target: '_blank', rel: 'noopener' }
                  : { href: `#yazi/${p.slug}` };
                return (
                  <a key={p.id} {...linkProps} className="article-row">
                    <span className="num">{String(n).padStart(3,'0')}</span>
                    <span className="topic">{p.topic || 'Not'}</span>
                    <span className="title">
                      {window.tn ? window.tn(p.title) : p.title}
                      <em>{((window.tn ? window.tn(p.excerpt) : p.excerpt) || '').slice(0, 160)}…</em>
                    </span>
                    <span className="date">{shortDate(p.date)}</span>
                    <span className="read">{isPdf ? 'PDF' : `${readMinutes(window.tn ? window.tn(p.body) : p.body)} ${window.t ? window.t('blog.min') : 'dk'}`}</span>
                    <span className="arr">→</span>
                  </a>
                );
              })}
            </div>
          )}

          {totalPages > 1 && (
            <div className="pagination">
              <button className="clearbtn" style={{width:'auto', padding:'10px 18px'}}
                disabled={safePage===1}
                onClick={()=>setPage(p=>Math.max(1, p-1))}>{window.t ? window.t('page.prev') : '← Önceki'}</button>
              <div className="page-numbers">
                {pageSeq.map((n, i) =>
                  n === '…'
                    ? <span key={`dots-${i}`} className="ellipsis">…</span>
                    : (
                      <button key={n} className={n===safePage ? 'active' : ''}
                        onClick={()=>setPage(n)}>{n}</button>
                    )
                )}
              </div>
              <button className="clearbtn" style={{width:'auto', padding:'10px 18px'}}
                disabled={safePage===totalPages}
                onClick={()=>setPage(p=>Math.min(totalPages, p+1))}>{window.t ? window.t('page.next') : 'Sonraki →'}</button>
            </div>
          )}
        </div>
      </section>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('blog-app')).render(<BlogApp />);
