/* novica.jsx, single article view; fetches article from WP by id or falls back to NEWS array */

/* Support path-based /novice/[slug] and /novica/[slug], and legacy /novica?id=[slug] */
(function resolveArticleId() {
  const pathParts = window.location.pathname.split('/').filter(Boolean);
  const lastPart = pathParts[pathParts.length - 1];
  const fromPath = lastPart && !['novica', 'novice'].includes(lastPart) ? lastPart : null;
  const fromQuery = new URLSearchParams(window.location.search).get('id') || '';
  window.__novicaId = fromPath || fromQuery;
}());
const articleId = window.__novicaId || "";

function injectSeoMeta(item, imgUrl) {
  const title = item.title ? `${item.title} | Advant Novice` : 'Novica | Advant';
  const rawExcerpt = item.excerpt || '';
  const desc = rawExcerpt.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim().slice(0, 155);
  const img = imgUrl || item.img || 'https://advant.si/images/og-default.png';
  const slug = item.slug || item.id || '';
  const url = `https://advant.si/novice/${slug}`;

  document.title = title;
  const setMeta = (sel, val) => { const el = document.querySelector(sel); if (el) el.setAttribute('content', val); };
  setMeta('meta[name="description"]', desc);
  setMeta('meta[property="og:title"]', title);
  setMeta('meta[property="og:description"]', desc);
  setMeta('meta[property="og:url"]', url);
  setMeta('meta[property="og:image"]', img);
  const canonical = document.querySelector('link[rel="canonical"]');
  if (canonical) canonical.href = url;

  const ldEl = document.getElementById('ld-article');
  if (ldEl) {
    ldEl.textContent = JSON.stringify({
      '@context': 'https://schema.org',
      '@type': 'Article',
      'headline': item.title || '',
      'description': desc,
      'image': img,
      'datePublished': item.dateRaw || '',
      'author': { '@type': 'Organization', 'name': 'Advant', 'url': 'https://advant.si' },
      'publisher': {
        '@type': 'Organization',
        'name': 'Advant',
        'url': 'https://advant.si',
        'logo': { '@type': 'ImageObject', 'url': 'https://advant.si/favicon-192x192.png' }
      },
      'mainEntityOfPage': { '@type': 'WebPage', '@id': url }
    });
  }
}

