/**
 * AJL40 Digital Series
 * © 2026 sultanmuzaffar. Hak cipta terpelihara / All rights reserved.
 * Penggunaan, penyalinan atau pengedaran tanpa kebenaran bertulis adalah dilarang.
 * Unauthorized use, copying or distribution is prohibited.
 */

// AJL 40 — Essay Detail Page Components
// All structural modules for a single essay reader page.
// Reads from window.AJL_ESSAY (unified shape across all 15 essays).

const { useState, useEffect, useRef } = React;

/* ============== READING PROGRESS BAR (top, sticky) ============== */
function ReadingProgress() {
  const [pct, setPct] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const doc = document.documentElement;
      const max = doc.scrollHeight - doc.clientHeight;
      setPct(max > 0 ? Math.min(1, doc.scrollTop / max) : 0);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className="ajl-progress" aria-hidden="true">
      <div className="ajl-progress__fill" style={{ transform: `scaleX(${pct})` }} />
    </div>
  );
}

/* ============== TOAST NOTIFICATION ============== */
let _toastTimeout = null;
function showToast(msg) {
  let el = document.getElementById("ajl-toast");
  if (!el) {
    el = document.createElement("div");
    el.id = "ajl-toast";
    el.className = "ajl-toast";
    document.body.appendChild(el);
  }
  el.textContent = msg;
  el.classList.remove("is-visible");
  void el.offsetWidth; // reflow
  el.classList.add("is-visible");
  clearTimeout(_toastTimeout);
  _toastTimeout = setTimeout(() => el.classList.remove("is-visible"), 2400);
}

/* ============== SHARE RAIL (sticky left) ============== */
function ShareRail() {
  const e = window.AJL_ESSAY;
  const [saved, setSaved] = useState(() => {
    try {
      const list = JSON.parse(localStorage.getItem("ajl_saved") || "[]");
      return e ? list.includes(e.no) : false;
    } catch { return false; }
  });

  const handleShare = () => {
    const url = window.location.href;
    const title = e ? `AJL 40 — ${e.title}` : "AJL 40 — Dunia Kreatif MM, Antologi Jiwa Lagu";
    if (navigator.share) {
      navigator.share({ title, url }).catch(() => {});
    } else if (navigator.clipboard) {
      navigator.clipboard.writeText(url).then(() => {
        showToast("Pautan disalin!");
      }).catch(() => showToast("Tidak dapat menyalin pautan"));
    } else {
      // Fallback
      const ta = document.createElement("textarea");
      ta.value = url; ta.style.position = "fixed"; ta.style.opacity = "0";
      document.body.appendChild(ta); ta.select();
      document.execCommand("copy"); document.body.removeChild(ta);
      showToast("Pautan disalin!");
    }
  };

  const handleSave = () => {
    if (!e) return;
    try {
      const list = JSON.parse(localStorage.getItem("ajl_saved") || "[]");
      const idx = list.indexOf(e.no);
      if (idx >= 0) {
        list.splice(idx, 1);
        setSaved(false);
        showToast("Esei dibuang dari simpanan");
      } else {
        list.push(e.no);
        setSaved(true);
        showToast("Esei disimpan!");
      }
      localStorage.setItem("ajl_saved", JSON.stringify(list));
    } catch {}
  };

  const handleTwitter = () => {
    const url = window.location.href;
    const text = e ? `${e.title} — AJL 40: Dunia Kreatif MM` : "AJL 40 — Dunia Kreatif MM, Antologi Jiwa Lagu";
    const tw = `https://x.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`;
    window.open(tw, "_blank", "noopener,noreferrer");
  };

  return (
    <aside className="ajl-share">
      <div className="ajl-share__label t-mono">KONGSI</div>
      <button className="ajl-share__btn" aria-label="Kongsi pautan" title="Kongsi pautan" onClick={handleShare}>
        <Icon name="share" size={16} />
      </button>
      <button className={`ajl-share__btn${saved ? " is-saved" : ""}`} aria-label={saved ? "Buang simpanan" : "Simpan esei"} title={saved ? "Buang simpanan" : "Simpan esei"} onClick={handleSave}>
        <Icon name="bookmark" size={16} />
      </button>
      <button className="ajl-share__btn" aria-label="Kongsi ke X" title="Kongsi ke X / Twitter" onClick={handleTwitter}>
        <Icon name="globe" size={16} />
      </button>
    </aside>
  );
}

