// Blog post detail — fetched from /api/posts/<slug>?lang=X
// Slug PHP server-render'dan window.__BLOG_SLUG__ olarak gelir.

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP, useRef: useRefP } = React;

// ============================================================
//  GA4 tracking helper — gtag global'i blog-post.php'de yüklendi
// ============================================================
function track(eventName, params) {
  try {
    if (typeof window.gtag === "function") {
      window.gtag("event", eventName, params || {});
    }
  } catch (e) { /* sessiz */ }
}

// ============================================================
//  Logo + Nav (hamburger pattern with shared LanguageMenu)
// ============================================================
function PostLogo({ 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 PostNav({ t, lang, setLang }) {
  const [menuOpen, setMenuOpen] = useStateP(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 === "blog" };
  });
  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}}>
        <PostLogo/>
        <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 renderer + 9 glyph (blog.jsx ile aynı)
// ============================================================
function PostCoverGlyph({ kind, accent, size = 120 }) {
  // Aynı kütüphane — blog.jsx'teki ile birebir
  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>);
    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"/>{[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;
  }
}

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: "long", day: "numeric" }
    );
  } catch (e) { return dt; }
}

// ============================================================
//  Not found
// ============================================================
// ============================================================
//  Top banner — her blog yazısının ÜSTÜNDE (yazıdan önce) gösterilir.
//  Arka plan: /assets/blog-cta-bg.jpg (yoksa bg-2 + gradient fallback).
//  Metin: dile göre blog-i18n.jsx > t.topBanner (eyebrow, title, btn).
// ============================================================
function PostTopBanner({ t }) {
  if (!t || !t.topBanner) return null;
  const tb = t.topBanner;
  const c = t.cta || {};
  const APP_STORE_URL  = "https://apps.apple.com/app/obdthink-for-bmw/id6754601889";
  const PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=com.obdthink.tekincode";
  return (
    <section style={{
      position: "relative",
      backgroundColor: "var(--bg-2)",
      backgroundImage: "linear-gradient(135deg, rgba(7,9,12,0.78) 0%, rgba(7,9,12,0.45) 50%, rgba(7,9,12,0.78) 100%), url('/assets/blog-cta-bg.jpg')",
      backgroundSize: "cover",
      backgroundPosition: "center",
      backgroundRepeat: "no-repeat",
      borderBottom: "1px solid var(--line)",
      overflow: "hidden",
    }}>
      <div className="container" style={{padding: "72px 28px", position: "relative", zIndex: 1, textAlign: "center"}}>
        <div className="eyebrow" style={{marginBottom: 22}}>
          <span className="dot"/> {tb.eyebrow}
        </div>
        <h2 className="display" style={{
          fontSize: "clamp(26px, 4vw, 42px)",
          lineHeight: 1.15,
          margin: "0 auto 32px",
          maxWidth: 760,
          fontWeight: 700,
          color: "var(--fg)",
          textShadow: "0 2px 16px rgba(0,0,0,0.5)",
        }}>{tb.title}</h2>
        <div style={{display:"inline-flex",gap:14,flexWrap:"wrap",justifyContent:"center"}}>
          <a href={APP_STORE_URL} target="_blank" rel="noopener noreferrer"
             onClick={() => track("blog_top_banner_store_click", { store: "app_store", post_slug: window.__BLOG_SLUG__ || "" })}
             style={storeBtn}>
            <AppleIcon size={28}/>
            <span style={storeText}>
              <span style={storeTop}>{c.iosTop || "Download on the"}</span>
              <span style={storeBottom}>{c.iosBottom || "App Store"}</span>
            </span>
          </a>
          <a href={PLAY_STORE_URL} target="_blank" rel="noopener noreferrer"
             onClick={() => track("blog_top_banner_store_click", { store: "google_play", post_slug: window.__BLOG_SLUG__ || "" })}
             style={storeBtn}>
            <PlayIcon size={28}/>
            <span style={storeText}>
              <span style={storeTop}>{c.androidTop || "Get it on"}</span>
              <span style={storeBottom}>{c.androidBottom || "Google Play"}</span>
            </span>
          </a>
        </div>
      </div>
    </section>
  );
}

