/* Manifesto.jsx — 盟之所向 (5-phrase verse) + Quick-Access nav cards
   - Verse lines are live-synced from admin (sw_manifesto)
   - Each line: { accent1, accent2, dot } (highlighted pair)
                 OR { text, text2, dot }   (plain pair)
                 OR a free mix of either side */

const MANIFESTO_LS_KEY = "sw_manifesto";

const DEFAULT_MANIFESTO = {
  lines: [
    { accent1: "亂世起", dot: true, accent2: "群雄逐" },
    { text: "我輩聚",    dot: true, text2:  "不為附庸" },
    { accent1: "兔躍所至", dot: true, accent2: "即是樂土" },
    { text: "華夏血性",   dot: true, text2:  "不容輕侮" },
    { accent1: "哈皮一戰", dot: true, accent2: "共寫山河" },
  ],
};

const loadManifesto = () => {
  try {
    const v = JSON.parse(localStorage.getItem(MANIFESTO_LS_KEY) || "null");
    if (v && Array.isArray(v.lines) && v.lines.length) return v;
  } catch {}
  return DEFAULT_MANIFESTO;
};

// Render a half-line: prefers accent (highlighted) over plain text.
const renderHalf = (accent, text) => {
  if (accent) return <span className="accent">{accent}</span>;
  if (text)   return <span>{text}</span>;
  return null;
};

const Manifesto = () => {
  const [manifesto, setManifesto] = React.useState(loadManifesto);

  React.useEffect(() => {
    const refresh = () => setManifesto(loadManifesto());
    const onStorage = (e) => { if (e.key === MANIFESTO_LS_KEY) refresh(); };
    window.addEventListener("storage", onStorage);
    const t = setInterval(refresh, 8000);
    return () => { window.removeEventListener("storage", onStorage); clearInterval(t); };
  }, []);

  return (
    <div className="wrap">
      <div className="manifesto-v2">
        <div className="manifesto-v2__verse" style={{ fontSize: "12pt" }}>
          {manifesto.lines.map((line, i) => (
            <div className="manifesto-v2__line" key={i}>
              {renderHalf(line.accent1, line.text)}
              {line.dot && <span className="dot" />}
              {renderHalf(line.accent2, line.text2)}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// expose to other scripts and reuse in subnav handlers
window.smoothJump = (e, id) => {
  if (e) e.preventDefault();
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 60;
  window.scrollTo({ top, behavior: "smooth" });
};
window.Manifesto = Manifesto;
