/* Sayings — the second strip on the landing page, under Media.
   Built on the card system from mnc-bio-site: a tinted panel carrying its own
   line pattern, the saying set as poster type in that tint, a hover lift, one
   shared height so the row reads as a band, a reader for the whole text and a
   share button. Twenty sayings instead of nine posts, so the tints, patterns,
   widths and the two poster layouts vary across the set.

     1. horizontal scroll — snap rail; native swipe on touch, arrows on desktop
     2. random order      — reshuffled on every load, and reshuffled again until
                            no two neighbours carry the same tint, so the colour
                            rhythm of the row survives the randomness
     3. share             — IgShareButton: the device's own sheet first, our own
                            popover after
*/

/* ─────────────────────────────────────────────────────────────────────────
   CONFIG — the sayings.

     topic  short label for the card's top line. The client filed each saying
            under a Turkish topic; these are those topics in English, since the
            strip is English-facing.
     text   the saying, verbatim. This is the source of truth: nothing on the
            card is written by hand, the poster lines are cut out of it.
     lead   the phrase set large in the card's tint. It must be a prefix of
            `text` (after `kick`, where there is one) — the remainder is what
            falls to the italic line beneath, so the card can never say
            anything the saying does not say, in an order it does not say it.
     kick   shout layout only: the quieter line above the lead, and the first
            prefix of `text`.
     layout "hero" sets the lead as one big line; "shout" splits it across a
            quiet kicker and a loud second line, the way the MNC cards
            alternate.
     tint   one of the five poster tints.
     size   s5 / s6 / s7 — the card's width, chosen by how much copy it carries.
     pat    the panel's line pattern.
   ───────────────────────────────────────────────────────────────────────── */