/* ============== SOCIAL SHARE BUTTONS ============== */
function SocialShareRow({ text, url, variant, quote }) {
  // variant: "hero" (light on dark), "bone" (dark on bone), "quote" (inside pullquote)
  const shareUrl = url || window.location.href;
  const e = window.AJL_ESSAY;
  const shareText = text || (e ? `${e.title} — AJL 40: Dunia Kreatif MM` : 'AJL 40');
  const quoteText = quote || '';

  const open = (href) => window.open(href, '_blank', 'noopener,noreferrer,width=600,height=500');

  const handleWhatsApp = () => open(`https://api.whatsapp.com/send?text=${encodeURIComponent(shareText + '\n' + shareUrl)}`);
  const handleFacebook = () => open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}&quote=${encodeURIComponent(shareText)}`);
  const handleX = () => open(`https://x.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(shareUrl)}`);
  const handleTelegram = () => open(`https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(shareText)}`);
  const handleThreads = () => open(`https://www.threads.net/intent/post?text=${encodeURIComponent(shareText + ' ' + shareUrl)}`);
  const handleInstagram = () => {
    const copyText = quoteText ? `"${quoteText}"\n\n${shareText}\n${shareUrl}` : `${shareText}\n${shareUrl}`;
    if (navigator.clipboard) {
      navigator.clipboard.writeText(copyText).then(() => showToast('Disalin untuk Instagram!')).catch(() => showToast('Tidak dapat menyalin'));
    } else {
      const ta = document.createElement('textarea'); ta.value = copyText; ta.style.cssText = 'position:fixed;opacity:0';
      document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
      showToast('Disalin untuk Instagram!');
    }
  };

  const cls = `ajl-socshare ajl-socshare--${variant || 'hero'}`;

  return (
    <div className={cls}>
      <button className="ajl-socshare__btn" onClick={handleWhatsApp} aria-label="Kongsi ke WhatsApp" title="WhatsApp">
        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
      </button>
      <button className="ajl-socshare__btn" onClick={handleFacebook} aria-label="Kongsi ke Facebook" title="Facebook">
        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
      </button>
      <button className="ajl-socshare__btn" onClick={handleX} aria-label="Kongsi ke X" title="X (Twitter)">
        <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
      </button>
      <button className="ajl-socshare__btn" onClick={handleTelegram} aria-label="Kongsi ke Telegram" title="Telegram">
        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M11.944 0A12 12 0 000 12a12 12 0 0012 12 12 12 0 0012-12A12 12 0 0012 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 01.171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>
      </button>
      <button className="ajl-socshare__btn" onClick={handleThreads} aria-label="Kongsi ke Threads" title="Threads">
        <svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor"><path d="M12.186 24h-.007C5.965 24 2.634 20.155 2.634 14.564V14.5c0-5.531 3.315-9.5 8.02-9.5 3.727 0 6.469 2.223 7.178 5.07l-2.46.56c-.474-1.864-2.15-3.396-4.69-3.396-3.288 0-5.515 2.75-5.515 7.266v.064c0 4.134 1.867 7.202 5.537 7.202 1.97 0 3.382-.68 4.296-1.693.85-.943 1.31-2.218 1.31-3.624v-.02c0-.32-.012-.623-.037-.91-.866.426-1.856.653-2.924.653-3.874 0-6.275-2.282-6.275-5.96 0-3.362 2.258-5.802 5.368-5.802 1.673 0 3.037.617 3.95 1.788.877 1.123 1.321 2.694 1.321 4.667v.204c.005.08.008.16.008.24v.02c0 2.06-.629 3.891-1.81 5.226C14.843 22.69 13.115 24 12.186 24zm.793-14.39c-1.783 0-2.882 1.37-2.882 3.568 0 2.322 1.193 3.724 3.189 3.724.717 0 1.378-.14 1.97-.417a7.106 7.106 0 01-.072-1.01v-.203c0-2.813-.77-5.662-2.205-5.662z"/></svg>
      </button>
      <button className="ajl-socshare__btn ajl-socshare__btn--ig" onClick={handleInstagram} aria-label="Salin untuk Instagram" title="Instagram (salin)">
        <svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/></svg>
      </button>
    </div>
  );
}

