/* News Hub — Apple-Newsroom-style index: Latest News hero, press-release
   cards, an "In the Loop" portrait carousel, then a filterable list.
   Reuses BLOG_POSTS, useLang, useViewCount, applySEO from shared.jsx. */

const NH = {
  en: {
    eyebrow: "News Hub", title: "The latest from the studio.",
    subtitle: "Product news, field notes and what we're seeing across the markets we build in — Syria's tech reopening included.",
    latestNews: "Latest News", inTheLoop: "In the Loop", more: "More from Innoveev",
    viewAll: "View all", allTopics: "All topics", update: "Update", read: "Read article",
  },
  ar: {
    eyebrow: "مركز الأخبار", title: "أحدث ما لدى الاستوديو.",
    subtitle: "أخبار المنتجات وملاحظات ميدانية وما نراه في الأسواق التي نبني فيها — بما في ذلك انفتاح قطاع التقنية في سوريا.",
    latestNews: "أحدث الأخبار", inTheLoop: "في الحلقة", more: "المزيد من Innoveev",
    viewAll: "عرض الكل", allTopics: "كل المواضيع", update: "تحديث", read: "اقرأ المقال",
  },
};

function fmtDate(iso, lang, long = true) {
  return new Intl.DateTimeFormat(lang === "ar" ? "ar-AE" : "en-GB", {
    year: "numeric", month: long ? "long" : "short", day: "numeric",
  }).format(new Date(iso));
}
const grad = (c) => `linear-gradient(135deg, oklch(0.66 0.18 ${c.hue}), oklch(0.5 0.18 ${c.hue2 ?? c.hue}))`;

function NewsHero({ post, lang, nh, t }) {
  const d = post[lang];
  return (
    <a className="nh-hero" href={`post.html?slug=${post.slug}&lang=${lang}`}>
      <div className="nh-hero__cover" style={{ background: grad(post.cover) }}>
        <span className="blog-card__cover-pattern" aria-hidden="true"></span>
        <span className="nh-hero__tag">{`#${post.tags[0]}`}</span>
      </div>
      <div className="nh-hero__panel">
        <span className="nh-kicker">{nh.update}</span>
        <h3 className="nh-hero__title">{d.title}</h3>
        <time className="nh-hero__date" dateTime={post.publishedAt}>{fmtDate(post.publishedAt, lang)}</time>
      </div>
    </a>
  );
}

function PressCard({ post, lang, t, big }) {
  const d = post[lang];
  return (
    <a className={`nh-press ${big ? "nh-press--big" : ""}`} href={`post.html?slug=${post.slug}&lang=${lang}`}>
      <div className="nh-press__cover" style={{ background: grad(post.cover) }}>
        <span className="blog-card__cover-pattern" aria-hidden="true"></span>
      </div>
      <div className="nh-press__body">
        <span className="nh-kicker">{`#${post.tags[0]}`}</span>
        <h3 className="nh-press__title">{d.title}</h3>
        <time className="nh-press__date" dateTime={post.publishedAt}>{fmtDate(post.publishedAt, lang)}</time>
      </div>
    </a>
  );
}

function LoopCard({ post, lang }) {
  const d = post[lang];
  return (
    <a className="nh-loop-card" href={`post.html?slug=${post.slug}&lang=${lang}`} data-card style={{ background: grad(post.cover) }}>
      <span className="blog-card__cover-pattern" aria-hidden="true"></span>
      <div className="nh-loop-card__scrim"></div>
      <div className="nh-loop-card__content">
        <span className="nh-loop-card__author">
          <span className="blog-card__avatar" aria-hidden="true">{post.author.initials}</span>
          {post.author.name}
        </span>
        <p className="nh-loop-card__dek">{d.title}</p>
        <time className="nh-loop-card__date" dateTime={post.publishedAt}>{fmtDate(post.publishedAt, lang, false)}</time>
      </div>
    </a>
  );
}

function LoopCarousel({ posts, lang }) {
  const ref = React.useRef(null);
  const nudge = (dir) => {
    const el = ref.current; if (!el) return;
    const card = el.querySelector("[data-card]");
    const step = card ? card.getBoundingClientRect().width + 20 : 300;
    el.scrollBy({ left: dir * step, behavior: "smooth" });
  };
  return (
    <div className="nh-loop">
      <div className="nh-loop__rail" ref={ref}>
        <div className="nh-loop__pad">
          {posts.map((p) => <LoopCard key={p.slug} post={p} lang={lang} />)}
        </div>
      </div>
      <div className="nh-loop__arrows home-lineup__arrows">
        <button type="button" className="lineup-arrow" onClick={() => nudge(-1)} aria-label="Previous">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M10 3L5 8l5 5"/></svg>
        </button>
        <button type="button" className="lineup-arrow" onClick={() => nudge(1)} aria-label="Next">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M6 3l5 5-5 5"/></svg>
        </button>
      </div>
    </div>
  );
}