function PostNotFound({ t, lang }) {
  return (<section className="carbon-bg" style={{padding:"140px 0", textAlign:"center"}}>
    <div className="container">
      <div className="mono" style={{fontSize:72,color:"var(--accent)",fontWeight:700,lineHeight:1}}>404</div>
      <h1 className="display" style={{fontSize:"clamp(32px, 5vw, 48px)",margin:"20px 0 12px",fontWeight:600}}>{t.labels.notFound || "Post not found"}</h1>
      <p style={{fontSize:17,color:"var(--fg-dim)",margin:"0 auto 32px",maxWidth:480,lineHeight:1.5}}>{t.labels.notFoundSub || "The post you're looking for doesn't exist or has been removed."}</p>
      <a href={`/${lang}/blog`} className="btn btn-primary">← {t.labels.backToBlog}</a>
    </div>
  </section>);
}

// ============================================================
//  Hero with summary card and author byline
// ============================================================
function PostHero({ post, t, lang, fallbackBanner }) {
  const heroBg = post.cover.kind === "upload" && post.cover.image
    ? `linear-gradient(rgba(0,0,0,.55), rgba(0,0,0,.85)), url(${post.cover.image})`
    : post.cover.bg;
  return (<section style={{padding:"64px 0 40px", background: heroBg, backgroundSize:"cover", backgroundPosition:"center", position:"relative", overflow:"hidden", borderBottom:"1px solid var(--line)"}}>
    <div style={{position:"absolute",inset:0,background:"radial-gradient(800px 400px at 50% 100%, rgba(0,0,0,.4), transparent)"}}/>
    <div className="container" style={{position:"relative",zIndex:1, maxWidth: 860}}>
      <a href={`/${lang}/blog`} style={{display:"inline-flex",alignItems:"center",gap:8,fontSize:13,color:"var(--fg-dim)",marginBottom:32,fontFamily:"'JetBrains Mono', monospace"}}>← {t.labels.backToBlog}</a>

      {fallbackBanner && (
        <div style={{marginBottom:24,padding:"10px 14px",background:"color-mix(in oklab, var(--warn) 12%, transparent)",border:"1px solid color-mix(in oklab, var(--warn) 30%, transparent)",borderRadius:8,fontSize:13,color:"var(--warn)",fontFamily:"'JetBrains Mono', monospace"}}>{t.labels.langFallback}</div>
      )}

      <div style={{display:"flex",gap:12,alignItems:"center",marginBottom:24,fontFamily:"'JetBrains Mono', monospace",fontSize:11,color:"var(--fg-mute)",letterSpacing:".08em",flexWrap:"wrap"}}>
        <span style={{textTransform:"uppercase",color: post.cover.accent || "var(--accent)", fontWeight:600}}>{t.cats[post.category] || post.category}</span>
        <span>·</span>
        <span>{formatDate(post.published_at, lang)}</span>
        <span>·</span>
        <span>{post.read_min} {t.labels.readMin}</span>
      </div>

      <h1 className="display" style={{fontSize:"clamp(36px, 5.5vw, 64px)",lineHeight:1.02,margin:"0 0 24px",fontWeight:600,letterSpacing:"-0.025em"}}>{post.title}</h1>

      {/* Author byline */}
      <div style={{display:"flex",alignItems:"center",gap:12,fontFamily:"'JetBrains Mono', monospace",fontSize:13,color:"var(--fg-mute)",marginBottom:32}}>
        <div style={{width:36,height:36,borderRadius:"50%",background:"color-mix(in oklab, " + (post.cover.accent || "#ff6a2e") + " 30%, transparent)",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:700,color:post.cover.accent || "var(--accent)",fontSize:13}}>{post.author_initials || "TC"}</div>
        <div>
          <div style={{color:"var(--fg)",fontWeight:600}}>{post.author_name || "Tekin Code"}</div>
          <div style={{fontSize:11,marginTop:2}}>{formatDate(post.published_at, lang)}</div>
        </div>
      </div>

      {/* Summary kartı — kullanıcının tüm yazıyı okumadan anlaması için */}
      {post.summary && (
        <div style={{padding:"22px 26px",background:"color-mix(in oklab, var(--accent) 8%, var(--bg-2))",border:"1px solid color-mix(in oklab, var(--accent) 30%, transparent)",borderRadius:12,marginBottom:8}}>
          <div className="mono" style={{fontSize:10,letterSpacing:".14em",textTransform:"uppercase",color:"var(--accent)",marginBottom:8,fontWeight:600}}>TL;DR</div>
          <p style={{fontSize:17,color:"var(--fg)",lineHeight:1.5,margin:0}}>{post.summary}</p>
        </div>
      )}
    </div>
  </section>);
}

