// HomeSections.jsx — секции главной: служение, где служим, новости, поддержка

const MINISTRIES = [
  { icon: "book-open", title: "Журнал «Тропинка»", text: "Служение детям через добрый христианский журнал — истории, стихи и творчество.", anchor: "sl-tropinka" },
  { icon: "book", title: "Журнал «Вера и жизнь»", text: "Служение словом для взрослых: размышления, свидетельства и ответы на вопросы веры.", anchor: "sl-vera" },
  { icon: "music", title: "Детский хор", text: "Музыкальное служение — дети прославляют Бога песнями надежды и радости.", anchor: "sl-hor" },
];

function Ministries({ onNav }) {
  return (
    <section className="home-ministries" style={{ background: "var(--cream)", padding: "104px 40px" }}>
      <div style={{ maxWidth: 1080, margin: "0 auto" }}>
        <SectionHead eyebrow="Служение" title="Как мы служим людям"
          intro="Вера, которая проявляется в делах. Выберите служение, чтобы узнать о нём подробнее." />
        <div className="home-ministries-list" style={{ marginTop: 52, borderTop: "1px solid var(--line-warm)" }}>
          {MINISTRIES.map((m, i) => <MinistryRow key={m.title} index={i + 1} {...m} onNav={onNav} />)}
        </div>
      </div>
    </section>
  );
}

function MinistryRow({ index, icon, title, text, anchor, onNav }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={() => onNav("Служение", anchor)}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ width: "100%", textAlign: "left", cursor: "pointer", background: "transparent",
        border: "none", borderBottom: "1px solid var(--line-warm)", padding: "30px 8px",
        display: "grid", gridTemplateColumns: "56px 28px 1fr auto", alignItems: "center", gap: 28,
        transition: "all .24s cubic-bezier(.22,1,.36,1)" }} className="kit-min-row home-min-row">
      <span className="home-min-index" style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 18,
        color: hover ? "var(--terracotta)" : "var(--stone-soft)", transition: "color .24s ease",
        fontVariantNumeric: "tabular-nums" }}>{String(index).padStart(2, "0")}</span>
      <span className="home-min-icon">
        <Icon name={icon} size={26} color={hover ? "var(--terracotta)" : "var(--graphite)"} strokeWidth={1.6} />
      </span>
      <span className="home-min-copy" style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        <span className="home-min-title" style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 23,
          letterSpacing: "-.01em", color: "var(--ink)" }}>{title}</span>
        <span className="home-min-text" style={{ fontFamily: "var(--font-ui)", fontSize: 15, lineHeight: 1.5,
          color: "var(--stone)", maxWidth: 560 }}>{text}</span>
      </span>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 9, fontFamily: "var(--font-ui)",
        fontWeight: 600, fontSize: 14.5, color: "var(--terracotta)", whiteSpace: "nowrap" }} className="kit-min-cta">
        <span className="home-min-arrow" style={{ display: "inline-flex", width: 38, height: 38, borderRadius: 999, flex: "none",
          alignItems: "center", justifyContent: "center",
          background: hover ? "var(--terracotta)" : "transparent",
          border: "1.5px solid var(--terracotta)", transition: "all .24s ease" }}>
          <Icon name="arrow-right" size={17} color={hover ? "var(--cream)" : "var(--terracotta)"} />
        </span>
      </span>
    </button>
  );
}