const MEC_SAYINGS = [
  { id: 1, topic: "Readiness for the Hereafter", layout: "hero", tint: "bordo", size: "s6", pat: 0,
    lead: "A mature believer",
    text: "A mature believer is one who is ready for that transition to the Hereafter by becoming a servant Allah is pleased with." },
  { id: 2, topic: "Living together", layout: "shout", tint: "forest", size: "s5", pat: 1,
    kick: "Islam is",
    lead: "a way of living together.",
    text: "Islam is a way of living together. A Faith built for community." },
  { id: 3, topic: "Good character", layout: "hero", tint: "slate", size: "s6", pat: 2,
    lead: "We must remove bad traits from our hearts",
    text: "We must remove bad traits from our hearts and strive to beautify our character with mercy, love, and kindness." },
  { id: 4, topic: "Serving Islam", layout: "shout", tint: "gold", size: "s6", pat: 3,
    kick: "Wherever you are or whatever your past",
    lead: "you can serve Islam.",
    text: "Wherever you are or whatever your past you can serve Islam. That’s how Islam spread." },
  { id: 5, topic: "Faith in Allah", layout: "hero", tint: "ink", size: "s7", pat: 4,
    lead: "The Chapter of Purity of Faith",
    text: "The Chapter of Purity of Faith (Al-Ikhlas) sums it up beautifully: 1. Say [to those who wonder and ask about the true nature of Allah]: “He [is] Allah, the Unique One [of absolute Oneness and Indivisibility]! 2. Allah, the Eternal [the One Whom all creation is dependent on, while He does not depend on anything]! 3. He never had offspring, nor was He born, [He is the Only Deity]. 4. And there is [absolutely] none comparable to Him.” [Quran, 112:1-4]" },
  { id: 6, topic: "True faith", layout: "hero", tint: "bordo", size: "s6", pat: 5,
    lead: "I assure you, with certainty,",
    text: "I assure you, with certainty, without True Faith (Īmān) in Allah Almighty, nothing is truly achieved. It will fail both in this life and in the Hereafter." },
  { id: 7, topic: "The purpose of life", layout: "hero", tint: "forest", size: "s6", pat: 6,
    lead: "The Quran bears witness",
    text: "The Quran bears witness that our greatest responsibility is to know and seek the One Who created us." },
  { id: 8, topic: "Love for parents", layout: "shout", tint: "gold", size: "s5", pat: 7,
    kick: "Respect your parents.",
    lead: "Cherish them.",
    text: "Respect your parents. Cherish them. Humble yourself before them with love." },
  { id: 9, topic: "True love", layout: "shout", tint: "slate", size: "s6", pat: 8,
    kick: "The source, the essence, the ultimate reality of all love",
    lead: "is the Love of Allah Almighty.",
    text: "The source, the essence, the ultimate reality of all love is the Love of Allah Almighty." },
  { id: 10, topic: "The environment as worship", layout: "hero", tint: "forest", size: "s7", pat: 9,
    lead: "Caring for the environment",
    text: "Caring for the environment is not a trend, nor a performance. It’s a serious responsibility, a true act of service and an act of worship for the Sake of Allah Almighty." },
  { id: 11, topic: "Islam for everyone", layout: "shout", tint: "gold", size: "s7", pat: 10,
    kick: "Islam is",
    lead: "a way of life that benefits everyone.",
    text: "Islam is a way of life that benefits everyone. It uplifts, supports, and fulfils. It gives dignity, peace, and purpose to the unlearned, the overlooked, the forgotten. And at the same time, it offers depth, meaning, and fulfilment to the intellectual, the thoughtful, the wise." },
  { id: 12, topic: "The message of all Prophets", layout: "hero", tint: "ink", size: "s6", pat: 11,
    lead: "The message of every Prophet,",
    text: "The message of every Prophet, from Adam to Muhammad, peace be upon them all, is summed up in one truth: Islam." },
  { id: 13, topic: "The final way of life", layout: "shout", tint: "bordo", size: "s6", pat: 0,
    kick: "Islam is",
    lead: "the final, complete and preserved Lifestyle",
    text: "Islam is the final, complete and preserved Lifestyle chosen by Allah Almighty for all." },
  { id: 14, topic: "Responsibilities and rights", layout: "hero", tint: "slate", size: "s6", pat: 1,
    lead: "A mature believer",
    text: "A mature believer fulfills responsibilities with grace and balance neither neglecting nor overdoing them, and without causing harm." },
  { id: 15, topic: "The essence of the Books", layout: "hero", tint: "gold", size: "s7", pat: 2,
    lead: "The Quran declares",
    text: "The Quran declares that it contains the essence of all Divine Books and that the Prophets of Allah brought the same core message: “There is no deity worthy of worship except Allah.”" },
  { id: 16, topic: "Following the Sunnah", layout: "hero", tint: "forest", size: "s7", pat: 3,
    lead: "Our Master, the Prophet Muhammad,",
    text: "Our Master, the Prophet Muhammad, peace be upon him, is the one to whom the Quran was revealed. So he knew it best and more than that he practiced it better than anyone else. That is why learning about him and following his lifestyle (Sunnah) is not an option. It is the way!" },
  { id: 17, topic: "Love of the Prophet", layout: "hero", tint: "bordo", size: "s7", pat: 4,
    lead: "When you truly understand",
    text: "When you truly understand that everything is from Allah loving Him isn’t just natural it becomes essential. That love begins to overflow. And with it comes something amazing: The love of everything He loves. Beginning with the one He sent as a Mercy to the Worlds, our Master, the Beloved of Allah Almighty, Prophet Muhammad, peace be upon him." },
  { id: 18, topic: "Training the self", layout: "hero", tint: "ink", size: "s6", pat: 5,
    lead: "Life is a serious struggle,",
    text: "Life is a serious struggle, a relentless battle, a constant effort. Therefore, this oppressive Self must be reformed. Peace and success in both worlds, true prosperity, and real happiness are only found through the training and purification of the Self." },
  { id: 19, topic: "Family ties", layout: "hero", tint: "slate", size: "s6", pat: 6,
    lead: "Strong family ties",
    text: "Strong family ties are Islam’s gift for us. We share joyful moments, exchange gifts, heal broken relationships, touch hearts, and ask for their prayers." },
  { id: 20, topic: "Worship", layout: "shout", tint: "gold", size: "s5", pat: 7,
    kick: "Worship means",
    lead: "obedience to Allah.",
    text: "Worship means obedience to Allah. You are duty-bound. Yes! We are all duty-bound, to obey Him throughout our lives." },
];