/* ============== ARTICLE HERO ============== */
function ArticleHero({ essay }) {
  return (
    <section className="ajl-ahero">
      <div className="ajl-ahero__photo">
        <img src={essay.heroImage} alt="" />
        <div className="ajl-ahero__grain" />
        <div className="ajl-ahero__protect" />
      </div>

      <div className="ajl-container ajl-ahero__inner">
        <div className="ajl-eyebrow ajl-ahero__eyebrow">
          Esei {essay.no} · {essay.cluster}{essay.naratif ? ` · ${essay.naratif.join(" / ")}` : ""}
        </div>

        <div className="ajl-ahero__cluster">{essay.clusterSub}</div>

        <h1 className="ajl-ahero__title">{essay.title}</h1>

        <p className="ajl-ahero__standfirst">{essay.standfirst}</p>

        <div className="ajl-ahero__meta">
          <span className="t-mono">
            <Icon name="clock" size={12} style={{display:"inline-block",verticalAlign:"-2px",marginRight:"6px"}} />
            {essay.readMin} MIN · {essay.words}
          </span>
          <span className="ajl-ahero__sep">·</span>
          <span className="t-mono">{essay.publishDate}</span>
          <span className="ajl-ahero__sep">·</span>
          <span className="t-mono">{essay.byline}</span>
          <SocialShareRow variant="hero" />
        </div>

        {essay.provocation && (
          <div className="ajl-ahero__provocation">
            <blockquote className="ajl-ahero__prov-body"><em>{essay.provocation}</em></blockquote>
          </div>
        )}
      </div>
    </section>
  );
}

/* ============== ARTICLE BODY (long-form on bone) ============== */
function ArticleBody({ sections, pullQuotes, pullQuotePositions = {} }) {
  return (
    <article className="ajl-article" data-surface="bone">
      <div className="ajl-article__inner">
        {sections.map((sec, i) => (
          <React.Fragment key={i}>
            {sec.heading && <h2 className="ajl-article__h2">{sec.heading}</h2>}
            {sec.paragraphs.map((p, j) => (
              <p
                key={j}
                className={`ajl-article__p ${i === 0 && j === 0 ? "ajl-article__p--dropcap" : ""}`}
              >
                {p}
              </p>
            ))}
            {pullQuotePositions[i] !== undefined && (
              Array.isArray(pullQuotePositions[i])
                ? pullQuotePositions[i].map((qi, k) => (
                    pullQuotes[qi] ? <InlinePullQuote key={k} text={pullQuotes[qi]} /> : null
                  ))
                : (pullQuotes[pullQuotePositions[i]] ? <InlinePullQuote text={pullQuotes[pullQuotePositions[i]]} /> : null)
            )}
          </React.Fragment>
        ))}
      </div>
    </article>
  );
}

function InlinePullQuote({ text }) {
  const e = window.AJL_ESSAY;
  const shareText = e ? `"${text}" — ${e.title}, AJL 40` : `"${text}"`;
  return (
    <aside className="ajl-pullquote">
      <span className="ajl-pullquote__mark">"</span>
      <div>
        <blockquote className="ajl-pullquote__body">{text}</blockquote>
        <SocialShareRow variant="bone" text={shareText} quote={text} />
      </div>
    </aside>
  );
}