// Тёмно-зелёная секция «Где мы служим» — глубина, ощущение гор
function WhereWeServe({ bare } = {}) {
  const places = ["Владикавказ", "Беслан", "Алагир", "Ардон", "Дигора", "Моздок", "горные сёла"];
  const stats = [["12", "общин и групп"], ["8", "лет служения"], ["40+", "сёл и городов"], ["300+", "людей в служении"]];
  return (
    <section id="where-we-serve" style={{ background: "var(--green-deep)", padding: bare ? "0 40px 104px" : "104px 40px",
      position: "relative", overflow: "hidden", scrollMarginTop: 80 }}>
      <div data-anchor-content style={{ maxWidth: 1280, margin: "0 auto", position: "relative" }}>
        {!bare && (
          <Reveal>
            <SectionHead dark eyebrow="Где мы служим"
              title="От Владикавказа до горных сёл"
              intro="Наше служение охватывает города и отдалённые сёла Северной Осетии — там, где люди ждут слова надежды и доброй помощи." />
          </Reveal>
        )}
        <div style={{ display: "grid", gridTemplateColumns: "0.85fr 1.15fr", gap: 48,
          alignItems: "stretch", marginTop: bare ? 0 : 52 }} className="kit-2col">
          {/* левая колонка — города и цифры */}
          <Reveal delay={80} style={{ display: "flex", flexDirection: "column", gap: 28 }}>
            <div>
              <div className="caption" style={{ color: "rgba(243,238,218,.55)", marginBottom: 14 }}>Города и сёла служения</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
                {places.map((p) => (
                  <span key={p} style={{ fontFamily: "var(--font-ui)", fontSize: 14.5, fontWeight: 500,
                    color: "var(--cream)", padding: "9px 16px", borderRadius: 999,
                    border: "1px solid rgba(243,238,218,.28)", display: "inline-flex", alignItems: "center", gap: 7 }}>
                    <Icon name="map-pin" size={15} color="var(--terracotta-bright)" />{p}
                  </span>
                ))}
              </div>
            </div>
            <div className="serve-stats-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: "auto" }}>
              {stats.map(([n, l]) => (
                <div key={l} className="serve-stat-card" style={{ background: "rgba(243,238,218,.06)", border: "1px solid rgba(243,238,218,.14)",
                  borderRadius: 18, padding: "22px 20px" }}>
                  <div className="serve-stat-number" style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 40,
                    color: "var(--terracotta-bright)", lineHeight: 1 }}>{n}</div>
                  <div className="serve-stat-label" style={{ fontFamily: "var(--font-ui)", fontSize: 14, color: "rgba(243,238,218,.8)", marginTop: 8 }}>{l}</div>
                </div>
              ))}
            </div>
          </Reveal>
          {/* правая колонка — реальная карта */}
          <Reveal delay={160} style={{ width: "100%" }}>
            <ServeMap height={bare ? 500 : 460} />
          </Reveal>
        </div>
      </div>
    </section>
  );
}

// Превью-заглушка без текста: спокойный фирменный фон + крупная тихая иконка категории
function NewsThumb({ variant = "green", icon, zoom, image, style, className }) {
  const bg = {
    green: "radial-gradient(120% 100% at 80% 0%, #0a4a40 0%, #014138 60%, #052e28 100%)",
    terracotta: "radial-gradient(120% 100% at 80% 0%, #e0703f 0%, #D3613C 55%, #b44e2c 100%)",
    cream: "radial-gradient(120% 100% at 80% 0%, #efe7cf 0%, #e2d9bf 60%, #d4caac 100%)",
  }[variant];
  const iconColor = variant === "cream" ? "rgba(1,65,56,.20)" : "rgba(243,238,218,.26)";
  const sheen = variant === "cream"
    ? "linear-gradient(120deg, rgba(255,255,255,.5), rgba(255,255,255,0) 42%)"
    : "linear-gradient(120deg, rgba(243,238,218,.16), rgba(243,238,218,0) 42%)";
  // если есть реальное фото — показываем его (с мягким зумом при hover)
  if (image) {
    return (
      <div className={className} style={{ position: "relative", overflow: "hidden", background: "var(--green-deep-2)",
        borderRadius: 18, ...style }}>
        <img src={image} alt="" loading="lazy" style={{ position: "absolute", inset: 0,
          width: "100%", height: "100%", objectFit: "cover", display: "block",
          transform: zoom ? "scale(1.06)" : "scale(1)",
          transition: "transform .5s cubic-bezier(.22,1,.36,1)" }} />
      </div>
    );
  }
  return (
    <div className={className} style={{ position: "relative", overflow: "hidden", background: bg, borderRadius: 18, ...style }}>
      <div style={{ position: "absolute", inset: 0, background: sheen }} />
      <div style={{ position: "absolute", right: "-6%", bottom: "-14%", lineHeight: 0,
        transform: `rotate(-8deg) scale(${zoom ? 1.06 : 1})`, transformOrigin: "70% 70%",
        transition: "transform .4s cubic-bezier(.22,1,.36,1)" }}>
        <Icon name={icon} size={150} color={iconColor} strokeWidth={1.25} />
      </div>
    </div>
  );
}

