// NewsPage.jsx — раздел «Новости»: список из NEWS_DATA. Каждая новость кликабельна
// и ведёт на детальную страницу (NewsArticle). Структура готова под админку:
// список (NewsPage) → карточка (NewsListItem) → детальная (NewsArticle).

function openNews(id) {
  if (window.__openNews) window.__openNews(id);
}

// Карточка в списке: превью-заглушка слева, текст справа (без «карточности»)
function NewsListItem({ item, onOpen }) {
  const [h, setH] = React.useState(false);
  return (
    <button onClick={() => onOpen(item.id)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ width: "100%", textAlign: "left", cursor: "pointer", background: "transparent",
        border: "none", borderTop: "1px solid var(--line-warm)", padding: "28px 4px",
        display: "flex", gap: 28, alignItems: "center", transition: "all .24s ease" }}
      className="news-list-item">
      <NewsThumb variant={item.thumb} image={item.image} icon={item.icon} zoom={h}
        style={{ width: 200, height: 132, flex: "none" }} className="news-list-thumb" />
      <div style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
          <Badge tone="soft">{item.tag}</Badge>
          <span className="caption">{item.date}</span>
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 23,
          letterSpacing: "-.01em", lineHeight: 1.2, color: h ? "var(--terracotta)" : "var(--ink)",
          margin: "0 0 8px", textWrap: "pretty", transition: "color .2s ease" }}>{item.title}</h3>
        <p style={{ fontFamily: "var(--font-ui)", fontSize: 15.5, lineHeight: 1.55,
          color: "var(--stone)", margin: 0, maxWidth: 620, textWrap: "pretty" }}>{item.excerpt}</p>
      </div>
      <span style={{ display: "inline-flex", width: 40, height: 40, borderRadius: 999, flex: "none",
        alignItems: "center", justifyContent: "center",
        background: h ? "var(--terracotta)" : "transparent",
        border: "1.5px solid var(--terracotta)", transition: "all .24s ease" }} className="news-list-arrow">
        <Icon name="arrow-right" size={18} color={h ? "var(--cream)" : "var(--terracotta)"} />
      </span>
    </button>
  );
}

function NewsPage({ onOpen }) {
  const open = onOpen || openNews;
  const newsItems = useNewsData();
  return (
    <div>
      <PageHero eyebrow="Новости" title="Жизнь миссии"
        intro="Коротко о том, чем живёт миссия — служение, события, медиа и объявления."
        image="../../assets/page-heroes/news.png" imagePosition="center center" />
      <section style={{ background: "var(--cream)", padding: "72px 40px 96px" }}>
        <div style={{ maxWidth: 980, margin: "0 auto" }}>
          {newsItems.map((n) => <NewsListItem key={n.id} item={n} onOpen={open} />)}
          <div style={{ borderTop: "1px solid var(--line-warm)" }} />
        </div>
      </section>
    </div>
  );
}

