/* ============ 免費試用 30 天 × 方案說明 × 方案比較表 ============
   內容取自需求方提供的兩張視覺稿，配色改用官網色票（深墨底 + 金色重點）。
   =============================================================== */

const TP_HIGHLIGHTS = [
  { t: '上傳 IFC', d: '50MB 內' },
  { t: '快速開啟模型', d: '免安裝' },
  { t: '立即開始體驗', d: '登入即用' }
];

const TP_SPECS = ['每月 1,000 點', '3 個圖台作業帳號', '瀏覽者免費'];

const TP_PRODUCTS = [
  { t: '建築管理 BIM', d: '設計 · 模型 · 資產管理' },
  { t: '施工進度 BIM', d: '進度追蹤 · 現場協同' },
  { t: '3D GIS', d: '空間資訊 · 地理整合' }
];

const TP_TRUST = [
  { t: '雲端圖台', d: '安全可靠' },
  { t: '快速開啟', d: '流暢檢視' },
  { t: '多格式支援', d: 'IFC 完整解析' },
  { t: '跨裝置支援', d: '隨時隨地查看' }
];

const TP_PLANS = [
  { key:'s', name:'小型專案版 S', price:'NT$1,490', per:'/ 月', point:'每月 1,000 點',
    who:'首次導入／小型團隊', seat:'3 個作業帳號' },
  { key:'a', name:'專業進階版 A', price:'NT$4,990', per:'/ 月', point:'每月 5,000 點',
    who:'中型專案／跨部門協作', seat:'10 個作業帳號', featured:true, tag:'推薦' },
  { key:'b', name:'企業旗艦版 B', price:'NT$19,900', per:'/ 月', point:'每月 25,000 點',
    who:'大型建築／含機電模型／多專案管理', seat:'30 個作業帳號' },
  { key:'x', name:'直接聯絡方案', price:'請洽專人', per:'', point:'客製配置',
    who:'大型企業／住戶版／整合導入', seat:'客製配置' }
];

/* 比對表：v 打勾、x 叉、其他為文字 */
const TP_TABLE = [
  { group:'價格與點數', rows:[
    ['月租價格', 'NT$1,490 / 月', 'NT$4,990 / 月', 'NT$19,900 / 月', '請洽專人'],
    ['每月基本點數', '1,000 點', '5,000 點', '25,000 點', '客製配置'],
    ['點數加值擴充', 'NT$500／500 點', 'NT$500／500 點', 'NT$500／500 點', '依需求規劃']
  ]},
  { group:'核心功能', rows:[
    ['建築管理 BIM', 'v', 'v', 'v', '客製'],
    ['施工進度 BIM', 'v', 'v', 'v', '客製'],
    ['3D GIS', 'x', 'v', 'v', '客製'],
    ['IFC 上傳與模型瀏覽', 'v', 'v', 'v', '客製'],
    ['雲端圖台跨裝置使用', 'v', 'v', 'v', 'v']
  ]},
  { group:'帳號與使用', rows:[
    ['圖台作業帳號', '3 人', '10 人', '30 人', '客製配置'],
    ['Viewer 瀏覽者', '免費，不計入作業帳號', '免費，不計入作業帳號', '免費，不計入作業帳號', '免費，不計入作業帳號'],
    ['30 天試用', 'v', '洽詢', '洽詢', '洽詢'],
    ['同模型更新 2 次內', '不另扣點', '不另扣點', '不另扣點', '依方案'],
    ['檔案儲存空間', '50GB', '200GB', '1TB', '客製配置']
  ]},
  { group:'支援與導入', rows:[
    ['適合對象', '首次導入／小型團隊', '中型專案／跨部門協作', '大型建築／含機電模型／多專案管理', '大型企業／住戶版／整合導入'],
    ['50MB 以下模型快速體驗', 'v', 'v', 'v', '依需求'],
    ['住戶版／物管應用', 'x', 'x', '可評估', 'v'],
    ['系統整合與客製導入', 'x', 'x', '可評估', 'v']
  ]}
];

const TP_NOTES = [
  'S 版不含 3D GIS',
  'Viewer 瀏覽者免費，且不計入圖台作業帳號人數，採合理使用原則',
  '同一模型更新 2 次內不另扣點，第三次起依規則扣點',
  '50MB 以下基本模型可快速體驗',
  '施工進度 BIM 依模型量體採較高點數規則',
  '檔案儲存空間包含原始 IFC、模型轉檔成果、PDF、圖片、Office 文件、設備手冊及專案附件。Viewer 瀏覽採合理使用原則。若有大量模型版本、長期保存大量文件或超出一般專案需求之儲存量，將提供容量加購或客製方案建議。'
];

