/* ============================================================
   Төрмен — Blog from Sanity CMS
   Public dataset read via CDN. Fallback: static VIDEOS.
   ============================================================ */
const { createContext:createCtxBlog, useContext:useCtxBlog, useState:useStateBlog, useEffect:useEffectBlog } = React;

const BLOG_CATS_FALLBACK = typeof VIDEO_CATS !== 'undefined' ? VIDEO_CATS : [
  { id:'all',    label:{ru:'Все',kz:'Барлығы'} },
  { id:'recipe', label:{ru:'Рецепты',kz:'Рецепттер'} },
  { id:'farm',   label:{ru:'О ферме',kz:'Ферма туралы'} },
  { id:'cut',    label:{ru:'Разделка',kz:'Бөлшектеу'} },
  { id:'story',  label:{ru:'Истории',kz:'Әңгімелер'} },
];

function sanityEnv(){
  return window.TORMEN_ENV?.sanity || {};
}

function isSanityConfigured(){
  const { projectId } = sanityEnv();
  return !!(projectId && projectId.length > 4 && projectId !== 'YOUR_PROJECT_ID');
}

function sanityImageUrl(source, { w = 1200 } = {}){
  if(!source) return null;
  if(typeof source === 'string' && source.startsWith('http')) return source;
  // Already resolved absolute URL from query
  if(source.url) return source.url;
  const ref = source.asset?._ref || source._ref;
  if(!ref) return null;
  const { projectId, dataset } = sanityEnv();
  if(!projectId) return null;
  // image-{id}-{w}x{h}-{fmt}
  const m = String(ref).match(/^image-([a-f0-9]+)-(\d+x\d+)-(\w+)$/i);
  if(!m) return null;
  const [, id, dims, fmt] = m;
  return `https://cdn.sanity.io/images/${projectId}/${dataset || 'production'}/${id}-${dims}.${fmt}?w=${w}&auto=format`;
}