function NewsGallery({ title, photos, articleTitle }) {
  const trackRef = React.useRef(null);
  const hasMany = photos.length > 1;
  const scrollGallery = (direction) => {
    const track = trackRef.current;
    if (!track) return;
    track.scrollBy({
      left: direction * track.clientWidth,
      behavior: "smooth",
    });
  };

  return (
    <div style={{ marginTop: 42 }}>
      <style>{`
        .news-gallery-track {
          display: flex;
          gap: 14px;
          overflow-x: auto;
          overscroll-behavior-x: contain;
          scroll-snap-type: x mandatory;
          scroll-padding-inline: 0;
          padding: 2px 0 14px;
          scrollbar-width: thin;
        }
        .news-gallery-track::-webkit-scrollbar {
          height: 8px;
        }
        .news-gallery-track::-webkit-scrollbar-thumb {
          background: var(--line-warm);
          border-radius: 999px;
        }
        .news-gallery-slide {
          flex: 0 0 100%;
          min-width: 0;
          scroll-snap-align: start;
        }
        .news-gallery-arrow {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          z-index: 2;
          width: 40px;
          height: 40px;
          border-radius: 999px;
          border: 1px solid rgba(243,238,218,.82);
          background: rgba(255,255,255,.92);
          cursor: pointer;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 8px 22px rgba(30,26,22,.14);
        }
        .news-gallery-arrow-left {
          left: 12px;
        }
        .news-gallery-arrow-right {
          right: 12px;
        }
        @media (max-width: 720px) {
          .news-gallery-arrow {
            width: 36px;
            height: 36px;
          }
          .news-gallery-arrow-left {
            left: 10px;
          }
          .news-gallery-arrow-right {
            right: 10px;
          }
        }
      `}</style>
      <div style={{ marginBottom: 18 }}>
        {title && <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 26,
          letterSpacing: "-.01em", color: "var(--ink)", margin: 0 }}>{title}</h2>}
      </div>
      <div style={{ position: "relative" }}>
        {hasMany && (
          <button type="button" className="news-gallery-arrow news-gallery-arrow-left"
            onClick={() => scrollGallery(-1)} aria-label="Предыдущая фотография">
            <Icon name="chevron-left" size={19} color="var(--terracotta)" />
          </button>
        )}
        <div ref={trackRef} className="news-gallery-track" aria-label={title || "Дополнительные фотографии"}>
          {photos.map((photo, i) => (
            <figure key={`${photo.image}-${i}`} className="news-gallery-slide" style={{ margin: 0 }}>
              <div style={{ width: "100%", aspectRatio: "16 / 10", maxHeight: 360,
                borderRadius: 18, overflow: "hidden", background: "var(--line-warm)" }}>
                <img src={photo.image} alt={photo.alt || articleTitle} loading="lazy"
                  style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
              </div>
              {photo.caption && <figcaption className="caption" style={{ marginTop: 8 }}>{photo.caption}</figcaption>}
            </figure>
          ))}
        </div>
        {hasMany && (
          <button type="button" className="news-gallery-arrow news-gallery-arrow-right"
            onClick={() => scrollGallery(1)} aria-label="Следующая фотография">
            <Icon name="chevron-right" size={19} color="var(--terracotta)" />
          </button>
        )}
      </div>
    </div>
  );
}