/* ---------- 模型處理包點數標準 ---------- */
/* 依 IFC 原始檔案大小與模型用途扣點；施工進度 BIM 為建築管理 BIM 的 3 倍 */
const TP_PT_TABLE = [
  ['50MB 以下',      '500 點',   '1,500 點'],
  ['50MB ～ 100MB',  '1,000 點', '3,000 點'],
  ['100MB ～ 200MB', '2,500 點', '7,500 點'],
  ['200MB ～ 500MB', '5,000 點', '15,000 點'],
  ['500MB 以上',     '專案評估', '專案評估']
];

/* 一個處理包內含的三次 */
const TP_PT_PACK = [
  { n: '第 1 次', t: '首次模型處理' },
  { n: '第 2 次', t: '第一次同模型更新' },
  { n: '第 3 次', t: '第二次同模型更新' }
];

const TP_PT_OK = [
  ['同一專案', '必須為同一專案內的模型'],
  ['同一模型', '原模型的更新版本，不可換成其他模型'],
  ['同一用途', '建築管理 BIM 不可改為施工進度 BIM'],
  ['同一級距', '更新後 IFC 檔案大小不得跨越原級距']
];

/* 點數加值：$500 為一個單位，加值的點數不歸零 */
const TP_PT_TOPUP = [
  { amount: 'NT$500', point: '500 點' },
  { amount: 'NT$1,000', point: '1,000 點' },
  { amount: 'NT$1,500', point: '1,500 點' }
];

const TP_PT_RULES = [
  ['點數用途', '模型處理、施工進度 BIM 處理與模型更新'],
  ['月配點數', '每月依方案提供固定點數，不累積至下月'],
  ['加值點數', '以 NT$500 為單位加值，保留至不續約為止'],
  ['Viewer 瀏覽', '外部 Viewer 純瀏覽不扣點，也不計入作業帳號人數，採合理使用原則'],
  ['大型模型', '500MB 以上或高元件量模型採專案評估']
];

const TP_PT_EXAMPLES = [
  ['小型專案版', '1,000 點', '每月可處理 2 個 50MB 以下建築管理 BIM，各含 2 次同模型更新'],
  ['專業進階版', '5,000 點', '可處理 1 個 50MB～100MB 施工進度 BIM，餘額還能再處理多個建築管理 BIM'],
  ['企業旗艦版', '25,000 點', '可處理 1 個 200MB～500MB 施工進度 BIM，餘額還能再處理多個中型建築管理 BIM'],
  ['直接聯絡方案', '客製', '大型模型、高元件量機電、多專案、企業模型庫或系統整合']
];

const TP_LOGIN = 'https://luxor.cpweia.org.tw/IPCS2.0/Ipcs/Login';

/* ---------- 首頁：免費試用主視覺 ---------- */
function TrialBanner({ onCompare, onTrial }) {
  const ref = useReveal(0.2);
  return (
    <section className="lx-trial is-first" id="home" ref={ref}>
      <div className="lx-trial-inner">
        <div className="lx-trial-main">
          <div className="lx-trial-brand">
            <span className="lx-trial-brand-name">智慧 BIM 圖台</span>
            <span className="lx-trial-brand-sub">建築管理 BIM ／ 施工進度 BIM ／ 3D GIS</span>
          </div>

          <h2 className="lx-trial-head">
            免費試用<strong>30</strong>天
          </h2>
          <p className="lx-trial-sub">登入後即可體驗圖台</p>

          <ul className="lx-trial-quick">
            {TP_HIGHLIGHTS.map((h) =>
              <li key={h.t}><b>{h.t}</b><span>{h.d}</span></li>
            )}
          </ul>

          <div className="lx-trial-price">
            <span className="lx-trial-price-label">體驗價</span>
            <span className="lx-trial-price-num">NT$1,490</span>
            <span className="lx-trial-price-per">／月起</span>
          </div>

          <div className="lx-trial-specs">
            {TP_SPECS.map((s) => <span key={s}>{s}</span>)}
          </div>

          <div className="lx-trial-products">
            {TP_PRODUCTS.map((p) =>
              <div key={p.t}><b>{p.t}</b><span>{p.d}</span></div>
            )}
          </div>

          <div className="lx-trial-cta">
            <button className="lx-trial-btn is-primary is-disabled" disabled>立即試用 →</button>
            <button className="lx-trial-btn" onClick={onCompare}>看詳細說明</button>
          </div>
          <p className="lx-trial-foot">低門檻開始，先讓客戶看見圖台價值</p>
        </div>

        <aside className="lx-trial-side">
          <div className="lx-trial-shot">
            <img src="img/prod-bim.webp" alt="智慧 BIM 圖台" />
          </div>
          <div className="lx-trial-trust">
            {TP_TRUST.map((t) =>
              <div key={t.t}><b>{t.t}</b><span>{t.d}</span></div>
            )}
          </div>
        </aside>
      </div>
    </section>
  );
}