// ============================================================
//  YouTube embed veya "yakında" mockup player
// ============================================================
function PostVideo({ post, t }) {
  // Sadece tutorial/coding kategorilerinde mockup göster (yoksa hiç render etme)
  const showMockup = !post.youtube_id && (post.category === "tutorial" || post.category === "coding");
  if (!post.youtube_id && !showMockup) return null;

  return (<section style={{padding:"32px 0 0"}}>
    <div className="container" style={{maxWidth:860}}>
      {post.youtube_id ? (
        <div style={{position:"relative",paddingBottom:"56.25%",height:0,borderRadius:14,overflow:"hidden",border:"1px solid var(--line-2)"}}>
          <iframe
            src={`https://www.youtube.com/embed/${post.youtube_id}`}
            title={post.title}
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            style={{position:"absolute",inset:0,width:"100%",height:"100%",border:0}}
          />
        </div>
      ) : (
        // Coming soon mockup
        <div style={{position:"relative",paddingBottom:"56.25%",height:0,borderRadius:14,overflow:"hidden",border:"1px dashed var(--line-2)",background:"linear-gradient(135deg, var(--bg-2) 0%, var(--bg-3) 100%)"}}>
          <div style={{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:16}}>
            <div style={{position:"absolute",top:16,left:16,padding:"4px 10px",background:"rgba(0,0,0,.6)",borderRadius:6,fontFamily:"'JetBrains Mono', monospace",fontSize:10,letterSpacing:".12em",color:"var(--accent)",fontWeight:700}}>TC</div>
            <div style={{width:80,height:80,borderRadius:"50%",border:"2px solid var(--accent)",display:"flex",alignItems:"center",justifyContent:"center",background:"color-mix(in oklab, var(--accent) 12%, transparent)"}}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="var(--accent)"><path d="M8 5v14l11-7z"/></svg>
            </div>
            <div style={{fontFamily:"'JetBrains Mono', monospace",fontSize:13,letterSpacing:".08em",color:"var(--fg-dim)",textTransform:"uppercase"}}>{t.labels.videoComingSoon || "Video coming soon"}</div>
          </div>
        </div>
      )}
    </div>
  </section>);
}