function ArticleApp() {
  const [item, setItem] = React.useState(null);
  const [body, setBody] = React.useState(null);
  const [related, setRelated] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const { wpPosts, wpOptions, gs, fmtDate, decode, stripShortcodes, stripShortcodesHtml, calcReadTime } = window.AdvantWP || {};
    const pageLang = (document.body.dataset.lang || 'SI').toLowerCase();

    /* Apply global contact/nav to T so Header/Footer look right */
    if (wpOptions) {
      wpOptions('global').then(g => {
        const set = (obj, key, val) => { if (val) obj[key] = decode(val); };
        ['SI','EN','DE'].forEach(LANG => {
          const l = LANG.toLowerCase();
          const tl = T[LANG];
          set(tl.contact.meta, 'emailVal',   gs(g, `g_contact_email_${l}`));
          set(tl.contact.meta, 'phoneVal',   gs(g, `g_contact_phone_${l}`));
          set(tl.contact.meta, 'addressVal', gs(g, `g_contact_address_${l}`));
          set(tl.contact.meta, 'mapsUrl',    gs(g, `g_contact_maps_${l}`));
          set(tl.footer, 'emailVal', gs(g, `g_contact_email_${l}`));
          set(tl.footer, 'phoneVal', gs(g, `g_contact_phone_${l}`));
        });
      }).catch(() => {});
    }

    /* Helper to build item + body from a WP post (prefers multilingual ACF) */
    function fromPost(p) {
      const media = (p._embedded && p._embedded['wp:featuredmedia']) || [];
      const img = (media[0] && media[0].source_url) || null;
      const terms = (p._embedded && p._embedded['wp:term']) || [];
      const cat = (terms[0] && terms[0][0] && terms[0][0].name) || 'Novice';
      const acf = p.acf || {};
      const acfExcerpt = gs(acf, `nov_excerpt_${pageLang}`);
      const acfBody    = gs(acf, `nov_body_${pageLang}`);
      const excerpt = acfExcerpt ? decode(acfExcerpt) : stripShortcodes(p.excerpt && p.excerpt.rendered || '');
      const bodyHtml = acfBody || (p.content && p.content.rendered) || null;
      const articleItem = {
        id:       String(p.id),
        slug:     p.slug,
        cat:      cat,
        title:    decode(p.title && p.title.rendered || ''),
        date:     fmtDate(p.date_gmt || p.date),
        dateRaw:  p.date_gmt || p.date || '',
        author:   'ADV',
        excerpt:  excerpt,
        img:      img,
        readTime: calcReadTime(bodyHtml),
        featured: !!p.sticky,
      };
      const articleBody = {
        lede:         excerpt,
        cover:        img,
        coverCaption: '',
        role:         'Advant inženirska ekipa',
        rawHtml:      stripShortcodesHtml(bodyHtml),
      };
      return { articleItem, articleBody };
    }

    /* Try to fetch single post by numeric WP id */
    if (articleId && /^\d+$/.test(articleId) && wpPosts) {
      wpPosts('posts', { include: articleId, per_page: 1 })
        .then(posts => {
          if (posts && posts.length) {
            const { articleItem, articleBody } = fromPost(posts[0]);
            injectSeoMeta(articleItem, articleBody.cover);
            setItem(articleItem);
            setBody(articleBody);
            /* Fetch related (same cat, different post) */
            return wpPosts('posts', { per_page: 3, exclude: articleId }).then(rel => {
              if (rel) setRelated(rel.map(r => fromPost(r).articleItem));
            });
          } else {
            return fallbackToLocal();
          }
        })
        .catch(fallbackToLocal)
        .finally(() => { setLoading(false); window.AdvantWP && window.AdvantWP.hidePreloader(); });
    } else {
      /* Try fallback by slug (old N-xxx ids) */
      if (articleId && wpPosts) {
        wpPosts('posts', { slug: articleId, per_page: 1 })
          .then(posts => {
            if (posts && posts.length) {
              const { articleItem, articleBody } = fromPost(posts[0]);
              injectSeoMeta(articleItem, articleBody.cover);
              setItem(articleItem);
              setBody(articleBody);
            } else {
              fallbackToLocal();
            }
          })
          .catch(fallbackToLocal)
          .finally(() => { setLoading(false); window.AdvantWP && window.AdvantWP.hidePreloader(); });
      } else {
        fallbackToLocal();
        setLoading(false);
        window.AdvantWP && window.AdvantWP.hidePreloader();
      }
    }

    function fallbackToLocal() {
      const fallbackNews = window.__ADVANT_NEWS__ || (typeof NEWS !== 'undefined' ? NEWS : []);
      const found = fallbackNews.find(n => n.id === articleId || n.slug === articleId) || fallbackNews[0];
      if (!found) { setLoading(false); window.AdvantWP && window.AdvantWP.hidePreloader(); return; }
      const hardBody = typeof ARTICLE_BODIES !== 'undefined' ? ARTICLE_BODIES[found.id] : null;
      injectSeoMeta(found, found.img);
      setItem(found);
      setBody(hardBody || {
        lede:    found.excerpt,
        cover:   found.img,
        coverCaption: null,
        role:    'Inženirska ekipa',
        rawHtml: null,
      });
      const fallbackRelated = fallbackNews.filter(n => n.id !== found.id).slice(0, 3);
      setRelated(fallbackRelated);
    }
  }, []);

  if (loading) {
    return (
      <>
        <Header />
        <section className="article"><div className="container"><p style={{padding:'80px 0',opacity:.5}}>Nalagam…</p></div></section>
        <Footer />
      </>
    );
  }

  if (!item) {
    return (
      <>
        <Header />
        <section className="article">
          <div className="container">
            <h1>Novica ni najdena.</h1>
            <a href="/novice" className="article__back">← Nazaj na novice</a>
          </div>
        </section>
        <Footer />
      </>
    );
  }

  const data = body || { lede: item.excerpt, cover: item.img, coverCaption: null, role: 'Inženirska ekipa', rawHtml: null };

  /* Build rendered body: prefer raw HTML from WP, else structured blocks */
  let bodyContent;
  if (data.rawHtml) {
    bodyContent = <div className="article__body" dangerouslySetInnerHTML={{ __html: data.rawHtml }} />;
  } else {
    const blocks = data.body || [];
    bodyContent = (
      <div className="article__body">
        {blocks.map((block, i) => {
          if (block.type === "h2") return <h2 key={i}>{block.text}</h2>;
          if (block.type === "pull") return <blockquote key={i} className="article__pull">{block.text}</blockquote>;
          if (block.type === "stats") return (
            <div key={i} className="article__stats">
              {block.items.map((s, j) => (
                <div key={j} className="article__stat">
                  <div className="num">{s.num[0]}<sup>{s.num[1]}</sup></div>
                  <div className="lbl">{s.label}</div>
                </div>
              ))}
            </div>
          );
          return <p key={i}>{block.text}</p>;
        })}
      </div>
    );
  }

  return (
    <LangContext.Provider value={document.body.dataset.lang || "SI"}>
      <Header />

      <section className="article">
        <div className="container">
          <a href="/novice" className="article__back">
            <Arrow size={11} /> Nazaj na vse novice
          </a>

          <header className="article__head">
            <div className="article__meta">
              <span className="cat">{item.cat}</span>
              <span className="dot" />
              <span>{item.date}</span>
              <span className="dot" />
              <span>{item.id}</span>
            </div>
            <h1 className="article__title">{item.title}</h1>
            <p className="article__lede">{data.lede}</p>
          </header>

          <div className="article__byline">
            <div className="article__byline-left">
              <div className="article__avatar">{item.author}</div>
              <div>
                <div className="article__byline-name">Advant inženirska ekipa</div>
                <div className="article__byline-role">{data.role}</div>
              </div>
            </div>
            <div className="article__byline-right">
              <span>{item.readTime} branja</span>
              <span>·</span>
              <span>Objavljeno {item.date}</span>
            </div>
          </div>

          <figure className="article__cover">
            {data.cover && <img src={data.cover} alt={item.title} />}
            {data.coverCaption && <figcaption>{data.coverCaption}</figcaption>}
          </figure>

          {bodyContent}

          <div className="article__foot">
            <span>{item.id} · {item.cat}</span>
            <a href="/novice" style={{ color: "var(--ink-3)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}>
              Vse novice <Arrow size={11} />
            </a>
          </div>
        </div>
      </section>

      {related.length > 0 && (
        <section className="article__related">
          <div className="container">
            <h3>Sorodni zapisi</h3>
            <div className="news-grid">
              {related.map(it => <NewsCard key={it.id} item={it} />)}
            </div>
          </div>
        </section>
      )}

      <Footer />
    </LangContext.Provider>
  );
}

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