/* novice.jsx, news index page; uses Header/Footer/Arrow from advant.jsx */
const { useState: useStateN } = React;

const NEWS = [
  {
    id: "N-024",
    cat: "Projekti",
    date: "21. apr 2026",
    title: "Predaja podatkovnega centra Tier III za farmacevtsko podjetje",
    excerpt: "Po 14 mesecih izvedbe smo predali 1.2 MW podatkovni center z 2N napajanjem in hot/cold aisle hlajenjem. Migracija je potekala brez prekinitve produkcije.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "MK",
    readtime: "6 min",
    featured: true,
  },
  {
    id: "N-023",
    cat: "Tehnologija",
    date: "08. apr 2026",
    title: "PUE pod 1.3: kako smo prenovili hlajenje obstoječega DC",
    excerpt: "Zamenjava CRAH enot, ločitev hot/cold aisle in optimizacija zračnih tokov. Rezultat, 22% nižja poraba energije v prvih treh mesecih.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "JP",
    readtime: "8 min",
  },
  {
    id: "N-022",
    cat: "Projekti",
    date: "27. mar 2026",
    title: "Računalniška omrežja za 12-nadstropno poslovno stavbo",
    excerpt: "OS2 hrbtenica, Cat6A horizontalno omrežje, redundantni MMR prostori. Projekt smo dokončali tri tedne pred rokom.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "AB",
    readtime: "5 min",
  },
  {
    id: "N-021",
    cat: "Tehnologija",
    date: "14. mar 2026",
    title: "Wi-Fi 7 v industrijskem okolju: prvi praktični izsledki",
    excerpt: "Šest mesecev meritev v proizvodni hali. Kje 320 MHz kanali pomagajo, kje pa je MLO ključen za zanesljivost povezav.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "TM",
    readtime: "10 min",
  },
  {
    id: "N-020",
    cat: "Podjetje",
    date: "02. mar 2026",
    title: "Krepimo ekipo: pet novih inženirjev v 2026",
    excerpt: "Razširjamo projektni in vzdrževalni tim na področju podatkovnih centrov in optičnih omrežij. Odprti razpisi za senior inženirje.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "KS",
    readtime: "3 min",
  },
  {
    id: "N-019",
    cat: "Tehnologija",
    date: "18. feb 2026",
    title: "Redundanca napajanja: kdaj N+1 ni dovolj",
    excerpt: "Praktični vodnik skozi različne topologije napajanja in kdaj za vašo obremenitev resnično potrebujete 2N ali 2(N+1) sistem.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "JP",
    readtime: "12 min",
  },
  {
    id: "N-018",
    cat: "Projekti",
    date: "29. jan 2026",
    title: "Nadgradnja DC za finančno institucijo brez prekinitve",
    excerpt: "Zamenjava UPS sistema in distribucijskih plošč med produkcijo. Ključ je bil v 6-mesečnem načrtovanju in tedensko sinhroniziranih oknih.",
    img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=1600&q=85&auto=format&fit=crop",
    author: "MK",
    readtime: "7 min",
  },
];

const CATS = ["Vse", "Projekti", "Tehnologija", "Podjetje"];

