/* ================= AI問道 · 六爻問事 + 命盤詳批 ================= */
/* 六爻起卦为真实现（三枚制钱法+64卦纳甲查表），前端自足；
   八字/大六壬排盘 + AI 解读均接后端 /api/reading（真盘），Stripe 支付接 /api/checkout。 */

/* 天地盘轮展示顺序（视觉起 12 点钟位=午，顺时针），非引擎内部序 */
const ZHI_12 = ['午', '未', '申', '酉', '戌', '亥', '子', '丑', '寅', '卯', '辰', '巳'];

/* ---- 六爻 · 卦表 ---- */
const TRIG = { 7: ['乾', '天'], 3: ['兌', '澤'], 5: ['離', '火'], 1: ['震', '雷'], 6: ['巽', '風'], 2: ['坎', '水'], 4: ['艮', '山'], 0: ['坤', '地'] };
const KW_NAMES = ['乾', '坤', '屯', '蒙', '需', '訟', '師', '比', '小畜', '履', '泰', '否', '同人', '大有', '謙', '豫', '隨', '蠱', '臨', '觀', '噬嗑', '賁', '剝', '復', '無妄', '大畜', '頤', '大過', '坎', '離', '咸', '恆', '遯', '大壯', '晉', '明夷', '家人', '睽', '蹇', '解', '損', '益', '夬', '姤', '萃', '升', '困', '井', '革', '鼎', '震', '艮', '漸', '歸妹', '豐', '旅', '巽', '兌', '渙', '節', '中孚', '小過', '既濟', '未濟'];
/* 京房八宫序查表：KW[上卦][下卦] → 卦序（上下卦均按 乾兌離震巽坎艮坤） */
const KW_ORDER = [7, 3, 5, 1, 6, 2, 4, 0];
const KW_TABLE = [
  [1, 10, 13, 25, 44, 6, 33, 12],    // 上乾
  [43, 58, 49, 17, 28, 47, 31, 45],  // 上兌
  [14, 38, 30, 21, 50, 64, 56, 35],  // 上離
  [34, 54, 55, 51, 32, 40, 62, 16],  // 上震
  [9, 61, 37, 42, 57, 59, 53, 20],   // 上巽
  [5, 60, 63, 3, 48, 29, 39, 8],     // 上坎
  [26, 41, 22, 27, 18, 4, 52, 23],   // 上艮（2026-07-04 修：坎/艮列曾互换，蒙曾错排成艮）
  [11, 19, 36, 24, 46, 7, 15, 2],    // 上坤（2026-07-04 修：坎/艮/坤三列曾轮转，坤卦曾错排成謙）
];
/* lines: 6 元素数组，初爻在前，1=阳 0=阴 → { n, char, name } */
function hexagram(lines) {
  const lower = lines[0] + (lines[1] << 1) + (lines[2] << 2);
  const upper = lines[3] + (lines[4] << 1) + (lines[5] << 2);
  const n = KW_TABLE[KW_ORDER.indexOf(upper)][KW_ORDER.indexOf(lower)];
  const base = KW_NAMES[n - 1];
  const name = upper === lower ? `${base}為${TRIG[upper][1]}` : `${TRIG[upper][1]}${TRIG[lower][1]}${base}`;
  return { n, char: String.fromCodePoint(0x4DC0 + n - 1), name };
}
/* 三枚制钱：背记3字记2，和 6老陰 7少陽 8少陰 9老陽 */
function tossYao() {
  const heads = [0, 0, 0].map(() => (Math.random() < 0.5 ? 1 : 0));
  const sum = heads.reduce((s, h) => s + (h ? 3 : 2), 0);
  return { coins: heads, sum, yang: sum % 2 === 1, moving: sum === 6 || sum === 9 };
}
const YAO_CN = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻'];
const YAO_EN = ['1st line', '2nd line', '3rd line', '4th line', '5th line', 'top line'];
const SUM_CN = { 6: '三字 · 老陰（動）', 7: '一背二字 · 少陽', 8: '二背一字 · 少陰', 9: '三背 · 老陽（動）' };
const SUM_EN = { 6: 'old yin (moving)', 7: 'young yang', 8: 'young yin', 9: 'old yang (moving)' };

