// Blog listing — content fetched from /api/posts?lang=X
// UI strings come from window.BLOG_T (blog-i18n.jsx), translations come from backend.

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

// GA4 tracking helper
function trackBlog(eventName, params) {
  try {
    if (typeof window.gtag === "function") window.gtag("event", eventName, params || {});
  } catch (e) {}
}

// ============================================================
//  Cover glyph — backend "cover_glyph" ile eşleşen SVG ikon
// ============================================================
function BlogCoverGlyph({ kind, accent, size = 120 }) {
  const props = { width: size, height: size, viewBox: "0 0 120 120", fill: "none", stroke: accent || "#ff6a2e", strokeWidth: 1.5 };
  const A = accent || "#ff6a2e";
  switch (kind) {
    case "cable":
      return (<svg {...props}><rect x="14" y="46" width="32" height="28" rx="3"/><rect x="20" y="52" width="20" height="8" rx="1" fill={A} opacity=".2"/>{[...Array(5)].map((_,i)=><rect key={i} x={22+i*3.5} y={62} width={2} height={6} fill={A} opacity=".8"/>)}<path d="M46 60 Q 60 40 74 60" strokeWidth="3" fill="none" opacity=".85"/><path d="M74 46 L 84 42 L 106 42 L 106 74 L 84 74 L 74 68 Z"/><rect x="82" y="52" width="22" height="12" rx="1" fill={A} opacity=".15"/></svg>);
    case "audio":
      return (<svg {...props}>{[20,30,40,50,60,70,80,90,100].map((x,i) => { const h = [20,40,70,50,90,50,70,40,20][i]; return <rect key={i} x={x-4} y={60-h/2} width={6} height={h} fill={A} opacity={0.4 + (i%3)*0.2} rx="1"/>;})}<circle cx="60" cy="60" r="48" opacity=".2"/><circle cx="60" cy="60" r="56" opacity=".1"/></svg>);
    case "battery":
      return (<svg {...props}><rect x="20" y="38" width="70" height="44" rx="4"/><rect x="90" y="48" width="6" height="24" rx="1" fill={A}/><rect x="24" y="42" width="62" height="36" rx="2" fill={A} opacity=".1"/><text x="55" y="66" fontSize="16" textAnchor="middle" fill={A} fontFamily="Space Grotesk" fontWeight="700">12V</text>{[35,50,65,80].map(x => <circle key={x} cx={x} cy="78" r="1.5" fill={A} opacity=".5"/>)}</svg>);
    case "compare":
      return (<svg {...props}><rect x="12" y="35" width="42" height="50" rx="4" fill={A} opacity=".08"/><rect x="66" y="35" width="42" height="50" rx="4" fill={A} opacity=".2"/><text x="33" y="64" fontSize="14" textAnchor="middle" fill={A} fontFamily="Space Grotesk" fontWeight="700">F30</text><text x="87" y="64" fontSize="14" textAnchor="middle" fill={A} fontFamily="Space Grotesk" fontWeight="700">G20</text><path d="M56 60 L 64 60 M60 56 L 64 60 L 60 64" strokeWidth="2"/></svg>);
    case "chart":
      return (<svg {...props}><polyline points="12,90 28,70 44,78 60,50 76,60 92,30 108,40" strokeWidth="2" fill="none"/><polyline points="12,90 28,70 44,78 60,50 76,60 92,30 108,40 108,100 12,100" fill={A} opacity=".15" stroke="none"/>{[28,60,92].map(x => <circle key={x} cx={x} cy={x===28?70:x===60?50:30} r="3" fill={A}/>)}<line x1="12" y1="100" x2="108" y2="100" opacity=".3"/></svg>);
    case "shield":
      return (<svg {...props}><path d="M60 18 L 96 32 L 96 60 Q 96 84 60 104 Q 24 84 24 60 L 24 32 Z" fill={A} opacity=".08"/><path d="M60 18 L 96 32 L 96 60 Q 96 84 60 104 Q 24 84 24 60 L 24 32 Z" strokeWidth="2"/><path d="M44 60 L 56 72 L 78 48" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>);
    // --- yeni: chip, obd, connection ---
    case "chip":
      return (<svg {...props}><rect x="30" y="30" width="60" height="60" rx="6" fill={A} opacity=".08"/><rect x="30" y="30" width="60" height="60" rx="6" strokeWidth="2"/><rect x="42" y="42" width="36" height="36" rx="2" fill={A} opacity=".25"/>{[40,50,60,70,80].map(y => (<g key={y}><line x1="18" y1={y} x2="30" y2={y} strokeWidth="2"/><line x1="90" y1={y} x2="102" y2={y} strokeWidth="2"/></g>))}{[40,50,60,70,80].map(x => (<g key={x}><line x1={x} y1="18" x2={x} y2="30" strokeWidth="2"/><line x1={x} y1="90" x2={x} y2="102" strokeWidth="2"/></g>))}<text x="60" y="65" fontSize="9" textAnchor="middle" fill={A} fontFamily="JetBrains Mono" fontWeight="700">ECU</text></svg>);
    case "obd":
      return (<svg {...props}><path d="M30 40 L 90 40 L 100 50 L 100 80 L 20 80 L 20 50 Z" fill={A} opacity=".1" stroke={A} strokeWidth="2"/>{[...Array(8)].map((_,i)=>(<g key={i}><circle cx={30+i*7} cy="55" r="2.5" fill={A} opacity=".8"/><circle cx={30+i*7} cy="70" r="2.5" fill={A} opacity=".5"/></g>))}<text x="60" y="100" fontSize="10" textAnchor="middle" fill={A} opacity=".7" fontFamily="JetBrains Mono" fontWeight="600">OBD-II</text></svg>);
    case "connection":
      return (<svg {...props}><circle cx="30" cy="60" r="6" fill={A}/><circle cx="90" cy="60" r="6" fill={A}/><path d="M36 60 Q 50 30 60 60 Q 70 90 84 60" strokeWidth="2.5" fill="none">{/* dalga benzeri akış */}</path>{[42,52,62,72].map((x,i) => <circle key={x} cx={x} cy={60 + (i%2?-6:6)} r="2" fill={A} opacity={0.3+(i*0.15)}/>)}<circle cx="30" cy="60" r="14" stroke={A} strokeWidth="1" fill="none" opacity=".25"/><circle cx="90" cy="60" r="14" stroke={A} strokeWidth="1" fill="none" opacity=".25"/></svg>);
    default:
      return null;
  }
}