/* ============== PULL QUOTES STRIP (5 quotes, end-of-essay) ============== */
function PullQuotesStrip({ quotes }) {
  const e2 = window.AJL_ESSAY;
  return (
    <section className="ajl-quotes5" data-surface="bone">
      <div className="ajl-container">
        <div className="ajl-eyebrow ajl-quotes5__eyebrow">{quotes.length} Petikan Pilihan · Daripada Esei</div>
        <ol className="ajl-quotes5__list">
          {quotes.map((q, i) => (
            <li className="ajl-quotes5__item" key={i}>
              <div className="ajl-quotes5__no">{String(i + 1).padStart(2, "0")}</div>
              <div>
                <blockquote className="ajl-quotes5__body">{q}</blockquote>
                <SocialShareRow variant="bone" text={e2 ? `"${q}" — ${e2.title}, AJL 40` : `"${q}"`} quote={q} />
              </div>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* ============== 10 PRINCIPLES ============== */
function PrinciplesList({ principles, headingTop, headingBottom, principlesTitle }) {
  return (
    <section className="ajl-prinsip">
      <div className="ajl-container">
        <div className="ajl-section__head ajl-prinsip__head">
          <div className="ajl-eyebrow">10 Prinsip</div>
          {principlesTitle ? (
            <h2 className="ajl-section__title">{principlesTitle}</h2>
          ) : (
            <h2 className="ajl-section__title">
              <span>{headingTop || "Sepuluh peringatan"}</span><br />
              <em className="ajl-section__title-em">{headingBottom || "untuk pencipta dan industri."}</em>
            </h2>
          )}
        </div>
        <ol className="ajl-prinsip__list">
          {principles.map((p, i) => (
            <li className="ajl-prinsip__item" key={i}>
              <div className="ajl-prinsip__no">{String(i + 1).padStart(2, "0")}</div>
              <div className="ajl-prinsip__body">
                <h3 className="ajl-prinsip__t">{p.t}</h3>
                {p.b && <p className="ajl-prinsip__b">{p.b}</p>}
              </div>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

/* ============== CTA BLOCK ============== */
// Handles two styles:
//  (a) Essay with hashtags — lead + body + hashtags + closer
//  (b) Essay with prompts — title + fill-in-the-blank prompts + textarea + submit
function CTABlock({ cta }) {
  if (!cta) return null;
  const hasHashtags = cta.hashtags && cta.hashtags.length > 0;
  const hasPrompts = cta.prompts && cta.prompts.length > 0;
  const [answer, setAnswer] = React.useState("");
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState("");

  const essayNo = window.AJL_ESSAY ? window.AJL_ESSAY.no : "00";

  async function handleSubmit() {
    if (!answer.trim() || answer.trim().length < 5) {
      setStatus("error");
      setErrorMsg("Sila tulis sekurang-kurangnya 5 aksara.");
      return;
    }
    setStatus("sending");
    setErrorMsg("");
    try {
      const res = await fetch("/api/memory-wall", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ essayNo, answer: answer.trim() }),
      });
      if (res.ok) {
        setStatus("sent");
        setAnswer("");
      } else {
        const data = await res.json().catch(() => ({}));
        setStatus("error");
        setErrorMsg(data.error || "Ralat. Sila cuba lagi.");
      }
    } catch (_) {
      setStatus("error");
      setErrorMsg("Tiada sambungan. Sila cuba lagi.");
    }
  }

  function handleCopyLink() {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(window.location.href);
      showToast("Pautan disalin!");
    }
  }

  return (
    <section className="ajl-cta">
      <div className="ajl-container ajl-cta__inner">
        <div className="ajl-eyebrow">CTA Komuniti · Pembaca</div>
        {cta.title && <h2 className="ajl-cta__title">{cta.title}</h2>}

        {hasHashtags && !hasPrompts ? (
          <>
            {cta.lead && <p className="ajl-cta__lead">{cta.lead}</p>}
            {cta.intro && <div className="ajl-cta__intro">{cta.intro}</div>}
            {cta.body && <p className="ajl-cta__body">{cta.body}</p>}
            <div className="ajl-cta__tags">
              {cta.hashtags.map((h, i) => <span className="ajl-cta__tag" key={i}>{h}</span>)}
            </div>
            {cta.closer && <div className="ajl-cta__closer"><em>{cta.closer}</em></div>}
          </>
        ) : null}

        {hasPrompts ? (
          <>
            <div className="ajl-cta__intro">{cta.intro || "Lengkapkan ayat ini"}</div>
            <div className="ajl-cta__prompts">
              {cta.prompts.map((p, i) => (
                <blockquote className="ajl-cta__prompt" key={i}>"{p}"</blockquote>
              ))}
            </div>
            {cta.body && <p className="ajl-cta__body">{cta.body}</p>}

            {!cta.hideInput && (status === "sent" ? (
              <div className="ajl-cta__success">
                <Icon name="check" size={20} />
                <span>Terima kasih! Jawapan anda telah dihantar ke AJL40 Song Memory Wall.</span>
              </div>
            ) : (
              <>
                <textarea
                  className="ajl-cta__textarea"
                  rows={4}
                  maxLength={2000}
                  placeholder="Tulis jawapan anda di sini…"
                  value={answer}
                  onChange={(e) => { setAnswer(e.target.value); if (status === "error") setStatus("idle"); }}
                />
                {status === "error" && errorMsg && (
                  <div className="ajl-cta__error">{errorMsg}</div>
                )}
              </>
            ))}
          </>
        ) : null}

        {!cta.hideInput && (
          <div className="ajl-cta__ctas">
            {hasPrompts && status !== "sent" ? (
              <button
                className="ajl-btn ajl-btn--primary"
                onClick={handleSubmit}
                disabled={status === "sending"}
              >
                {status === "sending" ? "Menghantar…" : "Hantar Jawapan Saya"}
                {status !== "sending" && <Icon name="arrow-right" size={14} />}
              </button>
            ) : null}
            <button className="ajl-btn ajl-btn--ghost" onClick={handleCopyLink}>
              Salin Pautan<span className="ajl-btn__ul" />
            </button>
          </div>
        )}
      </div>
    </section>
  );
}

/* ============== RELATED ESSAYS RAIL ============== */
function RelatedRail({ items }) {
  const slug = (e) => (e.slug || `essay-${e.no}`) + ".html";
  return (
    <section className="ajl-related">
      <div className="ajl-container">
        <div className="ajl-section__head">
          <div className="ajl-eyebrow">Bacaan Berkaitan</div>
          <h2 className="ajl-section__title">
            <em className="ajl-section__title-em">Teruskan bacaan.</em>
          </h2>
        </div>
        <div className="ajl-related__list">
          {items.map((r) => (
            <a className="ajl-related__card" href={slug(r)} key={r.no}>
              <div className="ajl-related__no">{r.no}</div>
              <div className="ajl-related__body">
                <div className="ajl-related__cluster">{r.cluster}</div>
                <h3 className="ajl-related__title">{r.title}</h3>
                <div className="ajl-related__meta t-mono">
                  {r.readMin} MIN · BACA <Icon name="arrow-right" size={11} style={{display:"inline-block",verticalAlign:"-1px",marginLeft:"6px"}} />
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============== MOBILE SHARE BAR (bottom, visible ≤1100px) ============== */
function MobileShareBar() {
  const e = window.AJL_ESSAY;
  const [saved, setSaved] = useState(() => {
    try {
      const list = JSON.parse(localStorage.getItem("ajl_saved") || "[]");
      return e ? list.includes(e.no) : false;
    } catch { return false; }
  });

  const handleShare = () => {
    const url = window.location.href;
    const title = e ? `AJL 40 — ${e.title}` : "AJL 40 — Dunia Kreatif MM, Antologi Jiwa Lagu";
    if (navigator.share) {
      navigator.share({ title, url }).catch(() => {});
    } else if (navigator.clipboard) {
      navigator.clipboard.writeText(url).then(() => showToast("Pautan disalin!")).catch(() => {});
    }
  };

  const handleSave = () => {
    if (!e) return;
    try {
      const list = JSON.parse(localStorage.getItem("ajl_saved") || "[]");
      const idx = list.indexOf(e.no);
      if (idx >= 0) { list.splice(idx, 1); setSaved(false); showToast("Esei dibuang dari simpanan"); }
      else { list.push(e.no); setSaved(true); showToast("Esei disimpan!"); }
      localStorage.setItem("ajl_saved", JSON.stringify(list));
    } catch {}
  };

  const handleTwitter = () => {
    const url = window.location.href;
    const text = e ? `${e.title} — AJL 40` : "AJL 40 — Dunia Kreatif MM, Antologi Jiwa Lagu";
    window.open(`https://x.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`, "_blank", "noopener,noreferrer");
  };

  return (
    <div className="ajl-mshare">
      <button className="ajl-mshare__btn" onClick={handleShare}>
        <Icon name="share" size={16} /><span>Kongsi</span>
      </button>
      <button className={`ajl-mshare__btn${saved ? " is-saved" : ""}`} onClick={handleSave}>
        <Icon name="bookmark" size={16} /><span>{saved ? "Disimpan" : "Simpan"}</span>
      </button>
      <button className="ajl-mshare__btn" onClick={handleTwitter}>
        <Icon name="globe" size={16} /><span>Tweet</span>
      </button>
    </div>
  );
}

/* ============== NOTA EDITORIAL ============== */
function NotaEditorial({ text }) {
  if (!text) return null;
  return (
    <div className="ajl-nota">
      <div className="ajl-nota__label">Nota Editorial</div>
      <p className="ajl-nota__body">{text}</p>
    </div>
  );
}

/* ============== QUIZ (Uji Kefahaman) ============== */
function QuizBlock({ quiz }) {
  if (!quiz || !quiz.length) return null;
  const [selected, setSelected] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const letters = ["A", "B", "C", "D", "E"];

  const allAnswered = quiz.every((_, i) => selected[i] !== undefined);
  const score = quiz.reduce((acc, q, i) => acc + (selected[i] === q.answer ? 1 : 0), 0);

  function choose(qi, oi) {
    if (submitted) return;
    setSelected((s) => ({ ...s, [qi]: oi }));
  }
  function reset() {
    setSelected({});
    setSubmitted(false);
  }

  return (
    <section className="ajl-quiz">
      <div className="ajl-container">
        <div className="ajl-section__head ajl-quiz__head">
          <div className="ajl-eyebrow">Kuiz · Uji Kefahaman</div>
          <h2 className="ajl-section__title">
            <em className="ajl-section__title-em">Seberapa teliti anda membaca?</em>
          </h2>
        </div>
        <div className="ajl-quiz__list">
          {quiz.map((q, qi) => (
            <div className="ajl-quiz__q" key={qi}>
              <div className="ajl-quiz__qno">{String(qi + 1).padStart(2, "0")}</div>
              <div>
                <h3 className="ajl-quiz__qtext">{q.q}</h3>
                <div className="ajl-quiz__opts">
                  {q.options.map((opt, oi) => {
                    let cls = "ajl-quiz__opt";
                    if (submitted) {
                      if (oi === q.answer) cls += " is-correct";
                      else if (selected[qi] === oi) cls += " is-wrong";
                    } else if (selected[qi] === oi) {
                      cls += " is-selected";
                    }
                    return (
                      <button className={cls} key={oi} disabled={submitted} onClick={() => choose(qi, oi)}>
                        <span className="ajl-quiz__optmark">{letters[oi]}</span>
                        <span>{opt}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="ajl-quiz__actions">
          {!submitted ? (
            <button className="ajl-btn ajl-btn--primary" disabled={!allAnswered} onClick={() => setSubmitted(true)}>
              Semak Jawapan <Icon name="check" size={14} />
            </button>
          ) : (
            <>
              <div className="ajl-quiz__score">{score} / {quiz.length} betul <span>· {Math.round((score / quiz.length) * 100)}%</span></div>
              <button className="ajl-btn ajl-btn--ghost" onClick={reset}>Cuba Lagi<span className="ajl-btn__ul" /></button>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

/* ============== BACK TO TOP ============== */
function BackToTop() {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 600);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (!visible) return null;
  return (
    <button className="ajl-btt" aria-label="Kembali ke atas" title="Kembali ke atas"
      onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="18 15 12 9 6 15" />
      </svg>
    </button>
  );
}

Object.assign(window, {
  ReadingProgress, ShareRail, ArticleHero, ArticleBody, InlinePullQuote,
  PullQuotesStrip, PrinciplesList, CTABlock, RelatedRail, MobileShareBar, showToast, BackToTop,
  NotaEditorial, QuizBlock, SocialShareRow,
});