/* ---- 免责声明（spec 定稿文案逐字，代码注入，AI 不改写） ---- */
const DISCLAIMER_CN = '「機斷有數 · 誠告緣主」——本篇命書由 AI 承易理推演而成。然當今大模型之斷，尚屬籠統之境，遠未及老道卦師數十年之火候。所言僅供參考助興，不構成醫療、法律、投資之建議。事關重大者，宜請道長親批，方得細微。';
const DISCLAIMER_EN = 'A Word of Honesty — This reading is cast by AI upon the old methods. Yet today\'s AI remains a blunt instrument beside a seasoned master\'s decades of craft. Take it as reference and delight, not as medical, legal, or financial counsel. For matters that weigh heavy, seek the Master\'s own hand.';
function Disclaimer() {
  const lang = useLang();
  const en = lang === 'en';
  return (
    <div className="wd-disclaimer" style={en ? { fontFamily: 'var(--font-en-serif)' } : null}>
      {en ? DISCLAIMER_EN : DISCLAIMER_CN}
      <div style={{ marginTop: 10, opacity: .75, fontSize: '.9em' }}>
        {en
          ? 'Taoist Fate is operated by Syncmotion LLC. Payments are processed by Syncmotion.'
          : 'Taoist Fate 由 Syncmotion LLC 運營，付款由 Syncmotion 處理'}
      </div>
    </div>
  );
}

/* ---- 付费墙（三线共用） ---- */
function Paywall({ title, desc, price, blur, cta, toast, onUnlock }) {
  const lang = useLang();
  const en = lang === 'en';
  const click = onUnlock || (() => toast(en ? 'Secure checkout is on its way — stay tuned ✦' : '支付通道接入中 · 敬請期待 ✦'));
  return (
    <div className="wd-paywall">
      <div className="wd-pay-blur">{blur}</div>
      <div className="wd-pay-mask">
        <div className="wd-pay-t" style={en ? { fontFamily: 'var(--font-en-serif)', fontWeight: 700 } : null}>{title}</div>
        <div className="wd-pay-d">{desc}</div>
        <button className="wd-btn-unlock" onClick={click}>{price} · {cta}</button>
        <div className="wd-pay-foot">{en ? 'Stripe secure checkout · Bilingual report · Payments are processed by Syncmotion' : 'Stripe 安全支付 · 中英雙語報告（付款由 Syncmotion 處理）'}</div>
      </div>
    </div>
  );
}