// ============================================================
//  Logo + Nav (hamburger menu pattern, shared with home)
// ============================================================
function BlogLogo({ size = 40 }) {
  return (<a href="/" style={{display:"flex",alignItems:"center",gap:10}}>
    <img src="/assets/obdthink-logo.png" alt="OBDThink" width={size} height={size} style={{height:size,width:size,display:"block",borderRadius:size*0.22}}/>
  </a>);
}

function BlogNav({ t, lang, setLang, current = "blog" }) {
  const [menuOpen, setMenuOpen] = useStateB(false);
  const links = Object.entries(t.nav).filter(([k]) => k !== "download").map(([k,v]) => {
    const href = k === "adapters" ? `/${lang}/adapters` : k === "faq" ? `/${lang}/faq` : k === "blog" ? `/${lang}/blog` : `/#${k}`;
    return { k, v, href, active: k === current };
  });
  return (<nav className="site-nav" style={{position:"sticky",top:0,zIndex:100,background:"color-mix(in oklab, var(--bg) 80%, transparent)",backdropFilter:"blur(16px)",borderBottom:"1px solid var(--line)"}}>
    <div className="container site-nav-row" style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"18px 28px"}}>
      <div className="site-nav-left" style={{display:"flex",alignItems:"center",gap:40}}>
        <BlogLogo/>
        <div className="site-nav-links" style={{display:"flex",gap:28}}>
          {links.map(({k,v,href,active}) => (<a key={k} href={href} style={{fontSize:13,color:active?"var(--fg)":"var(--fg-dim)",fontWeight:active?600:500}}>{v}</a>))}
        </div>
      </div>
      <div className="site-nav-right" style={{display:"flex",alignItems:"center",gap:10}}>
        <LanguageMenu lang={lang} setLang={setLang}/>
        <a href="/#download" className="btn btn-primary site-nav-cta" style={{padding:"10px 16px",fontSize:13}}>{t.nav.download} →</a>
        <button className="site-nav-hamburger" aria-label="menu" aria-expanded={menuOpen} onClick={() => setMenuOpen(o => !o)}>
          <span style={{transform: menuOpen ? "translateY(6px) rotate(45deg)" : "none"}}/>
          <span style={{opacity: menuOpen ? 0 : 1}}/>
          <span style={{transform: menuOpen ? "translateY(-6px) rotate(-45deg)" : "none"}}/>
        </button>
      </div>
    </div>
    {menuOpen && (
      <div className="site-nav-mobile-panel">
        {links.map(({k,v,href,active}) => (<a key={k} href={href} style={{color: active ? "var(--accent)" : undefined}} onClick={() => setMenuOpen(false)}>{v}</a>))}
        <a href="/#download" className="btn btn-primary" style={{justifyContent:"center"}} onClick={() => setMenuOpen(false)}>{t.nav.download} →</a>
      </div>
    )}
  </nav>);
}

