// Mottos & Scriptures page — 座右銘 (editable)
const { useState: useStateM } = React;

function MottosPage({ data }) {
  const [m, setM] = useStateM(JSON.parse(JSON.stringify(data.mottos))); // deep clone
  const [tab, setTab] = useStateM("primary");
  const [editing, setEditing] = useStateM(false);
  const [saving, setSaving] = useStateM(false);
  const [savedTick, setSavedTick] = useStateM(false);

  const tabs = [
    { id: "primary",   zh: "本命銘", en: "Primary" },
    { id: "scripture", zh: "經文",   en: "Scripture" },
    { id: "quotes",    zh: "引言",   en: "Quotes" },
    { id: "rules",     zh: "準則",   en: "Personal Rules" },
  ];

  const startEdit = () => {
    setM(JSON.parse(JSON.stringify(data.mottos)));
    setEditing(true);
  };
  const cancelEdit = () => {
    setM(JSON.parse(JSON.stringify(data.mottos)));
    setEditing(false);
  };
  const save = async () => {
    setSaving(true);
    try {
      await window.LifeData.saveMottos(m);
      setEditing(false);
      setSavedTick(true);
      setTimeout(() => setSavedTick(false), 2000);
    } catch (e) {
      alert('儲存失敗：' + (e?.message || e));
    } finally {
      setSaving(false);
    }
  };

  // Update helpers
  const setPrimary = (k, v) => setM({ ...m, primary: { ...m.primary, [k]: v } });
  const setScripture = (i, k, v) => {
    const arr = [...m.scriptures];
    arr[i] = { ...arr[i], [k]: v };
    setM({ ...m, scriptures: arr });
  };
  const addScripture = () => setM({
    ...m,
    scriptures: [...m.scriptures, { source: "", sourceEn: "", text: "", note: "—", date: "" }]
  });
  const removeScripture = (i) => {
    const arr = m.scriptures.filter((_, idx) => idx !== i);
    setM({ ...m, scriptures: arr });
  };
  const setQuote = (i, k, v) => {
    const arr = [...m.quotes];
    arr[i] = { ...arr[i], [k]: v };
    setM({ ...m, quotes: arr });
  };
  const addQuote = () => setM({
    ...m,
    quotes: [...m.quotes, { text: "", author: "—", date: "" }]
  });
  const removeQuote = (i) => {
    const arr = m.quotes.filter((_, idx) => idx !== i);
    setM({ ...m, quotes: arr });
  };
  const setRule = (i, v) => {
    const arr = [...m.personal];
    arr[i] = v;
    setM({ ...m, personal: arr });
  };
  const addRule = () => setM({ ...m, personal: [...m.personal, ""] });
  const removeRule = (i) => setM({ ...m, personal: m.personal.filter((_, idx) => idx !== i) });

  return (
    <div className="page-in" style={{ padding: "56px 72px 100px", maxWidth: 960, margin: "0 auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div className="en-caps" style={{ fontSize: 10, color: "var(--ink-3)" }}>Chapter III · Annex</div>
          <h1 className="han-display" style={{ fontSize: 38, margin: "4px 0 0", letterSpacing: "0.2em", fontWeight: 500 }}>座 右 銘</h1>
          <div className="en-title" style={{ fontSize: 18, color: "var(--ink-2)", marginTop: 4 }}>Mottos &amp; Scriptures</div>
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          {savedTick && (
            <span className="han-body" style={{ fontSize: 12, color: "var(--gold-deep)", fontStyle: "italic" }}>
              ✓ 已儲存
            </span>
          )}
          {!editing ? (
            <button className="btn btn-ghost" onClick={startEdit}>✎ 編輯</button>
          ) : (
            <>
              <button className="btn btn-ghost" onClick={cancelEdit} disabled={saving}>取消</button>
              <button className="btn btn-gold" onClick={save} disabled={saving}>
                {saving ? "儲存中⋯" : "✓ 儲存"}
              </button>
            </>
          )}
        </div>
      </div>
      <p className="han-body" style={{ fontSize: 14, color: "var(--ink-2)", marginTop: 12, maxWidth: 560 }}>
        在動搖時讀一遍。這些字句，是我願意一輩子放在心上的。
      </p>
      <hr className="rule" style={{ margin: "24px 0" }} />

      {/* Tabs */}
      <div style={{ display: "flex", gap: 6, marginBottom: 32, borderBottom: "1px solid var(--rule)" }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: "10px 18px",
            background: "transparent",
            border: "none",
            borderBottom: tab === t.id ? "2px solid var(--gold-deep)" : "2px solid transparent",
            cursor: "pointer",
            fontFamily: "var(--font-han)",
            fontSize: 14,
            letterSpacing: "0.2em",
            color: tab === t.id ? "var(--ink)" : "var(--ink-3)",
            marginBottom: -1
          }}>
            {t.zh}
            <span className="en-title" style={{ fontSize: 11, marginLeft: 8, opacity: 0.6 }}>{t.en}</span>
          </button>
        ))}
      </div>

      {/* ─── PRIMARY ─── */}
      {tab === "primary" && (
        editing ? (
          <div className="card" style={{ padding: "32px 36px" }}>
            <EditField label="中文 (zh)" value={m.primary.zh} onChange={v => setPrimary('zh', v)} />
            <EditField label="English (en)" value={m.primary.en} onChange={v => setPrimary('en', v)} />
            <EditField label="附註 (note)" value={m.primary.note} onChange={v => setPrimary('note', v)} multiline />
          </div>
        ) : (
          <div style={{
            padding: "64px 56px",
            background: "linear-gradient(180deg, oklch(0.92 0.04 78 / 0.4), oklch(0.94 0.025 80 / 0.15))",
            border: "1px solid var(--rule)",
            textAlign: "center",
            position: "relative"
          }}>
            <div style={{ display: "flex", justifyContent: "center", marginBottom: 24 }}>
              <window.LotusMark size={48} />
            </div>
            <div className="han-display" style={{
              fontSize: 38, lineHeight: 1.7, color: "var(--ink)",
              letterSpacing: "0.18em", fontWeight: 500
            }}>
              「{m.primary.zh}」
            </div>
            <div className="en-title" style={{ fontSize: 18, color: "var(--ink-2)", marginTop: 20, fontStyle: "italic" }}>
              {m.primary.en}
            </div>
            <div style={{ margin: "32px auto 0", width: 60, height: 1, background: "var(--rule)" }} />
            <p className="han-body" style={{ fontSize: 14, color: "var(--ink-3)", marginTop: 20, fontStyle: "italic" }}>
              {m.primary.note}
            </p>
          </div>
        )
      )}

      {/* ─── SCRIPTURES ─── */}
      {tab === "scripture" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
          {m.scriptures.map((s, i) => editing ? (
            <div key={i} className="card" style={{ padding: "24px 28px", position: "relative" }}>
              <button onClick={() => removeScripture(i)} title="刪除"
                style={{ position: "absolute", top: 12, right: 12, background: "transparent", border: "none", color: "var(--ink-3)", cursor: "pointer", fontSize: 14 }}>✕</button>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <EditField label="出處 (中)" value={s.source} onChange={v => setScripture(i, 'source', v)} />
                <EditField label="Source (en)" value={s.sourceEn} onChange={v => setScripture(i, 'sourceEn', v)} />
              </div>
              <EditField label="原文" value={s.text} onChange={v => setScripture(i, 'text', v)} multiline />
              <EditField label="附註" value={s.note} onChange={v => setScripture(i, 'note', v)} multiline />
              <EditField label="日期 (e.g. 2025.04)" value={s.date} onChange={v => setScripture(i, 'date', v)} />
            </div>
          ) : (
            <article key={i} style={{
              padding: "32px 36px", background: "var(--paper)",
              border: "1px solid var(--rule)", position: "relative"
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
                <div>
                  <div className="chop" style={{ background: "var(--ink)", color: "var(--paper)", transform: "rotate(-2deg)" }}>{s.source}</div>
                  <span className="en-title" style={{ fontSize: 12, color: "var(--ink-3)", marginLeft: 12, fontStyle: "italic" }}>{s.sourceEn}</span>
                </div>
                <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.15em" }}>抄錄 {s.date}</span>
              </div>
              <p className="han-display" style={{
                fontSize: 22, lineHeight: 1.9, color: "var(--ink)",
                margin: 0, letterSpacing: "0.1em", fontWeight: 500
              }}>
                {s.text}
              </p>
              {s.note && s.note !== "—" && (
                <>
                  <hr className="rule" style={{ margin: "20px 0 14px" }} />
                  <p className="han-body" style={{ fontSize: 13, color: "var(--ink-3)", margin: 0, fontStyle: "italic" }}>
                    <span style={{ color: "var(--gold-deep)", marginRight: 8 }}>—</span>{s.note}
                  </p>
                </>
              )}
            </article>
          ))}
          {editing && (
            <button className="btn btn-ghost" onClick={addScripture} style={{ alignSelf: "flex-start" }}>
              ✦ 新增經文
            </button>
          )}
        </div>
      )}

      {/* ─── QUOTES ─── */}
      {tab === "quotes" && (
        editing ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {m.quotes.map((q, i) => (
              <div key={i} className="card" style={{ padding: "20px 24px", position: "relative" }}>
                <button onClick={() => removeQuote(i)} title="刪除"
                  style={{ position: "absolute", top: 12, right: 12, background: "transparent", border: "none", color: "var(--ink-3)", cursor: "pointer", fontSize: 14 }}>✕</button>
                <EditField label="引言" value={q.text} onChange={v => setQuote(i, 'text', v)} multiline />
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <EditField label="作者" value={q.author} onChange={v => setQuote(i, 'author', v)} />
                  <EditField label="日期" value={q.date} onChange={v => setQuote(i, 'date', v)} />
                </div>
              </div>
            ))}
            <button className="btn btn-ghost" onClick={addQuote} style={{ alignSelf: "flex-start" }}>
              ✦ 新增引言
            </button>
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
            {m.quotes.map((q, i) => (
              <blockquote key={i} style={{
                margin: 0, padding: "28px 32px",
                background: "var(--paper)", border: "1px solid var(--rule)",
                borderLeft: "3px solid var(--gold)", position: "relative"
              }}>
                <div style={{
                  position: "absolute", top: 8, left: 16,
                  fontFamily: "var(--font-en)",
                  fontSize: 56, lineHeight: 1, color: "var(--gold-soft)",
                  opacity: 0.6
                }}>"</div>
                <p className="han-body" style={{
                  fontSize: 16, lineHeight: 1.9, color: "var(--ink)",
                  margin: "12px 0 16px",
                  fontStyle: q.text.match(/[A-Za-z]/) ? "italic" : "normal",
                  fontFamily: q.text.match(/^[A-Za-z]/) ? "var(--font-en)" : "var(--font-han)"
                }}>
                  {q.text}
                </p>
                <footer style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", borderTop: "1px dotted var(--rule)", paddingTop: 12 }}>
                  <cite className="en-title" style={{ fontSize: 13, color: "var(--ink-2)", fontStyle: "italic" }}>
                    — {q.author}
                  </cite>
                  <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{q.date}</span>
                </footer>
              </blockquote>
            ))}
          </div>
        )
      )}

      {/* ─── PERSONAL RULES ─── */}
      {tab === "rules" && (
        <div>
          <p className="han-body" style={{ fontSize: 14, color: "var(--ink-2)", marginTop: 0, marginBottom: 24, fontStyle: "italic" }}>
            自己訂的規矩。寫下來是為了在脆弱的時刻有一個錨。
          </p>
          {editing ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {m.personal.map((r, i) => (
                <div key={i} style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <span className="en-title" style={{
                    fontSize: 18, color: "var(--gold-deep)", fontStyle: "italic",
                    minWidth: 36, fontVariantNumeric: "lining-nums"
                  }}>{String(i + 1).padStart(2, "0")}.</span>
                  <input
                    className="field"
                    value={r}
                    onChange={e => setRule(i, e.target.value)}
                    style={{ flex: 1 }}
                    placeholder="一條準則…"
                  />
                  <button onClick={() => removeRule(i)} title="刪除" style={{
                    background: "transparent", border: "1px solid var(--rule)",
                    color: "var(--ink-3)", cursor: "pointer", padding: "8px 12px",
                    borderRadius: 2, fontSize: 12
                  }}>✕</button>
                </div>
              ))}
              <button className="btn btn-ghost" onClick={addRule} style={{ alignSelf: "flex-start", marginTop: 8 }}>
                ✦ 新增一條
              </button>
            </div>
          ) : (
            <ol style={{ margin: 0, padding: 0, listStyle: "none" }}>
              {m.personal.map((r, i) => (
                <li key={i} style={{
                  display: "flex", gap: 24, padding: "20px 0",
                  borderBottom: i === m.personal.length - 1 ? "none" : "1px dotted var(--rule)",
                  alignItems: "baseline"
                }}>
                  <span className="en-title" style={{
                    fontSize: 22, color: "var(--gold-deep)",
                    fontStyle: "italic", minWidth: 40,
                    fontVariantNumeric: "lining-nums"
                  }}>
                    {String(i + 1).padStart(2, "0")}.
                  </span>
                  <span className="han-body" style={{
                    fontSize: 17, color: "var(--ink)",
                    letterSpacing: "0.05em", lineHeight: 1.7, flex: 1
                  }}>
                    {r}
                  </span>
                </li>
              ))}
            </ol>
          )}
        </div>
      )}

      <div style={{ marginTop: 64, textAlign: "center", color: "var(--ink-3)" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 12 }}>
          <span style={{ width: 40, height: 1, background: "var(--rule)" }} />
          <span className="en-title" style={{ fontSize: 13, fontStyle: "italic", opacity: 0.7 }}>verba volant, scripta manent</span>
          <span style={{ width: 40, height: 1, background: "var(--rule)" }} />
        </div>
      </div>
    </div>
  );
}

function EditField({ label, value, onChange, multiline }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div className="en-caps" style={{ fontSize: 9, color: "var(--ink-3)", marginBottom: 4 }}>{label}</div>
      {multiline ? (
        <textarea
          className="field"
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          style={{ minHeight: 60, resize: "vertical", lineHeight: 1.7 }}
        />
      ) : (
        <input
          className="field"
          value={value || ''}
          onChange={e => onChange(e.target.value)}
        />
      )}
    </div>
  );
}

window.MottosPage = MottosPage;