function NewsHero({ h1, sub, eyebrow }) {
  return (
    <section className="page-hero">
      <div className="container">
        <div className="page-hero__inner">
          <div className="page-hero__title">
            <span className="eyebrow"><span className="mono">[novice]</span>&nbsp;&nbsp;{eyebrow || "Inženirski zapisi · projekti · podjetje"}</span>
            <h1 dangerouslySetInnerHTML={{ __html: h1 || "Iz prakse,<br/><em>ne s konference.</em>" }} />
            <p className="page-hero__lede">
              {sub || "Zapisi naših inženirjev o projektih, tehnoloških odločitvah in delovanju kritičnih sistemov. Brez marketinga, samo to, kar smo se naučili."}
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

function FilterBar({ active, setActive, counts }) {
  const cats = ["Vse", ...Object.keys(counts).filter(k => k !== "Vse")];
  return (
    <div className="container">
      <div className="filter-bar">
        {cats.map(c => (
          <button
            key={c}
            className={"filter-bar__btn " + (active === c ? "is-active" : "")}
            onClick={() => setActive(c)}
          >
            {c}<span className="count">{counts[c] ?? 0}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function Featured({ item }) {
  return (
    <a className="featured" href={`/novice/${item.slug || item.id}`}>
      <div className="featured__media">
        <span className="featured__badge">Najnovejše</span>
        <img src={item.img} alt={item.title} loading="lazy" />
      </div>
      <div className="featured__body">
        <div>
          <div className="featured__meta">
            <span>{item.cat}</span>
            <span className="dot" />
            <span>{item.date}</span>
            <span className="dot" />
            <span>{item.id}</span>
          </div>
          <h2 style={{ marginTop: 24 }}>{item.title}</h2>
          <p className="featured__excerpt" style={{ marginTop: 20 }}>{item.excerpt}</p>
        </div>
        <div className="featured__foot">
          <div className="featured__author">
            <div className="featured__avatar">{item.author}</div>
            <span>Avtor, Advant inženirska ekipa</span>
          </div>
          <span className="featured__readtime">{item.readtime} branja</span>
        </div>
      </div>
    </a>
  );
}

function NewsCard({ item }) {
  return (
    <a className="news-card" href={`/novice/${item.slug || item.id}`}>
      <div className="news-card__body">
        <div className="news-card__meta">
          <span>{item.date}</span>
          <span className="dot" />
          <span>{item.id}</span>
        </div>
        <h3>{item.title}</h3>
        <p className="news-card__excerpt">{item.excerpt}</p>
        <div className="news-card__foot">
          <span>{item.readTime} branja</span>
          <Arrow size={12} className="arr" />
        </div>
      </div>
    </a>
  );
}

function NewsList({ items }) {
  return (
    <div className="container">
      <div className="news-list">
        {items.map(it => (
          <a className="news-row" href={`/novice/${it.slug || it.id}`} key={it.id}>
            <div className="news-row__date">{it.date.split(" ")[0]}&nbsp;{it.date.split(" ")[1]}</div>
            <div className="news-row__cat">{it.cat}</div>
            <div className="news-row__title">{it.title}</div>
            <div className="news-row__readtime">{it.readTime}</div>
            <Arrow size={12} className="news-row__arrow" />
          </a>
        ))}
      </div>
    </div>
  );
}

const NT = {
  SI: {
    idx: "Mesečni zapis", h2a: "En zapis na mesec.", h2b: "Iz prakse, ne za prakso.",
    desc: "Pošljemo vam povzetek projektov in tehničnih odločitev, ki smo jih sprejeli v zadnjem mesecu. Brez novičnikov, brez marketinga.",
    ph: "ime@podjetje.si", btnDone: "✓ Prijavljeni", btnBusy: "Pošiljanje…", btnDefault: "Prijavi se",
    hintSent: "Hvala. Naslednja izdaja izide v začetku meseca.", hintDefault: "Brez deljenja podatkov. Odjavite se kadarkoli.",
    submitMsg: "Prijava na mesečni novičnik.", reject: "Prijava trenutno ni na voljo.", err: "Napaka pri prijavi.",
  },
  EN: {
    idx: "Monthly note", h2a: "One note a month.", h2b: "From practice, not for practice.",
    desc: "We send you a summary of the projects and technical decisions we made over the past month. No newsletters, no marketing.",
    ph: "name@company.com", btnDone: "✓ Subscribed", btnBusy: "Sending…", btnDefault: "Subscribe",
    hintSent: "Thank you. The next issue comes out at the start of the month.", hintDefault: "No data sharing. Unsubscribe at any time.",
    submitMsg: "Subscription to the monthly newsletter.", reject: "Subscription is currently unavailable.", err: "Subscription error.",
  },
  DE: {
    idx: "Monatliche Notiz", h2a: "Eine Notiz pro Monat.", h2b: "Aus der Praxis, nicht für die Praxis.",
    desc: "Wir senden Ihnen eine Zusammenfassung der Projekte und technischen Entscheidungen des letzten Monats. Keine Newsletter, kein Marketing.",
    ph: "name@firma.de", btnDone: "✓ Angemeldet", btnBusy: "Senden…", btnDefault: "Anmelden",
    hintSent: "Danke. Die nächste Ausgabe erscheint Anfang des Monats.", hintDefault: "Keine Datenweitergabe. Jederzeit abbestellbar.",
    submitMsg: "Anmeldung zum monatlichen Newsletter.", reject: "Anmeldung derzeit nicht verfügbar.", err: "Fehler bei der Anmeldung.",
  },
};

function Newsletter() {
  const lang = React.useContext(LangContext);
  const nt = NT[lang] || NT.SI;
  const [email, setEmail] = useStateN("");
  const [sent, setSent] = useStateN(false);
  const [hp, setHp] = useStateN("");        // honeypot
  const [busy, setBusy] = useStateN(false);
  const [err, setErr] = useStateN("");
  const mountedAt = React.useRef(Date.now());

  const submit = (e) => {
    e.preventDefault();
    setErr("");
    if (!email || busy) return;
    if (hp) { setSent(true); return; } // honeypot tripped → silent
    const submitFn = (window.AdvantWP && window.AdvantWP.wpSubmit)
      ? window.AdvantWP.wpSubmit("contact", {
          form: "newsletter", email,
          message: nt.submitMsg,
          website: hp, t: mountedAt.current, lang: lang,
          source: typeof location !== "undefined" ? location.pathname : ""
        })
      : Promise.reject(new Error(nt.reject));
    setBusy(true);
    submitFn
      .then(() => { setBusy(false); setSent(true); })
      .catch((e2) => { setBusy(false); setErr(e2.message || nt.err); });
  };
  return (
    <section className="newsletter">
      <div className="container">
        <div className="newsletter__inner">
          <div className="newsletter__copy">
            <div className="sec-head__index"><span className="num">01</span><span>{nt.idx}</span></div>
            <h2 style={{ marginTop: 18 }}>{nt.h2a}<br/>{nt.h2b}</h2>
            <p>{nt.desc}</p>
          </div>
          <div>
            <form
              className="newsletter__form"
              onSubmit={submit}
            >
              <input
                type="email"
                placeholder={nt.ph}
                value={email}
                onChange={e => setEmail(e.target.value)}
                disabled={sent || busy}
                required
              />
              {/* honeypot — skrito polje za bote */}
              <input type="text" tabIndex={-1} autoComplete="off" aria-hidden="true"
                value={hp} onChange={e => setHp(e.target.value)}
                style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
              <button type="submit" disabled={sent || busy}>
                {sent ? nt.btnDone : busy ? nt.btnBusy : nt.btnDefault} <Arrow size={12} className="arrow" />
              </button>
            </form>
            <div className="newsletter__hint">
              {err ? <span style={{ color: "#e5484d" }}>{err}</span>
                : sent ? nt.hintSent
                : nt.hintDefault}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function NewsApp() {
  const [active, setActive] = useStateN("Vse");
  const [news, setNews] = useStateN(null); /* null = loading, [] = loaded empty */
  const [heroData, setHeroData] = useStateN(null);

  /* ── Load from WP ── */
  React.useEffect(() => {
        const { wpOptions, wpPosts, gs, fmtDate, decode, stripShortcodes, calcReadTime } = window.AdvantWP || {};
    if (!wpOptions) { setNews([]); window.AdvantWP && window.AdvantWP.hidePreloader(); return; }

    /* Apply global contact to T */
    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(() => {});

    Promise.all([
      wpOptions('novice-page'),
      wpPosts('posts', { per_page: 100, orderby: 'date', order: 'desc' }),
    ])
      .then(([np, posts]) => {
        const l = (document.body.dataset.lang || 'SI').toLowerCase();

        /* ── Hero ── */
        setHeroData({
          h1:      gs(np, `np_hero_h1_${l}`) || null,
          sub:     gs(np, `np_hero_sub_${l}`) || null,
          eyebrow: gs(np, `np_hero_eyebrow_${l}`) || null,
        });

        /* ── Map standard WP posts → NEWS shape ── */
        if (!posts || !posts.length) { setNews([]); return; }
        const mapped = posts
          .map(p => {
            /* featured image — only if actually set, no fallback */
            const media = (p._embedded && p._embedded['wp:featuredmedia']) || [];
            const img = (media[0] && media[0].source_url) || null;
            /* primary category */
            const terms = (p._embedded && p._embedded['wp:term']) || [];
            const cat = (terms[0] && terms[0][0] && terms[0][0].name) || 'Novice';
            const acfExcerpt = p.acf && gs(p.acf, `nov_excerpt_${l}`);
            const excerpt = acfExcerpt ? decode(acfExcerpt) : stripShortcodes(p.excerpt && p.excerpt.rendered || '');
            window.__WP_NEWS__ = window.__WP_NEWS__ || {};
            window.__WP_NEWS__[p.id] = p;
            return {
              id:       String(p.id),
              slug:     p.slug,
              cat,
              title:    decode(p.title && p.title.rendered || ''),
              date:     fmtDate(p.date_gmt || p.date),
              author:   'ADV',
              excerpt,
              img,          /* null if no featured image */
              readTime: calcReadTime(p.content && p.content.rendered),
              featured: !!p.sticky,
            };
          })
          .filter(n => n.title);

        window.__ADVANT_NEWS__ = mapped;
        setNews(mapped);
        window.AdvantWP && window.AdvantWP.hidePreloader();
      })
      .catch(e => {
        console.warn('[AdvantWP] novice load failed.', e);
        setNews([]);
        window.AdvantWP && window.AdvantWP.hidePreloader();
      });
  }, []);

  /* Still loading — preloader overlay covers the page */
  if (news === null) return null;

  const counts = news.reduce((acc, n) => {
    acc["Vse"] = (acc["Vse"] || 0) + 1;
    acc[n.cat] = (acc[n.cat] || 0) + 1;
    return acc;
  }, {});

  const filtered = active === "Vse" ? news : news.filter(n => n.cat === active);

  return (
    <LangContext.Provider value={document.body.dataset.lang || "SI"}>
      <AmbientOrb />
      <Header />
      <NewsHero
        h1={heroData && heroData.h1}
        sub={heroData && heroData.sub}
        eyebrow={heroData && heroData.eyebrow}
      />
      <FilterBar active={active} setActive={setActive} counts={counts} />
      <section style={{ padding: "0 0 80px", background: "var(--bg-2)" }}>
        <NewsList items={filtered} />
      </section>
      <Newsletter />
      <Contact />
      <Footer />
    </LangContext.Provider>
  );
}

if (document.body.dataset.page !== 'novica') {
  ReactDOM.createRoot(document.getElementById("root")).render(<NewsApp />);
}
