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

const AlertsPage = () => {
  const [rules, setRules] = window.usePersistedState("alert.rules", window.MOCK.DEFAULT_ALERT_RULES);
  const [selected, setSelected] = React.useState(rules[0] ? rules[0].id : null);
  const sel = rules.find(r => r.id === selected) || rules[0] || null;
  const [op, setOp] = React.useState("AND");

  const toggleRule = (id) => {
    setRules(rs => rs.map(r => r.id === id ? { ...r, on: !r.on } : r));
  };
  const deleteRule = (id) => {
    if (!confirm("確定刪除此通知規則？")) return;
    setRules(rs => rs.filter(r => r.id !== id));
    if (selected === id) {
      const remaining = rules.filter(r => r.id !== id);
      setSelected(remaining[0] ? remaining[0].id : null);
    }
  };
  const addRule = () => {
    const id = "r-" + Date.now();
    const newRule = {
      id, sym: "*", name: "新規則", tf: "1D",
      cond: "KC long entry: 盤整突破", cd: "1d",
      on: true, last: "—", status: "armed", kc: "盤整突破",
    };
    setRules(rs => [...rs, newRule]);
    setSelected(id);
  };
  const resetToDefault = () => {
    if (!confirm("還原為預設規則（盤整突破 / 回後買上漲）？目前規則會被覆蓋。")) return;
    setRules(window.MOCK.DEFAULT_ALERT_RULES);
    setSelected(window.MOCK.DEFAULT_ALERT_RULES[0].id);
  };

  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 => r.on).length} 啟用</span>
            </div>
            <div className="section-head-r" style={{display:"flex", gap:6, alignItems:"center"}}>
              <button className="btn ghost" title="還原為預設規則" onClick={resetToDefault}
                      style={{padding:"2px 8px", fontSize:"var(--fs-xs)"}}>
                <Icon name="refresh" size={12}/> 還原預設
              </button>
              <button className="btn primary" onClick={addRule}><Icon name="plus" size={13}/> 新增規則</button>
            </div>
          </header>
          <div className="rules-scroll">
            {rules.length === 0 && (
              <div className="dim" style={{padding:"24px 16px", textAlign:"center", fontSize:"var(--fs-sm)"}}>
                目前沒有通知規則。點右上「新增規則」或「還原預設」開始。
              </div>
            )}
            {rules.map(r => {
              const isWatchlist = r.sym === "*" || !r.sym;
              const mode = !isWatchlist && r.sym.endsWith(".TW") ? "tw" : !isWatchlist ? "us" : "tw";
              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}}>{isWatchlist ? "全觀察清單" : r.sym}</span>
                      <span className="pill" style={{fontSize:9}}>{r.tf}</span>
                    </div>
                    <div style={{display:"flex", gap:6, alignItems:"center"}}>
                      <div className="switch-wrap" onClick={(e) => { e.stopPropagation(); toggleRule(r.id); }}>
                        <div className={"switch " + (r.on ? "on" : "")}/>
                      </div>
                      <button className="btn ghost icon-btn danger-ghost"
                              onClick={(e) => { e.stopPropagation(); deleteRule(r.id); }}
                              title="刪除此規則"
                              style={{padding:2}}>
                        <Icon name="trash" size={13}/>
                      </button>
                    </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">
          {!sel ? (
            <div className="dim" style={{padding:48, textAlign:"center", fontSize:"var(--fs-sm)"}}>
              <Icon name="bell" size={28}/>
              <div style={{marginTop:12, marginBottom:4, fontSize:"var(--fs-md)"}}>沒有選取規則</div>
              <div>從左側選一條，或新增規則來編輯條件。</div>
            </div>
          ) : (
            <>
          <header className="section-head">
            <div className="section-head-l">
              <h2 className="section-title">條件編輯</h2>
              <span className="pill accent dot">{sel.sym === "*" ? "全觀察清單" : sel.sym}</span>
            </div>
            <div className="section-head-r">
              <button className="btn ghost danger-ghost" onClick={() => deleteRule(sel.id)}>
                <Icon name="trash" 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} placeholder="* 代表全觀察清單"/>
              </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>
            {sel ? (
              <div className="tg-preview">
                <div className="tg-bubble">
                  <div className="tg-line head">
                    [{sel.name}] {sel.sym === "*" ? "<觸發股票>" : sel.sym.replace(".TW","")}
                    {sel.sym !== "*" && <span className="mono dim"> {sel.sym}</span>}
                  </div>
                  <div className="tg-line">條件：<span className="mono dim">{sel.cond}</span></div>
                  <div className="tg-line">適用：<span className="mono">{sel.sym === "*" ? "全觀察清單" : sel.sym}</span></div>
                  <div className="tg-line">時間：<span className="mono">— 觸發時填入 —</span></div>
                  <div className="tg-line">資料源：<span className="mono">FinMind</span></div>
                  <div className="tg-time">— ✓</div>
                </div>
              </div>
            ) : (
              <div className="dim" style={{padding:24, textAlign:"center", fontSize:"var(--fs-sm)"}}>
                選一條規則查看預覽
              </div>
            )}
          </section>

          <section className="surface aside-card">
            <header className="section-head"><h3 className="section-title">近期觸發</h3></header>
            <div className="dim" style={{padding:24, textAlign:"center", fontSize:"var(--fs-sm)"}}>
              尚未有任何觸發紀錄
            </div>
          </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;