// ============================================================
//  Content blocks
// ============================================================
function PostContent({ post, t }) {
  const [copied, setCopied] = useStateP(false);
  const copy = () => {
    navigator.clipboard.writeText(window.location.href);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
    track("blog_share_link_copied", { post_slug: post.slug });
  };
  const content = post.content || [];
  const headings = useMemoP(() => content.filter(b => b.type === "h2").map((b,i) => ({ id: `h-${i}`, text: b.text })), [content]);
  let h2idx = -1;
  return (<section style={{padding:"60px 0 80px"}}>
    <div className="container blog-post-grid" style={{display:"grid",gridTemplateColumns:"1fr 240px",gap:60,maxWidth:1080}}>
      <article style={{maxWidth:720, fontSize:17, lineHeight:1.7, color:"var(--fg-dim)"}}>
        {content.map((block, i) => {
          if (block.type === "p") return (<p key={i} style={{margin:"0 0 24px"}}>{block.text}</p>);
          if (block.type === "h2") { h2idx++; return (<h2 key={i} id={`h-${h2idx}`} className="display" style={{color:"var(--fg)",fontSize:28,fontWeight:600,margin:"44px 0 18px",lineHeight:1.2,letterSpacing:"-0.02em"}}>{block.text}</h2>); }
          if (block.type === "ul") return (<ul key={i} style={{margin:"0 0 24px",paddingLeft:0,listStyle:"none"}}>{(block.items||[]).map((it,j) => (<li key={j} style={{position:"relative",paddingLeft:24,marginBottom:10}}><span style={{position:"absolute",left:0,top:10,width:8,height:8,background:"var(--accent)",borderRadius:"2px",transform:"rotate(45deg)"}}/>{it}</li>))}</ul>);
          if (block.type === "code") return (<pre key={i} style={{margin:"0 0 24px",padding:"18px 22px",background:"var(--bg-2)",border:"1px solid var(--line)",borderLeft:"3px solid var(--accent)",borderRadius:8,fontFamily:"'JetBrains Mono', monospace",fontSize:13.5,color:"var(--fg)",overflow:"auto",lineHeight:1.6}}>{block.text}</pre>);
          if (block.type === "callout") {
            const c = block.kind === "warn" ? "var(--warn)" : block.kind === "ok" ? "var(--ok)" : "var(--accent)";
            const icon = block.kind === "warn" ? "⚠" : block.kind === "ok" ? "✓" : "ℹ";
            return (<div key={i} style={{margin:"0 0 24px",padding:"18px 22px",background:`color-mix(in oklab, ${c} 6%, transparent)`,border:`1px solid color-mix(in oklab, ${c} 30%, transparent)`,borderRadius:10,display:"flex",gap:14,alignItems:"flex-start"}}>
              <span style={{color:c,fontSize:20,lineHeight:1,marginTop:2,fontWeight:700}}>{icon}</span>
              <span style={{color:"var(--fg)",fontSize:15,lineHeight:1.6}}>{block.text}</span>
            </div>);
          }
          if (block.type === "image" && block.url) {
            return (<figure key={i} style={{margin:"0 0 28px"}}>
              <img src={block.url} alt={block.alt || ""} style={{width:"100%",borderRadius:10,border:"1px solid var(--line)"}}/>
              {block.caption && <figcaption style={{textAlign:"center",fontSize:13,color:"var(--fg-mute)",marginTop:10,fontFamily:"'JetBrains Mono', monospace"}}>{block.caption}</figcaption>}
            </figure>);
          }
          if (block.type === "youtube" && block.id) {
            return (<div key={i} style={{position:"relative",paddingBottom:"56.25%",height:0,marginBottom:28,borderRadius:10,overflow:"hidden",border:"1px solid var(--line-2)"}}>
              <iframe src={`https://www.youtube.com/embed/${block.id}`} allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen style={{position:"absolute",inset:0,width:"100%",height:"100%",border:0}}/>
            </div>);
          }
          return null;
        })}

        {/* Tags */}
        {Array.isArray(post.tags) && post.tags.length > 0 && (
          <div style={{marginTop:48,paddingTop:32,borderTop:"1px solid var(--line)",display:"flex",flexWrap:"wrap",gap:8}}>
            {post.tags.map(tag => (<span key={tag} style={{padding:"5px 10px",background:"var(--bg-2)",border:"1px solid var(--line)",borderRadius:6,fontFamily:"'JetBrains Mono', monospace",fontSize:11,color:"var(--fg-dim)",letterSpacing:".04em"}}>#{tag}</span>))}
          </div>
        )}
      </article>

      {/* Sidebar */}
      <aside style={{position:"sticky",top:100,alignSelf:"start",height:"fit-content"}}>
        {headings.length > 0 && (<div style={{paddingBottom:24,marginBottom:24,borderBottom:"1px solid var(--line)"}}>
          <div style={{fontFamily:"'JetBrains Mono', monospace",fontSize:10,letterSpacing:".14em",color:"var(--fg-mute)",marginBottom:14,textTransform:"uppercase"}}>{t.labels.toc || "Contents"}</div>
          <ol style={{margin:0,padding:0,listStyle:"none"}}>
            {headings.map((h,i) => (<li key={h.id} style={{marginBottom:10,fontSize:13,lineHeight:1.4}}>
              <a href={`#${h.id}`} style={{color:"var(--fg-dim)",display:"flex",gap:10}}>
                <span className="mono" style={{color:"var(--fg-mute)",fontSize:11}}>{String(i+1).padStart(2,"0")}</span>
                <span>{h.text}</span>
              </a>
            </li>))}
          </ol>
        </div>)}
        <div>
          <div style={{fontFamily:"'JetBrains Mono', monospace",fontSize:10,letterSpacing:".14em",color:"var(--fg-mute)",marginBottom:14,textTransform:"uppercase"}}>{t.labels.share || "Share"}</div>
          <button onClick={copy} style={{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:"var(--bg-2)",border:"1px solid var(--line-2)",borderRadius:8,color:"var(--fg)",fontSize:12,cursor:"pointer",width:"100%",textAlign:"left",transition:"border-color .15s ease"}} onMouseEnter={e=>e.currentTarget.style.borderColor="var(--accent)"} onMouseLeave={e=>e.currentTarget.style.borderColor="var(--line-2)"}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
            <span>{copied ? (t.labels.copied || "Copied!") : (t.labels.copy || "Copy link")}</span>
          </button>
        </div>
      </aside>
    </div>
  </section>);
}

// ============================================================
//  Related posts
// ============================================================
function RelatedPosts({ related, t, lang, fromPost }) {
  if (!related || related.length === 0) return null;
  return (<section style={{padding:"60px 0 80px", borderTop:"1px solid var(--line)", background:"var(--bg-2)"}}>
    <div className="container">
      <div className="eyebrow" style={{marginBottom:24}}><span className="dot"/> {t.labels.related || "Related"}</div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))",gap:20}}>
        {related.map(r => (<a key={r.slug} href={`/${lang}/blog/${r.slug}`}
          onClick={() => track("blog_related_click", { from_slug: fromPost, to_slug: r.slug, lang })}
          style={{display:"flex",flexDirection:"column",gap:12,padding:"20px 22px",border:"1px solid var(--line)",borderRadius:12,background:"var(--bg)",transition:"border-color .2s ease"}} onMouseEnter={e=>e.currentTarget.style.borderColor="var(--accent)"} onMouseLeave={e=>e.currentTarget.style.borderColor="var(--line)"}>
          <div style={{display:"flex",gap:10,alignItems:"center",fontFamily:"'JetBrains Mono', monospace",fontSize:10,color:"var(--fg-mute)",letterSpacing:".08em",textTransform:"uppercase"}}>
            <span style={{color:r.cover.accent || "var(--accent)"}}>{t.cats[r.category] || r.category}</span>
            <span>·</span>
            <span>{r.read_min} {t.labels.readMin}</span>
          </div>
          <h3 className="display" style={{fontSize:17,lineHeight:1.25,margin:0,fontWeight:600,color:"var(--fg)"}}>{r.title}</h3>
          <p style={{fontSize:13,color:"var(--fg-dim)",lineHeight:1.55,margin:0}}>{r.excerpt}</p>
        </a>))}
      </div>
    </div>
  </section>);
}

// ============================================================
//  CTA + Footer
// ============================================================
// Apple + Google Play SVG icons (inline — bağımsız)
function AppleIcon({ size = 22 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="currentColor" aria-hidden="true">
      <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
    </svg>
  );
}
function PlayIcon({ size = 22 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden="true">
      <defs>
        <linearGradient id="play_a" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#00d4ff"/><stop offset="100%" stopColor="#0080a8"/>
        </linearGradient>
        <linearGradient id="play_b" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#ffc83d"/><stop offset="100%" stopColor="#ff8a00"/>
        </linearGradient>
        <linearGradient id="play_c" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#ff6a2e"/><stop offset="100%" stopColor="#d11414"/>
        </linearGradient>
        <linearGradient id="play_d" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#58ff9a"/><stop offset="100%" stopColor="#1a8038"/>
        </linearGradient>
      </defs>
      <path d="M3.6 1.8c-.4.2-.6.6-.6 1v18.4c0 .4.2.8.6 1l9.6-10.2L3.6 1.8z" fill="url(#play_a)"/>
      <path d="M16.8 9l-3.6 3 3.6 3 3.5-2c.8-.5.8-1.5 0-2l-3.5-2z" fill="url(#play_b)"/>
      <path d="M3.6 22.2c.4.2.9.2 1.4-.1l12.4-7.1-3.6-3-10.2 10.2z" fill="url(#play_c)"/>
      <path d="M3.6 1.8L13.8 12l3.6-3L5 1.9c-.5-.3-1-.3-1.4-.1z" fill="url(#play_d)"/>
    </svg>
  );
}

function PostCta({ t, post }) {
  const APP_STORE_URL  = "https://apps.apple.com/app/obdthink-for-bmw/id6754601889";
  const PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=com.obdthink.tekincode";
  const c = t.cta || {};
  return (<section style={{
    padding:"96px 0",
    borderTop:"1px solid var(--line)",
    textAlign:"center",
    background: "radial-gradient(800px 500px at 50% 50%, color-mix(in oklab, var(--accent) 8%, transparent) 0%, transparent 70%)",
  }}>
    <div className="container" style={{maxWidth: 720}}>
      <div className="eyebrow" style={{marginBottom: 20}}>
        <span className="dot"/> OBDThink
      </div>
      <h2 className="display" style={{fontSize:"clamp(28px, 4vw, 42px)",margin:0,fontWeight:600,lineHeight:1.15,letterSpacing:"-0.02em"}}>
        {c.title || "Try this in your own car."}
      </h2>
      <p style={{fontSize:17,color:"var(--fg-dim)",margin:"18px auto 36px",maxWidth:560,lineHeight:1.5}}>
        {c.sub || "Discover the OBDThink mobile app — free to install."}
      </p>
      <div className="blog-cta-stores" style={{display:"inline-flex",gap:14,flexWrap:"wrap",justifyContent:"center"}}>
        <a href={APP_STORE_URL} target="_blank" rel="noopener noreferrer"
           onClick={() => track("blog_cta_store_click", { store: "app_store", from_post: post?.slug, post_category: post?.category })}
           style={storeBtn}>
          <AppleIcon size={28}/>
          <span style={storeText}>
            <span style={storeTop}>{c.iosTop || "Download on the"}</span>
            <span style={storeBottom}>{c.iosBottom || "App Store"}</span>
          </span>
        </a>
        <a href={PLAY_STORE_URL} target="_blank" rel="noopener noreferrer"
           onClick={() => track("blog_cta_store_click", { store: "google_play", from_post: post?.slug, post_category: post?.category })}
           style={storeBtn}>
          <PlayIcon size={28}/>
          <span style={storeText}>
            <span style={storeTop}>{c.androidTop || "Get it on"}</span>
            <span style={storeBottom}>{c.androidBottom || "Google Play"}</span>
          </span>
        </a>
      </div>
    </div>
  </section>);
}

const storeBtn = {
  display:"inline-flex", alignItems:"center", gap:12,
  padding:"14px 22px", borderRadius:12,
  background:"var(--fg)", color:"var(--bg)",
  textDecoration:"none", transition:"transform .15s ease, box-shadow .15s ease",
  boxShadow:"0 8px 24px -8px rgba(0,0,0,.4)",
  minWidth: 200,
};
const storeText = { display:"flex", flexDirection:"column", alignItems:"flex-start", lineHeight:1.1, textAlign:"left" };
const storeTop = { fontSize:10, fontWeight:400, opacity:.7, letterSpacing:".02em" };
const storeBottom = { fontSize:16, fontWeight:600, letterSpacing:".01em" };

function PostFooter({ 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}}>
        <PostLogo 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`}>{t.nav.blog}</a>
        <a href={`/${lang}/faq`}>{t.nav.faq}</a>
        <a href="/privacy-policy">Privacy</a>
      </div>
    </div>
  </footer>);
}

// ============================================================
//  Root
// ============================================================
function PostApp() {
  // Öncelik sırası: 1) URL path prefix (/tr/blog/...)  2) URL query (?lang=X — legacy)
  //                 3) localStorage tercihi  4) PHP server-render varsayılanı  5) "en"
  const SUPPORTED_LANGS = ["tr","en","de","fr","es","ru","pl","ar"];
  const pathLang = (() => {
    try {
      const m = window.location.pathname.match(/^\/(tr|en|de|fr|es|ru|pl|ar)\/blog\//);
      return m ? m[1] : null;
    } catch (e) { return null; }
  })();
  const urlLang = (() => {
    try {
      const v = new URLSearchParams(window.location.search).get("lang");
      return SUPPORTED_LANGS.includes(v) ? v : null;
    } catch (e) { return null; }
  })();
  const savedLang = (typeof readSharedLang === "function" ? readSharedLang() : null);
  const initialLang = pathLang
    || urlLang
    || savedLang
    || (typeof window.__BLOG_INITIAL_LANG__ === "string" && window.__BLOG_INITIAL_LANG__)
    || "en";
  const [lang, setLang] = useStateP(initialLang);
  const [post, setPost] = useStateP(null);
  const [related, setRelated] = useStateP([]);
  const [actualLang, setActualLang] = useStateP(initialLang);
  const [loading, setLoading] = useStateP(true);
  const [notFound, setNotFound] = useStateP(false);

  const slug = window.__BLOG_SLUG__
    || decodeURIComponent((window.location.pathname.match(/\/blog\/([a-z0-9-]+)/) || [])[1] || "");

  useEffectP(() => {
    if (typeof writeSharedLang === "function") writeSharedLang(lang);
    document.documentElement.lang = lang;
  }, [lang]);

  useEffectP(() => {
    if (!slug) { setNotFound(true); setLoading(false); return; }
    let cancelled = false;
    setLoading(true);
    setNotFound(false);
    fetch(`/api/posts/${encodeURIComponent(slug)}?lang=${lang}`)
      .then(r => r.json())
      .then(res => {
        if (cancelled) return;
        if (!res.ok) {
          setNotFound(true);
          setLoading(false);
          // Track 404
          track("blog_post_not_found", { post_slug: slug, lang });
          return;
        }
        setPost(res.data.post);
        setRelated(res.data.related || []);
        setActualLang(res.data.actual_lang || lang);
        setLoading(false);
        if (res.data.post?.title) document.title = `${res.data.post.title} · OBDThink`;

        // GA4 custom event — kim hangi yazıyı, hangi dilde okuyor
        track("blog_post_view", {
          post_slug:     res.data.post.slug,
          post_title:    res.data.post.title,
          post_category: res.data.post.category,
          post_lang:     res.data.actual_lang || lang,
          requested_lang: lang,
          post_author:   res.data.post.author_name,
          read_min:      res.data.post.read_min,
          has_video:     !!res.data.post.youtube_id,
          is_featured:   !!res.data.post.featured,
        });
      })
      .catch((err) => {
        if (!cancelled) {
          setNotFound(true);
          setLoading(false);
          track("blog_post_error", { post_slug: slug, lang, error: String(err.message || err) });
        }
      });
    return () => { cancelled = true; };
  }, [slug, lang]);

  // ----- Scroll depth tracking (25/50/75/100) -----
  const scrollMarks = useRefP({ 25: false, 50: false, 75: false, 100: false });
  useEffectP(() => {
    if (!post) return;
    scrollMarks.current = { 25: false, 50: false, 75: false, 100: false };

    const onScroll = () => {
      const h = document.documentElement;
      const scrolled = (h.scrollTop + window.innerHeight) / h.scrollHeight * 100;
      [25, 50, 75, 100].forEach(mark => {
        if (!scrollMarks.current[mark] && scrolled >= mark) {
          scrollMarks.current[mark] = true;
          track("blog_scroll", {
            depth_pct: mark,
            post_slug: post.slug,
            post_category: post.category,
            post_lang: actualLang,
          });
        }
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [post, actualLang]);

  // ----- Engagement tracking (30s + 120s milestones) -----
  useEffectP(() => {
    if (!post) return;
    const t30 = setTimeout(() => {
      track("blog_engaged_30s", {
        post_slug: post.slug,
        post_category: post.category,
        post_lang: actualLang,
      });
    }, 30_000);
    const t120 = setTimeout(() => {
      track("blog_engaged_120s", {
        post_slug: post.slug,
        post_category: post.category,
        post_lang: actualLang,
      });
    }, 120_000);
    return () => { clearTimeout(t30); clearTimeout(t120); };
  }, [post, actualLang]);

  const t = (window.BLOG_T && window.BLOG_T[lang]) || (window.BLOG_T && window.BLOG_T.en) || {};
  // POST_T'den eksik label'lar için fallback
  if (!t.labels) {
    t.labels = { backToBlog: "Back to blog", readMin: "min read", by: "by", toc: "Contents", share: "Share", copy: "Copy link", copied: "Copied!", related: "Related posts", notFound: "Post not found", notFoundSub: "The post you're looking for doesn't exist.", videoComingSoon: "Video coming soon", langFallback: "Showing English fallback." };
  }
  if (!t.cta) t.cta = { title: "Download OBDThink", sub: "The tool to put these guides to work.", btn: "Get the app" };

  const fallbackBanner = !notFound && post && actualLang !== lang;

  return (<>
    <PostNav t={t} lang={lang} setLang={setLang}/>
    {loading ? (
      <section style={{padding:"140px 0",textAlign:"center",color:"var(--fg-dim)"}}>…</section>
    ) : notFound || !post ? (
      <PostNotFound t={t} lang={lang}/>
    ) : (<>
      <PostTopBanner t={t}/>
      <PostHero post={post} t={t} lang={lang} fallbackBanner={fallbackBanner}/>
      <PostVideo post={post} t={t}/>
      <PostContent post={post} t={t}/>
      <RelatedPosts related={related} t={t} lang={lang} fromPost={post.slug}/>
      <PostCta t={t} post={post}/>
    </>)}
    <PostFooter t={t} lang={lang}/>
  </>);
}

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