/* ---- 六爻向导 ---- */
function LiuyaoWizard({ toast }) {
  const lang = useLang();
  const en = lang === 'en';
  const ff = en ? { fontFamily: 'var(--font-en-serif)' } : null;
  const [step, setStep] = useState(1);
  const [q, setQ] = useState(en ? 'A new offer came — should I take the leap?' : '近期有新機會欲跳槽，可行否？');
  const [yaos, setYaos] = useState([]); // {coins,sum,yang,moving}
  const [busy, setBusy] = useState(false);
  const [spin, setSpin] = useState(0);
  const TOPICS = en
    ? { Career: 'A new offer came — should I take the leap?', Love: 'Will this bond endure?', Wealth: 'Fortune this half-year — hold or advance?', Lawsuit: 'Settle or fight — where do my odds lie?', 'Lost item': 'Can what was lost still be found?', Decision: 'Two roads before me — which to walk?' }
    : { 事業: '近期有新機會欲跳槽，可行否？', 姻緣: '與此人之緣分，可長久否？', 財運: '今歲下半年財運如何，宜守宜攻？', 官非: '此樁糾紛，和解勝訴各幾成？', 尋物: '遺失之物，尚可尋回否？', 決斷: '兩條路擺在眼前，何去何從？' };

  const doToss = () => {
    if (busy || yaos.length >= 6) return;
    setBusy(true);
    setSpin(s => s + 1);
    setTimeout(() => {
      setYaos(ys => [...ys, tossYao()]);
      setBusy(false);
    }, 560);
  };
  const done = yaos.length === 6;
  const last = yaos[yaos.length - 1];
  const ben = done ? hexagram(yaos.map(y => (y.yang ? 1 : 0))) : null;
  const movingIdx = yaos.map((y, i) => (y.moving ? i : -1)).filter(i => i >= 0);
  const bian = done && movingIdx.length ? hexagram(yaos.map(y => (y.moving ? (y.yang ? 0 : 1) : (y.yang ? 1 : 0)))) : null;
  const teaser = done
    ? en
      ? `The cast reveals “${ben.name}” (Hexagram ${ben.n}).${bian ? ` Line${movingIdx.length > 1 ? 's' : ''} ${movingIdx.map(i => i + 1).join(', ')} moving — transforming into “${bian.name}”. The turn of events hides in the moving line${movingIdx.length > 1 ? 's' : ''}.` : ' All six lines at rest — the matter holds steady; stillness serves you.'}`
      : `卦成「${ben.name}」。${bian ? `${movingIdx.map(i => YAO_CN[i]).join('、')}動，變「${bian.name}」——事之轉機，正藏於動爻之中。` : '六爻安靜，事體平穩，宜靜守其成。'}`
    : '';

  return (
    <div>
      <div className="wd-steps" style={ff}>
        {(en ? ['I · Ask', 'II · Cast', 'III · Read'] : ['壹 · 問事', '貳 · 搖卦', '叁 · 卦成']).map((s, i) => (
          <span key={s} className={step > i ? 'on' : ''}>{s}</span>
        ))}
      </div>

      {step === 1 && (
        <div className="wd-stage">
          <div className="wd-qlabel" style={en ? { fontFamily: 'var(--font-en-serif)', fontWeight: 700, letterSpacing: '.04em' } : null}>{en ? 'What Troubles You' : '所 問 何 事'}</div>
          <div className="wd-topics">
            {Object.entries(TOPICS).map(([t, sample]) => (
              <button key={t} style={ff} onClick={() => setQ(sample)}>{t}</button>
            ))}
          </div>
          <textarea className="wd-qinput" style={ff} value={q} onChange={e => setQ(e.target.value)} />
          <div className="wd-center">
            <button className="wd-btn-main" style={ff} onClick={() => { if (!q.trim()) { toast(en ? 'Write down your question first ✦' : '請先寫下所問之事 ✦'); return; } setStep(2); }}>{en ? 'Cleanse & Cast' : '淨 手 起 卦'}</button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div className="wd-stage">
          <div className="wd-toss-area">
            <div>
              <div className="wd-coins">
                {[0, 1, 2].map(i => (
                  <div key={i} className={`wd-coin ${last && !last.coins[i] ? 'tail' : ''}`} style={{ transform: `rotateY(${spin * 720}deg)` }}>通寶</div>
                ))}
              </div>
              <div className="wd-toss-status" style={ff}>
                {yaos.length === 0
                  ? (en ? 'Hold your question in mind · cast the 1st line' : '誠心默念所問之事 · 擲初爻')
                  : done
                    ? (en ? `${YAO_EN[5]}: ${SUM_EN[last.sum]} — the hexagram is complete` : `上爻：${SUM_CN[last.sum]}　六爻已備，卦成！`)
                    : (en ? `${YAO_EN[yaos.length - 1]}: ${SUM_EN[last.sum]} → cast the ${YAO_EN[yaos.length]}` : `${YAO_CN[yaos.length - 1]}：${SUM_CN[last.sum]}　→　擲${YAO_CN[yaos.length]}`)}
              </div>
              <div className="wd-center">
                {!done
                  ? <button className="wd-btn-main" style={ff} disabled={busy} onClick={doToss}>{en ? 'Toss' : '擲　盃'}</button>
                  : <button className="wd-btn-main" style={ff} onClick={() => setStep(3)}>{en ? 'Read the Hexagram' : '觀　卦'}</button>}
              </div>
            </div>
            <div className="wd-yao-stack">
              {yaos.map((y, i) => (
                <div key={i} className="wd-yao">
                  {y.yang ? <span className="bar" /> : <span className="gap"><i /><i /></span>}
                  <span className="mark">{y.moving ? (y.yang ? '○' : '×') : ''}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {step === 3 && ben && (
        <div className="wd-stage">
          <div className="wd-gua-result">
            <div className="wd-gua-card">
              <div className="hexchar">{ben.char}</div>
              <div className="name">{ben.name}</div>
              <div className="sub" style={ff}>{en ? `Hexagram ${ben.n} · Primary` : `本卦 · 第${ben.n}卦`}</div>
            </div>
            {bian && <div className="wd-gua-arrow">→</div>}
            {bian && (
              <div className="wd-gua-card">
                <div className="hexchar">{bian.char}</div>
                <div className="name">{bian.name}</div>
                <div className="sub" style={ff}>{en ? `Hexagram ${bian.n} · Transformed` : `變卦 · 第${bian.n}卦`}</div>
              </div>
            )}
          </div>
          <div className="wd-ai-quote">
            <div className="mq">「</div>
            <p style={ff}>{teaser}</p>
            <div className="by" style={ff}>{en ? 'Hexagram overview · free' : '卦象速覽 · 免費'}</div>
          </div>
          <Paywall
            toast={toast}
            onUnlock={async () => {
              try {
                // 只送原始爻值+问题+起卦时间；卦名/纳甲后端复算，前端展示数据不上送
                const pad = (n) => String(n).padStart(2, '0');
                const d = new Date();
                const castTime = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
                const res = await window.api('/api/checkout', { kind: 'liuyao', question: q, throws: yaos.map(y => y.sum), castTime });
                location.href = res.url;
              } catch (e) {
                toast(en ? 'Checkout is warming up — try again shortly ✦' : '支付通道暫未就緒，請稍後再試 ✦');
              }
            }}
            title={en ? 'AI Full Hexagram Reading' : 'AI 詳細解卦'}
            desc={en ? 'Line-by-line reading · timing · what to do next' : '逐爻細斷 · 應期推算 · 行動指引'}
            price="$9.9" cta={en ? 'Unlock' : '解 鎖 全 卦'}
            blur={en
              ? 'The self line holds wealth under the Azure Dragon, while the officer star sits strong in the responding position. The opportunity is genuine, yet the month pillar presses against you — the timing has not ripened. Counting the moving lines forward, the metal breathes freely after the sixth month…'
              : '世爻持財臨青龍，應爻官鬼旺相，新機誠意有之，然月建剋世，時機未至。細數動爻遞進之象，六月之後金氣得祿，方為佳期……卦中兄弟爻兩現，同行競逐者不止一人，宜先密而後動。文書合同之事須逐條細審，尤忌口頭之諾……'}
          />
        </div>
      )}
    </div>
  );
}

/* ---- 命盤向导 ---- */
function MingpanWizard({ toast }) {
  const lang = useLang();
  const en = lang === 'en';
  const ff = en ? { fontFamily: 'var(--font-en-serif)' } : null;
  const [fate, setFate] = useState(window.__WD_INIT?.fate || 'bazi'); // bazi | dlr
  const [cast, setCast] = useState(false);
  const [dob, setDob] = useState('1990-06-15T14:30');
  const [gender, setGender] = useState('male');
  const [city, setCity] = useState('');
  const [focus, setFocus] = useState('');
  const [chart, setChart] = useState(null);
  const [pan, setPan] = useState(null);     // 大六壬排盘结果（引擎输出，Task 7 契约）
  const [ai, setAi] = useState(null);       // {cn,en} | null
  const [casting, setCasting] = useState(false);

  const doCast = async () => {
    const d = new Date(dob);
    if (!dob || isNaN(d)) { toast(en ? 'Please enter a valid birth time ✦' : '請填寫有效的出生時間 ✦'); return; }
    setCasting(true);
    if (fate === 'dlr') {
      try {
        const res = await window.api('/api/reading', { kind: 'dlr', dob, gender, city, focus });
        setPan(res.pan);
        setAi(res.ai || null);
        setCast(true);
      } catch (e) {
        // 大六壬无本地回退引擎——排盘失败即提示，不进 cast 态
        toast(en ? 'Casting failed — try again shortly ✦' : '排盤未成，請稍後再試 ✦');
      } finally {
        setCasting(false);
      }
      return;
    }
    try {
      const res = await window.api('/api/reading', { kind: 'bazi', dob, gender, city, focus });
      setChart(res.chart);
      setAi(res.ai || null);
    } catch (e) {
      // 后端未就绪：本地引擎出盘，无 AI 短评
      setChart(window.BAZI.computeBazi(d));
      setAi(null);
    } finally {
      setCasting(false);
      setCast(true);
    }
  };

  const goCheckout = async (kind) => {
    try {
      const res = await window.api('/api/checkout', { kind, dob, gender, city, focus });
      location.href = res.url;
    } catch (e) {
      toast(en ? 'Checkout is warming up — try again shortly ✦' : '支付通道暫未就緒，請稍後再試 ✦');
    }
  };

  return (
    <div>
      <div className="wd-fate-toggle" style={ff}>
        <button className={fate === 'bazi' ? 'on' : ''} onClick={() => setFate('bazi')}>{en ? 'BaZi Chart' : '八字命盤'}<span className="pt">$19.9</span></button>
        <button className={fate === 'dlr' ? 'on' : ''} onClick={() => setFate('dlr')}>{en ? 'Da Liu Ren' : '大六壬'}<span className="pt">{en ? 'Premium $29.9' : '尊享 · 帝王之學 $29.9'}</span></button>
      </div>

      {!cast && (
        <div className="wd-stage">
          <div className="wd-fform">
            <div>
              <label style={ff}>{en ? 'Date & time of birth (Gregorian) *' : '陽歷出生日期 · 精確到分 *'}</label>
              <input type="datetime-local" value={dob} onChange={e => setDob(e.target.value)} />
            </div>
            <div className="wd-two">
              <div>
                <label style={ff}>{en ? 'Gender *' : '性別 *'}</label>
                <div className="wd-radio-row">
                  {[['male', en ? 'Male' : '男'], ['female', en ? 'Female' : '女']].map(([v, t]) => (
                    <button key={v} className={gender === v ? 'sel' : ''} style={ff} onClick={() => setGender(v)}><span className="dot" />{t}</button>
                  ))}
                </div>
              </div>
              <div>
                <label style={ff}>{en ? 'City of birth' : '出生城市'}</label>
                <input type="text" style={ff} placeholder={en ? 'e.g. Chongqing — for true solar time' : '如：重慶（供真太陽時校準）'} value={city} onChange={e => setCity(e.target.value)} />
              </div>
            </div>
            <div>
              <label style={ff}>{en ? 'Focus (optional)' : '想重點看的方面（選填）'}</label>
              <input type="text" style={ff} placeholder={en ? 'Career / wealth / love / decade luck…' : '事業 / 財運 / 姻緣 / 大運流年…'} value={focus} onChange={e => setFocus(e.target.value)} />
            </div>
          </div>
          <div className="wd-center"><button className="wd-btn-main" style={ff} disabled={casting} onClick={doCast}>{casting ? (en ? 'Casting…' : '排盤中…') : (en ? 'Cast the Chart' : '排　盤')}</button></div>
        </div>
      )}

      {cast && fate === 'bazi' && chart && (
        <div className="wd-stage">
          <BaziChart data={chart} />
          {chart.solarNote && <div style={{ textAlign: 'center', fontSize: 12, color: '#8E815F', marginTop: 10, letterSpacing: '.04em' }}>☉ {chart.solarNote}</div>}
          {ai && (
            <div className="wd-ai-quote" style={{ marginTop: 26 }}>
              <div className="mq">「</div>
              <p style={ff}>{en ? ai.en : ai.cn}</p>
              <div className="by" style={ff}>{en ? 'AI reading · free' : 'AI 短評 · 免費'}</div>
            </div>
          )}
          <Disclaimer />
          <Paywall
            toast={toast}
            onUnlock={() => goCheckout('bazi')}
            title={en ? 'AI BaZi Destiny Book' : 'AI 八字命書'}
            desc={en ? 'Character · career & wealth · love · decade luck · yearly notes · remedies' : '性格深析 · 事業財運 · 姻緣 · 十年大運 · 流年提點 · 開運建議'}
            price="$19.9" cta={en ? 'Unlock' : '解 鎖 命 書'}
            blur={en
              ? 'The decade pillar now runs through the metal meridian — help arrives from the west. At thirty-eight the luck turns to fire and earth: this single decade decides the shape of the life. Wealth stars sit mixed, hidden and revealed; the surer road is skill-made money, not partnered ventures…'
              : '大運現行祿地，貴人自西方來。三十八歲換運火土並旺，此十年為一生成敗之樞紐……財星偏正混雜，正財藏而偏財透，求財宜走「以技生財」之路，忌合夥現金生意。姻緣一節，日支所藏與配偶宮相涉……'}
          />
          {ai && (
            <div className="wd-center" style={{ marginTop: 26 }}>
              <a className="wd-btn-main" style={{ textDecoration: 'none', display: 'inline-block' }}
                 href={en ? '/en/reading-report/' : (lang === 'tc' ? '/tc/mingshu/' : '/mingshu/')}>
                {en ? 'Get the Full Destiny Book ✦' : '出完整命書 ✦'}
              </a>
            </div>
          )}
        </div>
      )}

      {cast && fate === 'dlr' && pan && (
        <div className="wd-stage">
          <div className="wd-dlr-badge"><span style={ff}>{en ? 'DA LIU REN · THE EMPEROR’S ART' : '大六壬 · 帝王之學 · 尊享詳批'}</span></div>

          <div className="wd-tp-wheel">
            {ZHI_12.map((z, i) => (
              <i key={'o' + z} className="wd-tp-outer" style={{ '--a': `${i * 30}deg` }}>{pan.tianPan?.[z]}</i>
            ))}
            {ZHI_12.map((z, i) => (
              <i key={'i' + z} style={{ '--a': `${i * 30}deg` }}>{z}</i>
            ))}
            <div className="core">{pan.keTi}</div>
          </div>

          <div className="wd-sike-grid">
            {(pan.siKe || []).map((k, i) => (
              <div key={i} className="wd-sike-col">
                <div className="nm" style={ff}>{k.name}</div>
                <div className="zh">{k.shang}<span className="over">{k.xia}</span></div>
                <div className="chips">
                  <span className="chip tj">{k.tianJiang}</span>
                  <span className="chip cs">{k.changSheng}</span>
                </div>
              </div>
            ))}
          </div>

          <div className="wd-sc-rows">
            {(pan.sanChuan || []).map((s) => (
              <div key={s.pos} className="wd-sc-row">
                <span className="pos" style={ff}>{en ? { 初: 'Early', 中: 'Mid', 末: 'Final' }[s.pos] : `${s.pos}傳`}</span>
                <span className="zhi">{s.zhi}{s.gan && <b className="gan">{s.gan}</b>}</span>
                <span className="chip tj">{s.tianJiang}</span>
                <span className="chip cs">{s.changSheng}</span>
              </div>
            ))}
          </div>

          <div className="wd-dlr-info">
            <span>{en ? 'Day Salary' : '日祿'} <b>{pan.riLu || '—'}</b></span>
            <span>{en ? 'Noble' : '貴人'} <b>{pan.guiRen?.type === '昼' ? (en ? 'Day' : '晝貴') : (en ? 'Night' : '夜貴')} · {pan.guiRen?.pos || '—'}</b></span>
            <span>{en ? 'Month Gen.' : '月將'} <b>{pan.yueJiang || '—'}</b></span>
            <span>{en ? 'Hour' : '占時'} <b>{pan.zhanShi || '—'}</b></span>
          </div>
          {pan.solarNote && <div style={{ textAlign: 'center', fontSize: 12, color: '#8E815F', marginTop: 10, letterSpacing: '.04em' }}>☉ {pan.solarNote}</div>}

          {ai && (
            <div className="wd-ai-quote">
              <div className="mq">「</div>
              <p style={ff}>{en ? ai.en : ai.cn}</p>
              <div className="by" style={ff}>{en ? 'Quick reading · free' : '課傳簡斷 · 免費'}</div>
            </div>
          )}
          <Disclaimer />
          <Paywall
            toast={toast}
            onUnlock={() => goCheckout('dlr')}
            title={en ? 'AI Da Liu Ren Book · Premium' : 'AI 大六壬命書 · 尊享'}
            desc={en ? 'Full plates · course reading · timing · collectible PDF in the golden-ink style' : '天地盤全解 · 課體斷事 · 三傳應期 · 黃庭司金墨版式典藏 PDF'}
            price="$29.9" cta={en ? 'Unlock Premium' : '解 鎖 尊 享 命 書'}
            blur={en
              ? 'The Grand Constant graces the gate of destiny — nobility worn on the inside of the sleeve. Yet the post-horse stirs in the metal palace: within three years, a relocation is written. Daytime plans prosper; night plans scatter…'
              : '天盤未加午，太常臨門，衣祿之神坐命——此局貴氣內斂，然驛馬暗動於申，三年之內必有一遷。貴人順治，晝貴登天門，謀事宜晝不宜夜……四課上下相賊，取初傳為用神，申金為傳送之神，主道路消息文書……'}
          />
          {ai && (
            <div className="wd-center" style={{ marginTop: 26 }}>
              <a className="wd-btn-main" style={{ textDecoration: 'none', display: 'inline-block' }}
                 href={en ? '/en/reading-report/' : (lang === 'tc' ? '/tc/mingshu/' : '/mingshu/')}>
                {en ? 'Get the Full Destiny Book ✦' : '出完整命書 ✦'}
              </a>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ---- 主 section ---- */
function Wendao({ toast }) {
  const lang = useLang();
  const en = lang === 'en';
  const ff = en ? { fontFamily: 'var(--font-en-serif)' } : null;
  const [panel, setPanel] = useState(window.__WD_INIT?.panel || null); // null | 'liuyao' | 'mingpan'
  const open = (p) => {
    setPanel(p);
    setTimeout(() => document.getElementById('wd-panel')?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 60);
  };
  return (
    <section id="wendao" className="sec" style={{ position: 'relative', overflow: 'hidden' }}>
      <div className="wd-bg" />
      <div className="wrap" style={{ position: 'relative', padding: '84px 0 90px' }}>
        <Reveal>
          <div className="wd-head">
            <div className="cn" style={en ? { fontFamily: 'var(--font-en-serif)', fontWeight: 700, fontSize: 50 } : null}>{en ? <>Ask the <em>Dao</em></> : <>AI <em>問道</em></>}</div>
            <div className="en">{en ? 'Instant AI divination · cast now, read now' : 'Ask the Dao · Instant AI Divination'}</div>
            <div className="divider-red" />
          </div>
        </Reveal>

        <Reveal delay={70}>
          <div className="wd-cards">
            <button className={`wd-card ${panel === 'liuyao' ? 'active' : ''}`} onClick={() => open('liuyao')}>
              <span className="corner" style={ff}>{en ? 'ONE MATTER' : '問一事'}</span>
              <span className="glyph">☰&#xFE0E;☷&#xFE0E;</span>
              <h3 style={en ? { fontFamily: 'var(--font-en-serif)', fontWeight: 700, fontSize: 28 } : null}>{en ? 'Ask the Hexagrams' : '六爻問事'}</h3>
              <div className="tag" style={ff}>{en ? '“Six lines answer all things under heaven”' : '「六爻問盡天下事」'}</div>
              <p className="desc" style={ff}>{en ? 'Take the leap, or hold? Will this bond last? One matter, one cast — six sincere tosses and the hexagram speaks. AI reads it by the old rules, on the spot.' : '跳槽可行否？此緣可續否？一事一問，誠心搖卦六次，卦成即斷。AI 承易理細解一卦，即問即答。'}</p>
              <div className="price-row">
                <span className="wd-chip hot" style={ff}>{en ? '$9.9 / question' : '$9.9 / 一問'}</span>
                <span className="wd-chip" style={ff}>{en ? 'Instant cast' : '即時出卦'}</span>
              </div>
              <span className="cta" style={ff}>{en ? 'START ASKING' : '開 始 問 事'}</span>
            </button>

            <button className={`wd-card ${panel === 'mingpan' ? 'active' : ''}`} onClick={() => open('mingpan')}>
              <span className="corner" style={ff}>{en ? 'ONE LIFE' : '觀一生'}</span>
              <span className="glyph">◉</span>
              <h3 style={en ? { fontFamily: 'var(--font-en-serif)', fontWeight: 700, fontSize: 28 } : null}>{en ? 'Destiny Chart Reading' : '命盤詳批'}</h3>
              <div className="tag" style={ff}>{en ? '“One chart holds one lifetime”' : '「一盤觀一生」'}</div>
              <p className="desc" style={ff}>{en ? 'Your birth hour cast into the four pillars of BaZi — or into Da Liu Ren, the emperor’s art of plates and transmissions. AI writes the full destiny book, bilingual.' : '生辰入盤，八字排四柱十神；或以大六壬——古稱帝王之學——起天地盤課傳。AI 出詳批命書，中英雙語。'}</p>
              <div className="price-row">
                <span className="wd-chip" style={ff}>{en ? 'BaZi $19.9' : '八字 $19.9'}</span>
                <span className="wd-chip hot" style={ff}>{en ? 'Da Liu Ren · Premium $29.9' : '大六壬 · 尊享 $29.9'}</span>
              </div>
              <span className="cta" style={ff}>{en ? 'CAST MY CHART' : '立 即 排 盤'}</span>
            </button>
          </div>
        </Reveal>

        {panel && (
          <div className="wd-panel" id="wd-panel">
            {panel === 'liuyao' ? <LiuyaoWizard toast={toast} /> : <MingpanWizard toast={toast} />}
          </div>
        )}

        <div className="wd-human" style={ff}>
          <p>{en ? <>Numbers can be counted; the human heart cannot. <a href="/en/master/">Ask the Master in person ↓</a></> : <>機斷有數，人情無算 —— 嫌 AI 不夠？<a href={lang === 'tc' ? '/tc/master/' : '/master/'}>道長親批 ↓</a></>}</p>
        </div>
      </div>
    </section>
  );
}