/* ---------- 方案比較表（全螢幕） ---------- */
function PlanCompare({ open, onClose, onTrial }) {
  const { useEffect: uE, useRef: uR } = React;
  const scrollRef = uR(null);

  uE(() => {
    if (!open) return;
    document.body.style.overflow = 'hidden';
    document.body.classList.add('is-pd-open');
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => {
      document.body.style.overflow = '';
      document.body.classList.remove('is-pd-open');
      window.removeEventListener('keydown', h);
    };
  }, [open, onClose]);

  const cell = (v, i) => {
    if (v === 'v') return <td key={i} className="is-yes"><span aria-label="有">✓</span></td>;
    if (v === 'x') return <td key={i} className="is-no"><span aria-label="無">×</span></td>;
    return <td key={i}>{v}</td>;
  };

  // 這一頁是 fixed 的捲動容器，錨點要對容器捲，不能用預設的 hash 跳轉
  const jump = (id) => (e) => {
    e.preventDefault();
    const root = scrollRef.current;
    const target = root?.querySelector(`#${id}`);
    if (target) root.scrollTo({ top: target.offsetTop - 24, behavior: 'smooth' });
  };

  return (
    <div className={`lx-cmp ${open ? 'is-open' : ''}`} ref={scrollRef}>
      <div className="lx-pd-head">
        <button className="lx-pd-close" onClick={onClose}>
          <span>← CLOSE</span>
          <span style={{ color:'var(--lx-ink-4)', fontWeight:400, letterSpacing:'1px' }}>ESC</span>
        </button>
        <div className="lx-pd-crumb">PRICING &nbsp;/&nbsp; <span>收費方案</span></div>
      </div>

      <header className="lx-cmp-hero">
        <span className="lx-eyebrow">智慧 BIM 圖台 ／ IPCS 智慧工地</span>
        <h1>收費方案</h1>
        <p className="lx-cmp-line">兩套系統採不同的收費方式，請依導入的產品查看</p>
      </header>

      {/* 兩套系統的收費模式：BIM 圖台走方案定價，IPCS 走專人評估 —— 放在最上面，一進來就看得到 */}
      <div className="lx-mode-grid">
        <div className="lx-mode-card">
          <span className="lx-mode-tag">智慧 BIM 圖台</span>
          <h2>月租方案 + 模型處理點數</h2>
          <p>依導入規模、模型大小與協作人數選擇方案，模型處理另以點數扣抵，價格公開透明。</p>
          <ul className="lx-mode-factors is-light">
            <li>四種方案 S ／ A ／ B ／ 客製</li>
            <li>每月固定點數，當月有效</li>
            <li>加值 NT$500 = 500 點，不歸零</li>
            <li>圖台作業帳號 3 ～ 30 人</li>
            <li>外部 Viewer 免費瀏覽，不計入帳號數</li>
          </ul>
          <div className="lx-mode-price"><b>NT$1,490</b><span>／月起</span></div>
          <div className="lx-mode-cta">
            <a href="#cmp-plans" className="lx-trial-btn" onClick={jump('cmp-plans')}>看方案比對表</a>
            <a href="#cmp-points" className="lx-trial-btn" onClick={jump('cmp-points')}>看點數標準</a>
          </div>
        </div>

        <div className="lx-mode-card is-quote">
          <span className="lx-mode-tag">IPCS 智慧工地</span>
          <h2>由專人評估，量身配置</h2>
          <p>
            工地的收費無法一體適用 —— 專案數量、使用人數、作業場域類型，以及搭配使用的模組組合，
            都會影響配置方式。IPCS 具備<strong>細緻的權限與角色管控</strong>，
            可依總公司、工地主任、監造、承攬商到現場人員逐層開放不同功能與資料範圍，
            從單一工地到集團多專案都能對應。
          </p>
          <ul className="lx-mode-factors">
            <li>工地專案數量</li>
            <li>使用人數與角色層級</li>
            <li>作業場域類型</li>
            <li>搭配使用的模組</li>
          </ul>
          <div className="lx-mode-price"><b>請洽專人</b><span>／依需求評估</span></div>
          <div className="lx-mode-cta">
            <a className="lx-trial-btn is-primary" href="#contact"
               onClick={(e) => { e.preventDefault(); if (window.lxGoto) window.lxGoto('contact'); else onClose(); }}>
              聯絡專人評估 →
            </a>
          </div>
        </div>
      </div>

      <h2 className="lx-cmp-h2" id="cmp-plans">
        <span>01</span>智慧 BIM 圖台 · 方案功能比對表
      </h2>

      <div className="lx-cmp-wrap">
        <table className="lx-cmp-table">
          <thead>
            <tr>
              {/* 內文每列有「分類 + 項目」兩欄，表頭要跨兩格才不會整排偏移 */}
              <th className="lx-cmp-cat" colSpan={2}>項目</th>
              {TP_PLANS.map((p) =>
                <th key={p.key} className={p.featured ? 'is-featured' : ''}>
                  {p.name}{p.tag && <em>{p.tag}</em>}
                </th>
              )}
            </tr>
          </thead>
          {TP_TABLE.map((g) =>
            <tbody key={g.group}>
              {g.rows.map((row, ri) =>
                <tr key={ri}>
                  {ri === 0 && <th className="lx-cmp-group" rowSpan={g.rows.length}>{g.group}</th>}
                  <th className="lx-cmp-item">{row[0]}</th>
                  {row.slice(1).map((v, i) => cell(v, i))}
                </tr>
              )}
            </tbody>
          )}
        </table>
      </div>

      <ul className="lx-cmp-notes">
        {TP_NOTES.map((n, i) => <li key={i}>{n}</li>)}
      </ul>

      <h2 className="lx-cmp-h2" id="cmp-points">
        <span>02</span>智慧 BIM 圖台 · 模型處理包點數
      </h2>
      <p className="lx-cmp-intro">
        智慧 BIM 圖台採「月租方案 + 模型處理點數」，依 IFC 原始檔案大小與模型用途扣抵點數。
        每一次模型處理包皆包含<strong>首次模型處理 + 2 次同模型更新</strong>，
        對應工程專案初期模型持續修正的實際情況。
      </p>

      {/* 一包 = 3 次 */}
      <div className="lx-pt-pack">
        {TP_PT_PACK.map((p, i) =>
          <div key={p.n} className="lx-pt-pack-step">
            <span className="lx-pt-pack-n">{p.n}</span>
            <span className="lx-pt-pack-t">{p.t}</span>
            {i < TP_PT_PACK.length - 1 && <i className="lx-pt-pack-arrow" aria-hidden="true">→</i>}
          </div>
        )}
      </div>

      {/* 點數表 */}
      <div className="lx-cmp-wrap">
        <table className="lx-cmp-table lx-pt-table">
          <thead>
            <tr>
              <th className="lx-pt-size">IFC 原始檔案大小</th>
              <th>建築管理 BIM<em>基準</em></th>
              <th className="is-featured">施工進度 BIM<em>3 倍</em></th>
              <th className="lx-pt-inc">內含項目</th>
            </tr>
          </thead>
          <tbody>
            {TP_PT_TABLE.map((row, i) =>
              <tr key={row[0]}>
                <th className="lx-cmp-item">{row[0]}</th>
                <td>{row[1]}</td>
                <td className="is-pt">{row[2]}</td>
                {i === 0 && <td className="lx-pt-inc" rowSpan={TP_PT_TABLE.length}>
                  首次處理 + 2 次同模型更新<br />
                  <span>（500MB 以上依模型大小、元件量與處理需求評估）</span>
                </td>}
              </tr>
            )}
          </tbody>
        </table>
      </div>
      <p className="lx-cmp-caption">
        施工進度 BIM 需處理構件與工項對應、施工狀態套色與進度資料整合，依建築管理 BIM 基準點數 3 倍計算。
      </p>

      {/* 「級距」是後面免費更新條件的關鍵字，先在這裡把定義講清楚 */}
      <div className="lx-tier-note">
        <span className="lx-tier-note-label">什麼是「檔案級距」？</span>
        <p>
          級距就是上表左欄那五段 IFC 原始檔案大小區間（50MB 以下 ／ 50–100MB ／ 100–200MB ／ 200–500MB ／ 500MB 以上）。
          點數是<strong>按級距扣抵</strong>，不是按實際 MB 數換算 —— 同一個級距內不論 55MB 還是 98MB，扣的點數都一樣。
        </p>
        <div className="lx-tier-example">
          <div className="lx-tier-example-row is-ok">
            <b>沒跨級距</b>
            <span>183MB 更新後變成 195MB → 兩者都在 <em>100–200MB</em>，屬於免費更新範圍，不另外扣點。</span>
          </div>
          <div className="lx-tier-example-row is-ng">
            <b>跨了級距</b>
            <span>183MB 更新後變成 250MB → 從 <em>100–200MB</em> 跳到 <em>200–500MB</em>，模型處理量已不同，需依新級距重新扣抵點數。</span>
          </div>
        </div>
        <p className="lx-tier-note-foot">
          所以送模型前先確認檔案落在哪一段，就能預估這次要用掉多少點數；更新時只要不跨過原本那一段，兩次更新都在處理包內。
        </p>
      </div>

      {/* 免費更新條件 + 方案點數對應範例 */}
      <div className="lx-pt-cols">
        <div className="lx-pt-col is-ok">
          <h3>免費更新 2 次的適用條件</h3>
          <dl>
            {TP_PT_OK.map(([k, v]) =>
              <div key={k}><dt>{k}</dt><dd>{v}</dd></div>
            )}
          </dl>
        </div>
        <div className="lx-pt-col">
          <h3>方案點數對應範例</h3>
          <dl>
            {TP_PT_EXAMPLES.map(([k, pt, v]) =>
              <div key={k}><dt>{k}<b>{pt}</b></dt><dd>{v}</dd></div>
            )}
          </dl>
        </div>
      </div>

      {/* 點數加值擴充 —— 規則單純但很關鍵，獨立一區講清楚 */}
      <div className="lx-topup">
        <div className="lx-topup-head">
          <span className="lx-topup-label">點數加值擴充</span>
          <h3>以 NT$500 為一個單位，加值的點數<strong>不會歸零</strong></h3>
        </div>

        <div className="lx-topup-body">
          <div className="lx-topup-rates">
            {TP_PT_TOPUP.map((t) =>
              <div key={t.amount}>
                <b>{t.amount}</b>
                <i aria-hidden="true">=</i>
                <span>{t.point}</span>
              </div>
            )}
            <div className="lx-topup-more">以此類推</div>
          </div>

          <ul className="lx-topup-notes">
            <li>
              <b>加值以 NT$500 為基準</b>
              <span>只能是 500 的倍數：NT$500、NT$1,000、NT$1,500 …，NT$500 即為 500 點。</span>
            </li>
            <li>
              <b>加值點數保留到不續約為止</b>
              <span>與每月配發的點數不同 —— 月配點數當月不用即歸零，<em>加值購買的點數會一直保留</em>，直到合約終止。</span>
            </li>
          </ul>
        </div>
      </div>

      {/* 點數使用方式 */}
      <div className="lx-pt-cols is-single">
        <div className="lx-pt-col">
          <h3>點數使用方式</h3>
          <dl>
            {TP_PT_RULES.map(([k, v]) =>
              <div key={k}><dt>{k}</dt><dd>{v}</dd></div>
            )}
          </dl>
        </div>
      </div>

      <div className="lx-cmp-cta">
        <button className="lx-trial-btn is-primary is-disabled" disabled>立即試用 30 天 →</button>
        <a className="lx-trial-btn" href="#contact" onClick={(e) => { e.preventDefault(); if (window.lxGoto) window.lxGoto('contact'); else onClose(); }}>聯絡顧問團隊</a>
      </div>
    </div>
  );
}

/* ---------- 立即試用（試用說明待需求方提供） ---------- */
function TrialModal({ open, onClose }) {
  const { useEffect: uE } = React;
  uE(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="lx-fm-modal" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="lx-fm-modal-panel" role="dialog" aria-modal="true" aria-label="立即試用">
        <button className="lx-fm-modal-x" onClick={onClose} aria-label="關閉">×</button>
        <div className="lx-fm-modal-kicker">FREE TRIAL<em>30 天</em></div>
        <h2>立即試用智慧 BIM 圖台</h2>
        <p className="lx-fm-modal-sum">登入後即可開始體驗，上傳 50MB 內的 IFC 模型，快速開啟並檢視。</p>
        <p className="lx-fm-modal-desc lx-trial-todo">（試用說明內容待補：請提供欲呈現的試用流程與條款文字，我再放進這一區。）</p>
        <div className="lx-cmp-cta" style={{ padding: 0, marginTop: 8 }}>
          <a className="lx-trial-btn is-primary is-disabled" aria-disabled="true">登入開始試用 →</a>
        </div>
      </div>
    </div>
  );
}

window.TrialBanner = TrialBanner;
window.PlanCompare = PlanCompare;
window.TrialModal = TrialModal;