// ============================================================
//  Cover (template glyph veya custom upload)
// ============================================================
function BlogCover({ cover, label, size = 120 }) {
  if (cover.kind === "upload" && cover.image) {
    return (
      <div style={{position:"absolute",inset:0,backgroundImage:`url(${cover.image})`,backgroundSize:"cover",backgroundPosition:"center"}}>
        {label}
      </div>
    );
  }
  return (
    <div style={{background: cover.bg, position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center"}}>
      <BlogCoverGlyph kind={cover.glyph} accent={cover.accent} size={size}/>
      {label}
    </div>
  );
}

// ============================================================
//  Hero (featured)
// ============================================================
function BlogHero({ t, featured, lang }) {
  if (!featured) return null;
  return (<section className="carbon-bg" style={{padding:"80px 0 60px"}}>
    <div className="container">
      <div style={{maxWidth:820, marginBottom: 60}}>
        <div className="eyebrow" style={{marginBottom:20}}><span className="dot"/> {t.hero.eyebrow}</div>
        <h1 className="display" style={{fontSize:"clamp(44px, 6.5vw, 82px)",lineHeight:0.98,margin:0,fontWeight:600}}>
          {t.hero.title1}<br/><span style={{color:"var(--accent)"}}>{t.hero.title2}</span>
        </h1>
        <p style={{fontSize:18,color:"var(--fg-dim)",lineHeight:1.55,marginTop:24,maxWidth:680}}>{t.hero.sub}</p>
      </div>

      <a href={`/${lang}/blog/${featured.slug}`} className="blog-featured-card"
        onClick={() => trackBlog("blog_card_click", { post_slug: featured.slug, post_category: featured.category, source: "featured", lang })}
        style={{display:"grid",gridTemplateColumns:"1.1fr 1fr",gap:0,border:"1px solid var(--line-2)",borderRadius:16,overflow:"hidden",transition:"border-color .2s ease, transform .2s ease"}} onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--accent)"; }} onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line-2)"; }}>
        <div style={{aspectRatio:"16/11", position:"relative"}}>
          <BlogCover cover={featured.cover} size={160} label={
            <div style={{position:"absolute",top:20,left:20,padding:"6px 12px",background:"rgba(0,0,0,.5)",backdropFilter:"blur(10px)",borderRadius:6,fontFamily:"'JetBrains Mono', monospace",fontSize:11,letterSpacing:".12em",color:"var(--accent)",fontWeight:600}}>{t.labels.featured}</div>
          }/>
        </div>
        <div style={{padding:"44px 40px",display:"flex",flexDirection:"column",justifyContent:"center", background:"var(--bg-2)"}}>
          <div style={{display:"flex",gap:12,alignItems:"center",marginBottom:18,fontFamily:"'JetBrains Mono', monospace",fontSize:11,color:"var(--fg-mute)",letterSpacing:".08em",flexWrap:"wrap"}}>
            <span style={{textTransform:"uppercase",color:"var(--accent)"}}>{t.cats[featured.category] || featured.category}</span>
            <span>·</span>
            <span>{formatDate(featured.published_at, lang)}</span>
            <span>·</span>
            <span>{featured.read_min} {t.labels.readMin}</span>
          </div>
          <h2 className="display" style={{fontSize:32,lineHeight:1.1,margin:"0 0 14px",fontWeight:600}}>{featured.title}</h2>
          <p style={{fontSize:15,color:"var(--fg-dim)",lineHeight:1.55,margin:"0 0 24px"}}>{featured.summary || featured.excerpt}</p>
        </div>
      </a>
    </div>
  </section>);
}