function News({ onNav, hidden = false }) {
  if (hidden) return null;

  const open = (id) => (window.__openNews ? window.__openNews(id) : onNav("Новости"));
  const newsItems = useNewsData();
  const [a, b, c] = newsItems;
  return (
    <section style={{ background: "var(--cream)", padding: "104px 40px" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto" }}>
        <SectionHead eyebrow="Новости" title="Жизнь миссии" />
        <div className="kit-news-bento" style={{ marginTop: 48, display: "grid",
          gridTemplateColumns: "1.55fr 1fr", gridTemplateRows: "auto auto", gap: 22 }}>
          {a && <NewsFeature item={a} onOpen={open} style={{ gridColumn: 1, gridRow: 1 }} />}
          {b && <NewsTall item={b} onOpen={open} style={{ gridColumn: 2, gridRow: "1 / span 2" }} />}
          {c && <NewsWide item={c} onOpen={open} style={{ gridColumn: 1, gridRow: 2 }} />}
        </div>
        <div style={{ display: "flex", justifyContent: "center", marginTop: 42 }}>
          <Button variant="secondary" iconRight="arrow-right" onClick={() => onNav("Новости")}>Все новости</Button>
        </div>
      </div>
    </section>
  );
}

function cardShell(hover) {
  // без карточности: прозрачный фон, без рамки и тени
  return {
    textAlign: "left", cursor: "pointer", background: "transparent", border: "none",
    padding: 0, display: "flex", transition: "all .26s cubic-bezier(.22,1,.36,1)",
  };
}

function NewsMeta({ tag, date }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
      <Badge tone="soft">{tag}</Badge>
      <span className="caption">{date}</span>
    </div>
  );
}

// Широкая «featured» — крупное превью сверху, текст снизу
function NewsFeature({ item, onOpen, style }) {
  const { tag, date, title, excerpt, icon, thumb, image } = item;
  const [h, setH] = React.useState(false);
  return (
    <button onClick={() => onOpen(item.id)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ ...cardShell(h), flexDirection: "column", ...style }}>
      <NewsThumb variant={thumb} image={image} icon={icon} zoom={h}
        style={{ height: 240, width: "100%" }} className="home-news-thumb" />
      <div style={{ padding: "22px 4px 0" }}>
        <NewsMeta tag={tag} date={date} />
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 27,
          letterSpacing: "-.01em", lineHeight: 1.2, color: h ? "var(--terracotta)" : "var(--ink)",
          margin: "0 0 12px", textWrap: "pretty", transition: "color .2s ease" }}>{title}</h3>
        <p style={{ fontFamily: "var(--font-ui)", fontSize: 15.5, lineHeight: 1.55, color: "var(--stone)", margin: 0, maxWidth: 520 }}>{excerpt}</p>
      </div>
    </button>
  );
}

// Узкая вертикальная — превью занимает большую часть высоты
function NewsTall({ item, onOpen, style }) {
  const { tag, date, title, excerpt, icon, thumb, image } = item;
  const [h, setH] = React.useState(false);
  return (
    <button onClick={() => onOpen(item.id)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ ...cardShell(h), flexDirection: "column", ...style }}>
      <NewsThumb variant={thumb} image={image} icon={icon} zoom={h}
        style={{ flex: 1, minHeight: 240, width: "100%" }} className="home-news-thumb" />
      <div style={{ padding: "20px 4px 0" }}>
        <NewsMeta tag={tag} date={date} />
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 20,
          letterSpacing: "-.005em", lineHeight: 1.25, color: h ? "var(--terracotta)" : "var(--ink)",
          margin: "0 0 10px", textWrap: "pretty", transition: "color .2s ease" }}>{title}</h3>
        <p style={{ fontFamily: "var(--font-ui)", fontSize: 14, lineHeight: 1.5, color: "var(--stone)", margin: 0 }}>{excerpt}</p>
      </div>
    </button>
  );
}