/* The pattern geometry differs card to card, as on the MNC panels: the same
   two families, walked at different angles, radii and origins. */
const SY_PATTERNS = [
  "repeating-radial-gradient(circle at 90% -8%,transparent 0,transparent 48px,color-mix(in srgb,var(--tint) 10%,transparent) 48px,color-mix(in srgb,var(--tint) 10%,transparent) 49px)",
  "repeating-linear-gradient(115deg,transparent 0,transparent 30px,color-mix(in srgb,var(--tint) 8%,transparent) 30px,color-mix(in srgb,var(--tint) 8%,transparent) 31px)",
  "repeating-radial-gradient(circle at 10% -12%,transparent 0,transparent 50px,color-mix(in srgb,var(--tint) 9%,transparent) 50px,color-mix(in srgb,var(--tint) 9%,transparent) 51px)",
  "repeating-linear-gradient(65deg,transparent 0,transparent 26px,color-mix(in srgb,var(--tint) 8%,transparent) 26px,color-mix(in srgb,var(--tint) 8%,transparent) 27px)",
  "repeating-radial-gradient(circle at 96% 108%,transparent 0,transparent 52px,color-mix(in srgb,var(--tint) 8%,transparent) 52px,color-mix(in srgb,var(--tint) 8%,transparent) 53px)",
  "repeating-radial-gradient(circle at 8% 120%,transparent 0,transparent 56px,color-mix(in srgb,var(--tint) 9%,transparent) 56px,color-mix(in srgb,var(--tint) 9%,transparent) 57px)",
  "repeating-linear-gradient(115deg,transparent 0,transparent 32px,color-mix(in srgb,var(--tint) 8%,transparent) 32px,color-mix(in srgb,var(--tint) 8%,transparent) 33px)",
  "repeating-radial-gradient(circle at 88% 6%,transparent 0,transparent 46px,color-mix(in srgb,var(--tint) 10%,transparent) 46px,color-mix(in srgb,var(--tint) 10%,transparent) 47px)",
  "repeating-radial-gradient(circle at 50% 130%,transparent 0,transparent 54px,color-mix(in srgb,var(--tint) 9%,transparent) 54px,color-mix(in srgb,var(--tint) 9%,transparent) 55px)",
  "repeating-radial-gradient(circle at 104% 98%,transparent 0,transparent 44px,color-mix(in srgb,var(--tint) 8%,transparent) 44px,color-mix(in srgb,var(--tint) 8%,transparent) 45px)",
  "repeating-linear-gradient(115deg,transparent 0,transparent 30px,color-mix(in srgb,var(--tint) 6%,transparent) 30px,color-mix(in srgb,var(--tint) 6%,transparent) 31px)",
  "repeating-radial-gradient(circle at 50% 130%,transparent 0,transparent 58px,color-mix(in srgb,var(--tint) 9%,transparent) 58px,color-mix(in srgb,var(--tint) 9%,transparent) 59px)",
];

const SAYINGS_I18N = {
  read_full: { en: "Read in full", tr: "Tamamını oku", es: "Leer completo", de: "Vollständig lesen", fr: "Lire en entier", ru: "Читать целиком", ja: "全文を読む", zh: "阅读全文" },
  share_saying: { en: "Share this saying", tr: "Bu sözü paylaş", es: "Compartir este dicho", de: "Diesen Ausspruch teilen", fr: "Partager cette parole", ru: "Поделиться изречением", ja: "この言葉をシェア", zh: "分享这段话" },
  close: { en: "Close", tr: "Kapat", es: "Cerrar", de: "Schließen", fr: "Fermer", ru: "Закрыть", ja: "閉じる", zh: "关闭" },
  prev: { en: "Previous", tr: "Önceki", es: "Anterior", de: "Zurück", fr: "Précédent", ru: "Назад", ja: "前へ", zh: "上一个" },
  next: { en: "Next", tr: "Sonraki", es: "Siguiente", de: "Weiter", fr: "Suivant", ru: "Вперёд", ja: "次へ", zh: "下一个" },
};
function sayingT(key, lang) { const e = SAYINGS_I18N[key]; return (e && (e[lang] || e.en)) || ""; }