// ============================================================
//  Blog card
// ============================================================
function BlogCard({ post, lang, t }) {
  return (<a href={`/${lang}/blog/${post.slug}`} className="blog-card"
    onClick={() => trackBlog("blog_card_click", { post_slug: post.slug, post_category: post.category, source: "list", lang })}
    style={{display:"flex",flexDirection:"column",border:"1px solid var(--line)",borderRadius:14,overflow:"hidden",transition:"border-color .2s ease, transform .2s ease",background:"var(--bg-2)"}} onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.transform = "translateY(-2px)"; }} onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.transform = "translateY(0)"; }}>
    <div style={{aspectRatio:"16/10", position:"relative"}}>
      <BlogCover cover={post.cover} size={96}/>
    </div>
    <div style={{padding:"22px 22px 24px",display:"flex",flexDirection:"column",flex:1}}>
      <div style={{display:"flex",gap:10,alignItems:"center",marginBottom:12,fontFamily:"'JetBrains Mono', monospace",fontSize:10,color:"var(--fg-mute)",letterSpacing:".08em"}}>
        <span style={{textTransform:"uppercase",color:"var(--accent)"}}>{t.cats[post.category] || post.category}</span>
        <span>·</span>
        <span>{post.read_min} {t.labels.readMin}</span>
      </div>
      <h3 className="display" style={{fontSize:19,lineHeight:1.25,margin:"0 0 10px",fontWeight:600,flex:1}}>{post.title}</h3>
      <p style={{fontSize:13.5,color:"var(--fg-dim)",lineHeight:1.55,margin:"0 0 16px"}}>{post.excerpt || post.summary}</p>
      <div style={{fontFamily:"'JetBrains Mono', monospace",fontSize:10,color:"var(--fg-mute)",letterSpacing:".06em",borderTop:"1px solid var(--line)",paddingTop:14,marginTop:"auto"}}>
        {formatDate(post.published_at, lang)}
      </div>
    </div>
  </a>);
}

function formatDate(dt, lang) {
  if (!dt) return "";
  try {
    return new Date(dt).toLocaleDateString(
      lang === "tr" ? "tr-TR" : lang === "de" ? "de-DE" : lang === "fr" ? "fr-FR" :
      lang === "es" ? "es-ES" : lang === "ru" ? "ru-RU" : lang === "pl" ? "pl-PL" :
      lang === "ar" ? "ar-SA" : "en-US",
      { year: "numeric", month: "short", day: "numeric" }
    );
  } catch (e) {
    return dt;
  }
}

// ============================================================
//  Grid (categorized listing, search-free MVP)
// ============================================================
function BlogGrid({ t, posts, loading, error, lang }) {
  const [cat, setCat] = useStateB("all");
  const filtered = useMemoB(() => {
    if (cat === "all") return posts;
    return posts.filter(p => p.category === cat);
  }, [cat, posts]);
  const cats = Object.entries(t.cats);
  const selectCat = (id) => {
    setCat(id);
    if (id !== "all") trackBlog("blog_filter_category", { category: id, lang });
  };
  return (<section style={{padding:"40px 0 80px"}}>
    <div className="container">
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",gap:20,flexWrap:"wrap",marginBottom:32}}>
        <div style={{display:"flex",gap:10,flexWrap:"wrap"}}>
          {cats.map(([id,label]) => (<button key={id} onClick={() => selectCat(id)} className={`filter-chip ${cat===id?"active":""}`}>{label}</button>))}
        </div>
      </div>
      {error ? (
        <div style={{textAlign:"center",padding:"80px 20px",color:"var(--danger, #ff5d4a)",fontSize:15}}>{error}</div>
      ) : loading ? (
        <div style={{textAlign:"center",padding:"80px 20px",color:"var(--fg-dim)",fontSize:15}}>…</div>
      ) : filtered.length === 0 ? (
        <div style={{textAlign:"center",padding:"80px 20px",color:"var(--fg-dim)",fontSize:15}}>{t.labels.empty}</div>
      ) : (
        <div className="blog-grid" style={{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:24}}>
          {filtered.map(p => (<BlogCard key={p.slug} post={p} lang={lang} t={t}/>))}
        </div>
      )}
    </div>
  </section>);
}