// Детальная страница новости
function NewsArticle({ id, onOpen, onBack }) {
  const newsItems = useNewsData();
  const item = newsItems.find((n) => n.id === id) || getNewsById(id);
  const open = onOpen || openNews;

  if (!item) {
    return (
      <div>
        <PageHero eyebrow="Новости" title="Новость не найдена"
          intro="Возможно, материал был перемещён. Вернитесь к списку новостей."
          image="../../assets/page-heroes/news.png" imagePosition="center center" />
        <section style={{ background: "var(--cream)", padding: "80px 40px", textAlign: "center" }}>
          <Button variant="secondary" icon="arrow-left" onClick={() => (onBack ? onBack() : open(null))}>Ко всем новостям</Button>
        </section>
      </div>
    );
  }

  const others = newsItems.filter((n) => n.id !== item.id).slice(0, 3);

  return (
    <div>
      {/* Шапка статьи на тёмно-зелёном */}
      <section style={{ background: "var(--green-deep)", padding: "112px 40px 64px", position: "relative" }}>
        <div style={{ maxWidth: 820, margin: "0 auto" }}>
          <button onClick={() => (onBack ? onBack() : open(null))} style={{ background: "transparent",
            border: "none", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8,
            color: "rgba(243,238,218,.8)", fontFamily: "var(--font-ui)", fontSize: 14.5, fontWeight: 500,
            padding: 0, marginBottom: 26 }}>
            <Icon name="arrow-left" size={17} color="var(--terracotta-bright)" /> Ко всем новостям
          </button>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
            <Badge tone="solid">{item.tag}</Badge>
            <span style={{ fontFamily: "var(--font-ui)", fontSize: 14, color: "rgba(243,238,218,.7)" }}>{item.date}</span>
            <span style={{ fontFamily: "var(--font-ui)", fontSize: 14, color: "rgba(243,238,218,.5)" }}>· {item.readMin} мин чтения</span>
          </div>
          <h1 className="h1" style={{ color: "var(--cream)", margin: 0, textWrap: "balance" }}>{item.title}</h1>
          <p className="lead" style={{ color: "rgba(243,238,218,.78)", margin: "18px 0 0", maxWidth: 680 }}>{item.excerpt}</p>
        </div>
      </section>

      {/* Крупное превью показываем только если в новости выбрана главная фотография */}
      {item.image && (
        <section style={{ background: "var(--cream)", padding: "0 40px" }}>
          <div style={{ maxWidth: 980, margin: "0 auto" }}>
            <NewsThumb variant={item.thumb} image={item.image} icon={item.icon}
              style={{ width: "100%", height: 360, marginTop: -44, borderRadius: 24,
                boxShadow: "var(--shadow-lg)" }} />
          </div>
        </section>
      )}

      {/* Тело статьи */}
      <section style={{ background: "var(--cream)", padding: "56px 40px 88px" }}>
        <div style={{ maxWidth: 720, margin: "0 auto" }}>
          {item.body.map((b, i) => {
            if (b.type === "h") return (
              <h2 key={i} style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 26,
                letterSpacing: "-.01em", color: "var(--ink)", margin: "36px 0 14px" }}>{b.text}</h2>
            );
            if (b.type === "quote") return (
              <blockquote key={i} style={{ margin: "28px 0", padding: "4px 0 4px 24px",
                borderLeft: "3px solid var(--terracotta)", fontFamily: "var(--font-display)",
                fontWeight: 500, fontSize: 22, lineHeight: 1.4, letterSpacing: "-.01em",
                color: "var(--graphite)", textWrap: "pretty" }}>{b.text}</blockquote>
            );
            return (
              <p key={i} style={{ fontFamily: "var(--font-ui)", fontSize: 17.5, lineHeight: 1.7,
                color: "var(--graphite)", margin: "0 0 18px", textWrap: "pretty" }}>{b.text}</p>
            );
          })}

          {item.gallery && item.gallery.length > 0 && (
            <NewsGallery title={item.galleryTitle} photos={item.gallery} articleTitle={item.title} />
          )}

          <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 40,
            paddingTop: 24, borderTop: "1px solid var(--line-warm)" }}>
            <div style={{ width: 42, height: 42, borderRadius: 999, background: "rgba(211,97,60,.12)",
              display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
              <Icon name="users" size={20} color="var(--terracotta)" />
            </div>
            <div>
              <div className="caption" style={{ marginBottom: 1 }}>Автор</div>
              <div style={{ fontFamily: "var(--font-ui)", fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>{item.author}</div>
            </div>
          </div>
        </div>
      </section>

      {/* Другие новости */}
      <section style={{ background: "#fff", padding: "72px 40px", borderTop: "1px solid var(--line)" }}>
        <div style={{ maxWidth: 980, margin: "0 auto" }}>
          <h2 className="h1" style={{ fontSize: 30, margin: "0 0 32px" }}>Другие новости</h2>
          <div className="other-news-slider" style={{ display: "flex", gap: 22, overflowX: "auto",
            overscrollBehaviorX: "contain", scrollSnapType: "x mandatory", padding: "2px 2px 16px",
            scrollbarWidth: "thin" }}>
            {others.map((n) => {
              return <OtherNews key={n.id} item={n} onOpen={open} />;
            })}
          </div>
        </div>
      </section>
    </div>
  );
}

function OtherNews({ item, onOpen }) {
  const [h, setH] = React.useState(false);
  return (
    <button onClick={() => onOpen(item.id)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ textAlign: "left", cursor: "pointer", background: "transparent", border: "none",
        padding: 0, display: "flex", flexDirection: "column", gap: 14,
        flex: "0 0 min(31.8%, 292px)", minWidth: 240, scrollSnapAlign: "start" }}
      className="other-news-card">
      <NewsThumb variant={item.thumb} image={item.image} icon={item.icon} zoom={h}
        style={{ width: "100%", height: 150 }} className="other-news-thumb" />
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 8 }}>
          <Badge tone="soft">{item.tag}</Badge>
          <span className="caption">{item.date}</span>
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18,
          letterSpacing: "-.005em", lineHeight: 1.25, color: h ? "var(--terracotta)" : "var(--ink)",
          margin: 0, textWrap: "pretty", transition: "color .2s ease" }}>{item.title}</h3>
      </div>
    </button>
  );
}

Object.assign(window, { NewsPage, NewsArticle, NewsGallery, NewsListItem, OtherNews });