const SAYINGS_ATTRIBUTION = "M.E.C.";
const SAYINGS_BY = "Mahmud Esad Coşan";

/* A fresh order every load, but never two cards of one tint side by side.
   Redrawing until the neighbours happen to differ looked fine and was not: with
   these twenty only about one draw in seven comes out clean, so a handful of
   loads a day would clump. This places instead of retries. Each tint group is
   shuffled, the groups are ordered largest first (ties broken at random), and
   the flattened list is dealt into the even slots and then the odd ones — the
   standard placement, which cannot put two of a tint together as long as no
   tint holds more than half the cards. Both shuffles keep it random. */
function sayingsShuffle(list) {
  const shuffle = (a) => {
    a = a.slice();
    for (let i = a.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const t = a[i]; a[i] = a[j]; a[j] = t;
    }
    return a;
  };
  const groups = {};
  for (const s of shuffle(list)) (groups[s.tint] = groups[s.tint] || []).push(s);
  const ordered = shuffle(Object.keys(groups)).sort((a, b) => groups[b].length - groups[a].length);
  const flat = [];
  ordered.forEach((k) => flat.push(...groups[k]));
  const out = new Array(flat.length);
  let slot = 0;
  for (const s of flat) {
    out[slot] = s;
    slot += 2;
    if (slot >= flat.length) slot = 1;
  }
  return out;
}

