/* Page 3 — Alerts / Telegram Rules */
const { Icon, fmt } = window.UI;

const AlertsPage = () => {
  const rules = window.MOCK.ALERT_RULES;
  const [selected, setSelected] = React.useState(rules[1].id);
  const [toggle, setToggle] = React.useState(Object.fromEntries(rules.map(r => [r.id, r.on])));
  const sel = rules.find(r => r.id === selected);
  const [op, setOp] = React.useState("AND");

  return (
    <div className="page alerts-page">
      <div className="alerts-grid">
        {/* Left — rule list */}
        <section className="surface alerts-list">
          <header className="section-head">
            <div className="section-head-l">
              <h2 className="section-title">通知規則</h2>
              <span className="dim mono" style={{fontSize:"var(--fs-xs)"}}>{rules.length} 條 · {rules.filter(r => toggle[r.id]).length} 啟用</span>
            </div>
            <button className="btn primary"><Icon name="plus" size={13}/> 新增規則</button>
          </header>
          <div className="rules-scroll">
            {rules.map(r => {
              const mode = r.sym.endsWith(".TW") ? "tw" : "us";
              return (
                <button key={r.id} className={"rule-item" + (selected === r.id ? " selected" : "")}
                  onClick={() => setSelected(r.id)} data-color-mode={mode}>
                  <div className="rule-row top">
                    <div className="rule-sym">
                      <span className="mono" style={{fontWeight:600}}>{r.sym}</span>
                      <span className="pill" style={{fontSize:9}}>{r.tf}</span>
                    </div>
                    <div className="switch-wrap" onClick={(e) => { e.stopPropagation(); setToggle(t => ({...t, [r.id]: !t[r.id]})); }}>
                      <div className={"switch " + (toggle[r.id] ? "on" : "")}/>
                    </div>
                  </div>
                  <div className="rule-name">{r.name}</div>
                  <div className="rule-cond mono dim">{r.cond}</div>
                  <div className="rule-row bottom">
                    <span className={"pill " + (r.status === "delivered" ? "success" : (r.status === "muted" ? "warn" : "accent")) + " dot"}>
                      {r.status === "delivered" ? "已送達" : r.status === "muted" ? "冷卻中" : "待命"}
                    </span>
                    <span className="dim mono" style={{fontSize:"var(--fs-xs)"}}>{r.last}</span>
                  </div>
                </button>
              );
            })}
          </div>
        </section>

        {/* Center — condition editor */}
        <section className="surface alerts-editor">
          <header className="section-head">
            <div className="section-head-l">
              <h2 className="section-title">條件編輯</h2>
              <span className="pill accent dot">{sel.sym}</span>
            </div>
            <div className="section-head-r">
              <button className="btn ghost danger-ghost"><Icon name="x" size={13}/> 刪除</button>
              <button className="btn primary">儲存</button>
            </div>
          </header>

          <div className="editor-body">
            <div className="form-row">
              <label className="form-label">規則名稱</label>
              <input className="input" defaultValue={sel.name} style={{flex:1}}/>
            </div>
            <div className="form-grid">
              <div className="form-row col">
                <label className="form-label">股票代號</label>
                <input className="input" defaultValue={sel.sym}/>
              </div>
              <div className="form-row col">
                <label className="form-label">時間週期</label>
                <select className="select"><option>1D 日 K</option><option>1W 週 K</option><option>1M 月 K</option></select>
              </div>
              <div className="form-row col">
                <label className="form-label">冷卻時間</label>
                <select className="select" defaultValue={sel.cd}><option>1h</option><option>4h</option><option>1d</option><option>3d</option></select>
              </div>
              <div className="form-row col">
                <label className="form-label">方向</label>
                <div className="seg" style={{height:32}}>
                  <button className="active">多單</button>
                  <button>空單</button>
                  <button>多空</button>
                </div>
              </div>
            </div>

            <div className="cond-block">
              <div className="cond-header">
                <span className="sec-title">條件</span>
                <div className="seg">
                  <button className={op === "AND" ? "active" : ""} onClick={() => setOp("AND")}>AND</button>
                  <button className={op === "OR" ? "active" : ""} onClick={() => setOp("OR")}>OR</button>
                </div>
                <div className="toolbar-spacer"/>
                <button className="btn ghost"><Icon name="plus" size={13}/> 加條件</button>
                <button className="btn ghost"><Icon name="plus" size={13}/> 加群組</button>
              </div>

              <ConditionRow type="cross" left="Close" op="cross-above" right="MA(60)" market={sel.sym}/>
              <div className="and-divider">{op}</div>
              <ConditionRow type="cmp" left="Volume" op=">" right="MA20·1.5"/>
              <div className="and-divider">{op}</div>
              <ConditionRow type="kc" preset="長 · 盤整突破"/>

              <div className="add-condition-row">
                <button className="btn ghost"><Icon name="plus" size={13}/> 新增條件</button>
              </div>
            </div>

            <div className="form-grid two">
              <div className="form-row col">
                <label className="form-label">停損</label>
                <input className="input" placeholder="—  例: -3% 或 跌破 MA20"/>
              </div>
              <div className="form-row col">
                <label className="form-label">停利</label>
                <input className="input" placeholder="—  例: +8% 或 KC 多單出場"/>
              </div>
            </div>
          </div>
        </section>

        {/* Right — recent triggers + Telegram preview */}
        <aside className="alerts-aside">
          <section className="surface aside-card">
            <header className="section-head">
              <h3 className="section-title">Telegram 預覽</h3>
              <button className="btn ghost"><Icon name="send" size={13}/> 測試</button>
            </header>
            <div className="tg-preview">
              <div className="tg-bubble">
                <div className="tg-line head">[技術條件觸發] {sel.sym.replace(".TW","")} <span className="mono dim">{sel.sym}</span></div>
                <div className="tg-line">條件：收盤價突破 MA60 且成交量大於 20 日均量 1.5 倍</div>
                <div className="tg-line">現價：<span className="mono">980.00 TWD</span></div>
                <div className="tg-line">漲跌：<span className="up mono">+1.87%</span></div>
                <div className="tg-line">時間：<span className="mono">2026-05-07 10:31 Asia/Taipei</span></div>
                <div className="tg-line">資料源：<span className="mono">FinMind</span></div>
                <div className="tg-time">10:31 ✓✓</div>
              </div>
            </div>
          </section>

          <section className="surface aside-card">
            <header className="section-head"><h3 className="section-title">近期觸發</h3></header>
            <ul className="trigger-list">
              {[
                { time: "05-07 10:31", status: "delivered", note: "條件成立 · 量 1.42×" },
                { time: "05-06 14:02", status: "delivered", note: "條件成立 · 收盤 > MA60" },
                { time: "05-02 10:15", status: "muted", note: "冷卻中 · 4h" },
                { time: "04-29 09:08", status: "delivered", note: "條件成立 · 量 1.62×" },
                { time: "04-23 13:45", status: "failed", note: "Telegram 逾時" },
              ].map((t, i) => (
                <li key={i} className="trigger-item">
                  <span className={"trigger-dot " + t.status}/>
                  <span className="mono dim" style={{fontSize:"var(--fs-xs)", width:96}}>{t.time}</span>
                  <span style={{flex:1, fontSize:"var(--fs-sm)"}}>{t.note}</span>
                  <span className={"pill " + (t.status === "delivered" ? "success" : t.status === "muted" ? "warn" : "danger")}>
                    {t.status === "delivered" ? "已送達" : t.status === "muted" ? "冷卻" : "失敗"}
                  </span>
                </li>
              ))}
            </ul>
          </section>
        </aside>
      </div>
    </div>
  );
};