function BlogIndex() {
  const [lang, setLang] = useLang();
  const t = T[lang].blog;
  const nh = NH[lang];
  const posts = window.BLOG_POSTS;
  const [tag, setTag] = React.useState("all");

  React.useEffect(() => {
    const url = new URL(window.location.href);
    const canonical = url.origin + url.pathname;
    applySEO({
      title: lang === "ar" ? "مركز أخبار Innoveev" : "News Hub — Innoveev",
      description: nh.subtitle,
      keywords: ["Innoveev", "news", "Syria tech", "product studio", "press"],
      canonical, lang, type: "website",
      hreflangs: { en: `${url.origin}${url.pathname}?lang=en`, ar: `${url.origin}${url.pathname}?lang=ar`, "x-default": canonical },
    });
  }, [lang, nh]);

  const tags = React.useMemo(() => {
    const all = new Set();
    posts.forEach((p) => p.tags.forEach((x) => all.add(x)));
    return ["all", ...Array.from(all)];
  }, [posts]);

  const filtered = tag === "all" ? posts : posts.filter((p) => p.tags.includes(tag));
  const hero = filtered.find((p) => p.featured) || filtered[0];
  const afterHero = filtered.filter((p) => p !== hero);
  const press = afterHero.slice(0, 3);
  const loop = afterHero.slice(3, 11);
  const rest = afterHero.slice(11);

  return (
    <>
      <Nav />

      <header className="nh-top">
        <div className="container">
          <span className="eyebrow">{nh.eyebrow}</span>
          <h1 className="nh-top__title">{nh.title}</h1>
          <p className="nh-top__lede">{nh.subtitle}</p>
          <div className="blog-filters nh-filters">
            {tags.map((tg) => (
              <button key={tg} className={`blog-filters__chip ${tag === tg ? "is-active" : ""}`} onClick={() => setTag(tg)}>
                {tg === "all" ? nh.allTopics : `#${tg}`}
              </button>
            ))}
          </div>
        </div>
      </header>

      <section className="section section--tight nh-section">
        <div className="container">
          <h2 className="nh-head">{nh.latestNews}</h2>
          {hero && <NewsHero post={hero} lang={lang} nh={nh} t={t} />}
          {press.length > 0 && (
            <div className="nh-press-grid">
              {press.map((p) => <PressCard key={p.slug} post={p} lang={lang} t={t} />)}
            </div>
          )}
        </div>
      </section>

      {loop.length > 0 && (
        <section className="section section--tight nh-section">
          <div className="container">
            <div className="nh-head-row">
              <h2 className="nh-head">{nh.inTheLoop}</h2>
              <a href="#more" className="nh-viewall">{nh.viewAll}</a>
            </div>
          </div>
          <LoopCarousel posts={loop} lang={lang} />
        </section>
      )}

      <section className="section section--tight nh-section" id="more">
        <div className="container">
          <h2 className="nh-head">{nh.more}</h2>
          <ul className="blog-list">
            {(rest.length ? rest : afterHero).map((p) => (
              <PostRow key={p.slug} post={p} lang={lang} t={t} />
            ))}
          </ul>
          <Newsletter t={t} />
        </div>
      </section>

      <Footer />
      <BuildMode />
      <KeyboardEggs />
      <CookieBanner />
      <CustomCursor />
    </>
  );
}

function PostRow({ post, lang, t }) {
  const data = post[lang];
  return (
    <li className="blog-row">
      <a href={`post.html?slug=${post.slug}&lang=${lang}`} className="blog-row__link">
        <div className="blog-row__cover" style={{ background: grad(post.cover) }} aria-hidden="true">
          <span className="blog-card__cover-pattern"></span>
        </div>
        <div className="blog-row__body">
          <div className="blog-row__meta mono-meta">
            <time dateTime={post.publishedAt}>{fmtDate(post.publishedAt, lang, false)}</time>
            <span>·</span>
            <span>{post.readTime} {t.minRead}</span>
            <span>·</span>
            <span>{`#${post.tags[0]}`}</span>
          </div>
          <h3 className="blog-row__title">{data.title}</h3>
          <p className="blog-row__dek">{data.dek}</p>
          <div className="blog-row__foot">
            <span className="blog-card__author">
              <span className="blog-card__avatar" aria-hidden="true">{post.author.initials}</span>
              <span>{post.author.name}</span>
            </span>
            <span className="blog-row__arrow">{t.readMore} <Arrow /></span>
          </div>
        </div>
      </a>
    </li>
  );
}

function Newsletter({ t }) {
  const [submitted, setSubmitted] = React.useState(false);
  return (
    <aside className="newsletter">
      <div className="newsletter__copy">
        <h3 className="newsletter__title">{t.newsletter}</h3>
        <p className="newsletter__desc">{t.newsletterDesc}</p>
      </div>
      <form className="newsletter__form" onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }}>
        <input type="email" required placeholder={t.emailPlaceholder} className="newsletter__input" aria-label={t.emailPlaceholder} />
        <button type="submit" className="btn btn--primary">{submitted ? "✓" : t.subscribe}</button>
      </form>
    </aside>
  );
}

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