// ============================================================
//  Footer
// ============================================================
function BlogFooter({ t, lang }) {
  return (<footer style={{borderTop:"1px solid var(--line)",padding:"40px 0 28px",background:"var(--bg-2)"}}>
    <div className="container" style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:20}}>
      <div style={{display:"flex",alignItems:"center",gap:16}}>
        <BlogLogo size={36}/>
        <div style={{fontSize:12,color:"var(--fg-mute)",fontFamily:"'JetBrains Mono', monospace"}}>© {new Date().getFullYear()} OBDThink · {t.legal}</div>
      </div>
      <div style={{display:"flex",gap:24,fontSize:13,color:"var(--fg-dim)",flexWrap:"wrap"}}>
        <a href="/">{t.home}</a>
        <a href={`/${lang}/adapters`}>{t.nav.adapters}</a>
        <a href={`/${lang}/blog`} style={{color:"var(--fg)"}}>{t.nav.blog}</a>
        <a href={`/${lang}/faq`}>{t.nav.faq}</a>
        <a href="/privacy-policy">Privacy</a>
      </div>
    </div>
  </footer>);
}

// ============================================================
//  Root
// ============================================================
function BlogApp() {
  const [lang, setLang] = useStateB(() => {
    // Öncelik: SSR'dan gelen URL path lang > saved lang > "en"
    if (typeof window.__INITIAL_LANG__ === "string" && window.__INITIAL_LANG__) return window.__INITIAL_LANG__;
    return typeof readSharedLang === "function" ? readSharedLang() : "en";
  });
  const [posts, setPosts] = useStateB([]);
  const [featured, setFeatured] = useStateB(null);
  const [loading, setLoading] = useStateB(true);
  const [error, setError] = useStateB(null);

  useEffectB(() => {
    if (typeof writeSharedLang === "function") writeSharedLang(lang);
    document.documentElement.lang = lang;
    const tt = (window.BLOG_T?.[lang] || window.BLOG_T?.en)?.metaTitle;
    if (tt) document.title = tt;
  }, [lang]);

  useEffectB(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    Promise.all([
      fetch(`/api/posts?lang=${lang}&limit=50`).then(r => r.json()),
      fetch(`/api/posts/featured?lang=${lang}`).then(r => r.json()),
    ]).then(([listRes, featRes]) => {
      if (cancelled) return;
      if (listRes.ok) {
        setPosts(listRes.data.posts || []);
        trackBlog("blog_list_view", { lang, post_count: (listRes.data.posts || []).length });
      } else {
        setError(listRes.error?.message || "Failed to load posts");
      }
      if (featRes.ok && featRes.data.post) {
        setFeatured(featRes.data.post);
      } else {
        // Featured yoksa ilk listele
        if (listRes.ok && listRes.data.posts?.length) setFeatured(listRes.data.posts[0]);
      }
      setLoading(false);
    }).catch(err => {
      if (cancelled) return;
      setError(err.message || "Network error");
      setLoading(false);
    });
    return () => { cancelled = true; };
  }, [lang]);

  const t = (window.BLOG_T && window.BLOG_T[lang]) || (window.BLOG_T && window.BLOG_T.en) || {};
  // Featured zaten posts içinde — listede tekrar etmesin
  const gridPosts = featured ? posts.filter(p => p.slug !== featured.slug) : posts;

  return (<>
    <BlogNav t={t} lang={lang} setLang={setLang}/>
    <BlogHero t={t} featured={featured} lang={lang}/>
    <BlogGrid t={t} posts={gridPosts} loading={loading} error={error} lang={lang}/>
    <BlogFooter t={t} lang={lang}/>
  </>);
}

ReactDOM.createRoot(document.getElementById("root")).render(<BlogApp/>);