const ConditionRow = ({ type, left, op, right, preset }) => {
  if (type === "kc") {
    return (
      <div className="cond-row kc">
        <span className="pill accent dot">KC</span>
        <select className="select" defaultValue="long-entry">
          <option value="long-entry">多單進場</option>
          <option>多單出場</option>
          <option>空單進場</option>
          <option>空單出場</option>
          <option>等待訊號</option>
        </select>
        <select className="select" defaultValue={preset}>
          <option>多 · 盤整突破</option>
          <option>多 · 回後買上漲</option>
          <option>多 · 高勝率紅 K</option>
          <option>空 · 盤整跌破</option>
          <option>空 · 彈後破 5MA</option>
          <option>空 · 高勝率黑 K</option>
          <option>等待 · 多單</option>
          <option>等待 · 盤整突破</option>
        </select>
        <button className="btn ghost icon-btn"><Icon name="x" size={12}/></button>
      </div>
    );
  }
  return (
    <div className="cond-row">
      <select className="select" defaultValue={left}>
        <option>收盤價</option><option>開盤價</option><option>最高價</option><option>最低價</option>
        <option>成交量</option><option>RSI(14)</option><option>MA(20)</option><option>MA(60)</option>
      </select>
      <select className="select" defaultValue={op}>
        <option value="cross-above">向上突破</option>
        <option value="cross-below">向下跌破</option>
        <option value=">">{">"}</option>
        <option value="<">{"<"}</option>
        <option value=">=">{"≥"}</option>
        <option value="<=">{"≤"}</option>
      </select>
      <input className="input" defaultValue={right} style={{flex:1}}/>
      <button className="btn ghost icon-btn"><Icon name="x" size={12}/></button>
    </div>
  );
};

window.AlertsPage = AlertsPage;