/* ───── The strip ───── */
function SayingsStrip({ mobile = false, accent = "#B89968" }) {
  const [lang] = (typeof useLang === "function" ? useLang() : ["en"]);
  const t = (k) => sayingT(k, lang);
  const cards = React.useMemo(() => sayingsShuffle(MEC_SAYINGS), []);
  const railRef = React.useRef(null);
  const prevRef = React.useRef(null);
  const nextRef = React.useRef(null);
  const barRef = React.useRef(null);
  const [open, setOpen] = React.useState(null);

  const syncEdges = React.useCallback(() => {
    const el = railRef.current; if (!el) return;
    const max = el.scrollWidth - el.clientWidth;
    if (prevRef.current) prevRef.current.setAttribute("aria-disabled", String(el.scrollLeft <= 8));
    if (nextRef.current) nextRef.current.setAttribute("aria-disabled", String(el.scrollLeft >= max - 8));
    /* the progress bar is the viewport drawn onto the row: as wide as the
       visible share of it, sitting as far along as the scroll has come */
    if (barRef.current) {
      barRef.current.style.width = Math.min(100, el.clientWidth / el.scrollWidth * 100) + "%";
      barRef.current.style.left = (max ? el.scrollLeft / el.scrollWidth * 100 : 0) + "%";
    }
  }, []);

  React.useEffect(() => {
    syncEdges();
    const el = railRef.current; if (!el) return;
    el.addEventListener("scroll", syncEdges, { passive: true });
    window.addEventListener("resize", syncEdges);
    return () => { el.removeEventListener("scroll", syncEdges); window.removeEventListener("resize", syncEdges); };
  }, [syncEdges]);

  const nudge = (dir) => {
    const el = railRef.current; if (!el) return;
    const card = el.querySelector("[data-saying-card]");
    const step = (card ? card.getBoundingClientRect().width : 420) + 24;
    const calm = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const from = el.scrollLeft;
    const to = Math.max(0, Math.min(from + dir * step, el.scrollWidth - el.clientWidth));
    if (to === from) return;
    el.scrollTo({ left: to, behavior: calm ? "auto" : "smooth" });
    /* the smooth animation is driven by rAF, which some environments never run;
       if nothing has moved shortly after, land the scroll outright */
    window.setTimeout(() => {
      if (el.scrollLeft === from) el.scrollTo({ left: to, behavior: "auto" });
      syncEdges();
    }, 280);
    window.setTimeout(syncEdges, 700);
  };

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(null); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  /* As on mnc-bio-site: every saying owns a page under /s/ that carries its
     og:image, so X and Facebook have a picture to show for the link, and the
     device sheet is handed the story image itself. */
  const SITE = (typeof IG_SHARE_SITE === "string") ? IG_SHARE_SITE : "https://esadcosan.global";
  const pid = (s) => "q" + String(s.id).padStart(2, "0");
  const shareUrl = (s) => SITE + "/s/" + pid(s);
  const shareImg = (s) => "uploads/share/" + pid(s) + "-story.jpg";
  /* The tail is cut from the saying, never authored: whatever the poster lines
     do not use is what the italic line shows. */
  const head = (s) => (s.kick ? s.kick + " " + s.lead : s.lead);
  const tail = (s) => s.text.slice(head(s).length).trim();
  const full = (s) => s.text;
  const shareText = (s) => `“${full(s)}”\n\n${SAYINGS_BY}`;
  const panel = (s) => ({ "--tint": `var(--t-${s.tint})`, "--pat": SY_PATTERNS[s.pat % SY_PATTERNS.length] });

  return (
    <section className="hf-reveal" style={{
      padding: mobile ? "40px 0 64px" : "72px 0 132px",
      borderTop: "1px solid var(--hairline)",
    }}>
      <div ref={railRef} className="sy-rail" style={{ paddingInline: mobile ? 22 : 96, scrollPaddingInline: mobile ? 22 : 96 }}>
        {cards.map((s) => (
          <article key={s.id} data-saying-card data-saying-id={s.id}
            className={"sy-card sy-" + s.size} style={panel(s)}
            role="button" tabIndex={0} onClick={() => setOpen(s)}
            onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setOpen(s); } }}>
            <span className="sy-ghost" aria-hidden="true">{s.lead.trim().charAt(0)}</span>
            <div className="sy-in">
              <span className="sy-meta">{s.topic} · {SAYINGS_ATTRIBUTION}</span>
              {s.layout === "shout" ? (
                <>
                  <span className="sy-kicker">{s.kick}</span>
                  <span className="sy-shout">{s.lead}</span>
                </>
              ) : (
                <span className="sy-hero">{s.lead}</span>
              )}
              {tail(s) && <p className="sy-sub" style={{ WebkitLineClamp: s.layout === "shout" ? 3 : 4 }}>{tail(s)}</p>}
              <span className="sy-read">{t("read_full")} →</span>
            </div>
            <div className="sy-share">
              <IgShareButton url={shareUrl(s)} title={SAYINGS_BY} text={shareText(s)}
                image={shareImg(s)} caption="You have a message from Esad Cosan"
                lang={lang} accent={accent} variant="quiet" label={t("share_saying")} />
            </div>
          </article>
        ))}
      </div>

      {/* Rail footer, as under the MNC media rail: a progress hairline that
          mirrors the scroll, and the arrows beside it. The line shows on every
          width; the arrows are pointer furniture and stay off the phone. */}
      <div className="sy-rail-foot" style={{ marginInline: mobile ? 22 : 96 }}>
        <div className="sy-rail-track"><i ref={barRef} /></div>
        {!mobile && (
          <div className="sy-rail-btns">
            <button ref={prevRef} type="button" className="ig-nav" aria-label={t("prev")} aria-disabled="true" onClick={() => nudge(-1)}>←</button>
            <button ref={nextRef} type="button" className="ig-nav" aria-label={t("next")} aria-disabled="false" onClick={() => nudge(1)}>→</button>
          </div>
        )}
      </div>

      {open && (
        <div onClick={() => setOpen(null)} className="sy-reader-scrim"
          style={{ padding: mobile ? "6vh 20px" : "6vh 32px" }}>
          <div onClick={(e) => e.stopPropagation()} className="sy-reader"
            style={{ ...panel(open), padding: mobile ? "28px 22px" : "40px 44px" }}>
            <button onClick={() => setOpen(null)} aria-label={t("close")} className="sy-reader-close">×</button>
            <span className="sy-reader-meta">{open.topic} · {SAYINGS_ATTRIBUTION}</span>
            <p className="serif sy-reader-text">{full(open)}</p>
          </div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, { SayingsStrip, MEC_SAYINGS });