function youtubeEmbed(url){
  if(!url) return null;
  try{
    const u = new URL(url);
    if(u.hostname.includes('youtu.be')){
      const id = u.pathname.replace(/^\//,'');
      return id ? `https://www.youtube.com/embed/${id}` : null;
    }
    if(u.hostname.includes('youtube.com')){
      const id = u.searchParams.get('v');
      if(id) return `https://www.youtube.com/embed/${id}`;
      const parts = u.pathname.split('/');
      const i = parts.indexOf('embed');
      if(i >= 0 && parts[i+1]) return `https://www.youtube.com/embed/${parts[i+1]}`;
      const s = parts.indexOf('shorts');
      if(s >= 0 && parts[s+1]) return `https://www.youtube.com/embed/${parts[s+1]}`;
    }
  }catch(_){}
  return null;
}

function mapSanityPost(doc){
  if(!doc) return null;
  const catSlug = doc.categorySlug || doc.category?.slug || 'story';
  const coverUrl = doc.coverUrl || sanityImageUrl(doc.cover);
  return {
    id: doc._id || doc.slug || Math.random().toString(36).slice(2),
    slug: doc.slug || '',
    cat: catSlug,
    dur: String(doc.durationMin || 10),
    views: doc.viewsLabel || '—',
    feat: !!doc.featured,
    title: {
      ru: doc.title || '',
      kz: doc.titleKz || doc.title || '',
    },
    excerpt: {
      ru: doc.excerpt || '',
      kz: doc.excerptKz || doc.excerpt || '',
    },
    coverUrl: coverUrl || null,
    videoUrl: doc.videoUrl || null,
    embedUrl: youtubeEmbed(doc.videoUrl),
    publishedAt: doc.publishedAt || null,
    _fromCms: true,
  };
}

function mapSanityCategory(doc){
  if(!doc?.slug) return null;
  return {
    id: doc.slug,
    label: {
      ru: doc.title || doc.slug,
      kz: doc.titleKz || doc.title || doc.slug,
    },
    sortOrder: doc.sortOrder ?? 99,
  };
}

async function sanityFetch(query, params = {}){
  const { projectId, dataset, apiVersion } = sanityEnv();
  const ds = dataset || 'production';
  const ver = apiVersion || '2024-01-01';
  const q = encodeURIComponent(query);
  let url = `https://${projectId}.apicdn.sanity.io/v${ver}/data/query/${ds}?query=${q}`;
  for(const [k,v] of Object.entries(params)){
    url += `&$${k}=${encodeURIComponent(JSON.stringify(v))}`;
  }
  const ctrl = new AbortController();
  const timer = setTimeout(()=> ctrl.abort(), 12000);
  try{
    const res = await fetch(url, { signal: ctrl.signal });
    if(!res.ok) throw new Error(`sanity_${res.status}`);
    const data = await res.json();
    return data.result;
  }finally{
    clearTimeout(timer);
  }
}

const POSTS_QUERY = `*[_type == "blogPost" && defined(slug.current)] | order(featured desc, publishedAt desc) {
  _id,
  "slug": slug.current,
  title,
  titleKz,
  excerpt,
  excerptKz,
  durationMin,
  viewsLabel,
  featured,
  videoUrl,
  publishedAt,
  "categorySlug": category->slug.current,
  "coverUrl": cover.asset->url
}`;

const CATS_QUERY = `*[_type == "blogCategory" && defined(slug.current)] | order(sortOrder asc) {
  title,
  titleKz,
  "slug": slug.current,
  sortOrder
}`;

const BlogContext = createCtxBlog(null);

function BlogProvider({ children }){
  const [posts, setPosts] = useStateBlog(()=> {
    const staticList = (typeof VIDEOS !== 'undefined' && VIDEOS) || window.VIDEOS || [];
    return staticList;
  });
  const [categories, setCategories] = useStateBlog(()=> [
    { id:'all', label:{ru:'Все',kz:'Барлығы'} },
    ...BLOG_CATS_FALLBACK.filter(c=> c.id !== 'all'),
  ]);
  const [loading, setLoading] = useStateBlog(!!isSanityConfigured());
  const [source, setSource] = useStateBlog(isSanityConfigured() ? 'loading' : 'static');

  useEffectBlog(()=>{
    if(!isSanityConfigured()){
      setLoading(false);
      setSource('static');
      return;
    }
    let cancelled = false;
    (async ()=>{
      try{
        const [rawPosts, rawCats] = await Promise.all([
          sanityFetch(POSTS_QUERY),
          sanityFetch(CATS_QUERY),
        ]);
        if(cancelled) return;
        const mapped = (rawPosts || []).map(mapSanityPost).filter(Boolean);
        const cats = (rawCats || []).map(mapSanityCategory).filter(Boolean);
        if(mapped.length){
          setPosts(mapped);
          window.VIDEOS = mapped;
          setSource('sanity');
        }else{
          // CMS configured but empty — keep static demo until seed
          setSource('sanity-empty');
        }
        if(cats.length){
          setCategories([
            { id:'all', label:{ru:'Все',kz:'Барлығы'} },
            ...cats.sort((a,b)=> (a.sortOrder||0) - (b.sortOrder||0)),
          ]);
          window.VIDEO_CATS = [
            { id:'all', label:{ru:'Все',kz:'Барлығы'} },
            ...cats.map(c=> ({ id:c.id, label:c.label })),
          ];
        }
      }catch(e){
        console.warn('[blog] Sanity fetch failed, static fallback:', e.message);
        if(!cancelled) setSource('static');
      }finally{
        if(!cancelled) setLoading(false);
      }
    })();
    return ()=>{ cancelled = true; };
  }, []);

  const value = { posts, categories, loading, source, configured: isSanityConfigured() };
  return <BlogContext.Provider value={value}>{children}</BlogContext.Provider>;
}

function useBlog(){
  const ctx = useCtxBlog(BlogContext);
  if(!ctx){
    const staticList = (typeof VIDEOS !== 'undefined' && VIDEOS) || window.VIDEOS || [];
    return {
      posts: staticList,
      categories: BLOG_CATS_FALLBACK,
      loading: false,
      source: 'static',
      configured: false,
    };
  }
  return ctx;
}

Object.assign(window, {
  BlogProvider,
  useBlog,
  isSanityConfigured,
  sanityImageUrl,
  youtubeEmbed,
  mapSanityPost,
});