// Широкая горизонтальная — превью слева, текст справа
function NewsWide({ item, onOpen, style }) {
  const { tag, date, title, excerpt, icon, thumb, image } = item;
  const [h, setH] = React.useState(false);
  return (
    <button onClick={() => onOpen(item.id)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ ...cardShell(h), flexDirection: "row", alignItems: "stretch", gap: 24, ...style }} className="kit-news-wide">
      <NewsThumb variant={thumb} image={image} icon={icon} zoom={h}
        style={{ width: 230, flex: "none", minHeight: 170 }} className="home-news-thumb" />
      <div style={{ padding: "4px 0", display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <NewsMeta tag={tag} date={date} />
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 21,
          letterSpacing: "-.005em", lineHeight: 1.25, color: h ? "var(--terracotta)" : "var(--ink)",
          margin: "0 0 8px", textWrap: "pretty", transition: "color .2s ease" }}>{title}</h3>
        <p style={{ fontFamily: "var(--font-ui)", fontSize: 14.5, lineHeight: 1.5, color: "var(--stone)", margin: 0, maxWidth: 460 }}>{excerpt}</p>
      </div>
    </button>
  );
}

// Тёплый терракотовый призыв к поддержке
function SupportCTA({ onNav }) {
  return (
    <section style={{ padding: "40px" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", background: "var(--terracotta)",
        borderRadius: 32, padding: "72px 56px", position: "relative", overflow: "hidden",
        textAlign: "center" }}>
        <div style={{ position: "relative", maxWidth: 680, margin: "0 auto" }}>
          <h2 className="h1" style={{ color: "var(--cream)", margin: "0 0 16px" }}>Поддержите служение</h2>
          <p className="lead" style={{ color: "rgba(243,238,218,.9)", margin: "0 0 32px" }}>
            Ваша поддержка помогает нести надежду людям Северной Осетии — в молитве,
            словом и делом. Станьте частью миссии.
          </p>
          <div style={{ display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap" }}>
            <Button variant="dark" size="lg" icon="heart" onClick={() => onNav("Поддержать")}>Поддержать миссию</Button>
          </div>
        </div>
      </div>
    </section>
  );
}

// Краткий контактный блок для главной — основные данные + переход к форме
function HomeContact({ onNav }) {
  const items = [
    { icon: "map-pin", h: "Адрес", t: "г. Владикавказ, Северная Осетия" },
    { icon: "mail", h: "Почта", t: "nomcc@mail.ru" },
    { icon: "phone", h: "Телефон", t: "8 (867) 251-68-83" },
  ];
  return (
    <section style={{ background: "var(--cream)", padding: "96px 40px" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "grid",
        gridTemplateColumns: "1fr 1fr", gap: 64, alignItems: "center" }} className="kit-2col">
        <div>
          <SectionHead eyebrow="Контакты" title="Свяжитесь с нами"
            intro="Мы рады знакомству, молитве и общению. Напишите нам — ответим в ближайшее время." />
          <div style={{ marginTop: 32 }}>
            <Button variant="primary" iconRight="arrow-right" onClick={() => onNav("Контакты")}>Написать нам</Button>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          {items.map((it) => (
            <button key={it.h} onClick={() => onNav("Контакты")} style={{ display: "flex", gap: 16,
              alignItems: "center", background: "transparent", border: "none", padding: 0,
              textAlign: "left", cursor: "pointer" }}>
              <span style={{ width: 52, height: 52, borderRadius: 14, background: "#fff",
                border: "1px solid var(--line)", display: "flex", alignItems: "center",
                justifyContent: "center", flex: "none" }}>
                <Icon name={it.icon} size={22} color="var(--terracotta)" />
              </span>
              <span>
                <span className="caption" style={{ display: "block", marginBottom: 2 }}>{it.h}</span>
                <span style={{ fontFamily: "var(--font-ui)", fontSize: 16, fontWeight: 500, color: "var(--ink)" }}>{it.t}</span>
              </span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Ministries, WhereWeServe, News, SupportCTA, HomeContact, NewsFeature, NewsTall, NewsWide, NewsThumb, MinistryRow });
