/* Page — News
 *  分類 tab / weight 篩選 / 來源 filter / 時間軸排列
 *  資料來源：window.MOCK.NEWS_EXTENDED (fallback: window.MOCK.NEWS)
 */
const NewsPage = () => {
  const { Icon } = window.UI;

  const allNews = React.useMemo(() => {
    return (window.MOCK && (window.MOCK.NEWS_EXTENDED || window.MOCK.NEWS)) || [];
  }, []);

  /* filters */
  const [market, setMarket] = React.useState("all"); // all | TW | US
  const [weight, setWeight] = React.useState("all"); // all | high | med | low
  const [category, setCategory] = React.useState("all"); // all | company | macro | tech
  const [source, setSource] = React.useState("all");
  const [q, setQ] = React.useState("");

  /* unique sources */
  const sources = React.useMemo(() => {
    const set = new Set();
    allNews.forEach(n => set.add(n.src));
    return ["all", ...Array.from(set).sort()];
  }, [allNews]);

  const categoryLabel = { all: "全部", company: "個股", macro: "總體", tech: "科技" };
  const weightLabel = { all: "全部權重", high: "高重要", med: "中重要", low: "低重要" };
  const marketLabel = { all: "全部市場", TW: "台股", US: "美股" };

  const filtered = React.useMemo(() => {
    return allNews.filter(n => {
      if (market !== "all" && n.market !== market) return false;
      if (weight !== "all" && n.weight !== weight) return false;
      if (category !== "all" && n.category !== category) return false;
      if (source !== "all" && n.src !== source) return false;
      if (q) {
        const qq = q.toLowerCase();
        const hay = (n.title + " " + n.sym + " " + n.src).toLowerCase();
        if (!hay.includes(qq)) return false;
      }
      return true;
    });
  }, [allNews, market, weight, category, source, q]);

  /* group by time bucket */
  const buckets = React.useMemo(() => {
    const t = { today: [], yesterday: [] };
    filtered.forEach(n => {
      if (n.time && n.time.startsWith("昨日")) t.yesterday.push(n);
      else t.today.push(n);
    });
    return t;
  }, [filtered]);

  /* counts for tabs */
  const countByWeight = React.useMemo(() => ({
    all: allNews.length,
    high: allNews.filter(n => n.weight === "high").length,
    med: allNews.filter(n => n.weight === "med").length,
    low: allNews.filter(n => n.weight === "low").length,
  }), [allNews]);

  const resetFilters = () => {
    setMarket("all"); setWeight("all"); setCategory("all"); setSource("all"); setQ("");
  };

  const NewsCard = ({ n }) => {
    const weightCls =
      n.weight === "high" ? "w-high" :
      n.weight === "med" ? "w-med" : "w-low";
    const isUS = n.market === "US";
    return (
      <article className={"news-card " + weightCls} data-color-mode={isUS ? "us" : "tw"}>
        <div className="news-card-l">
          <span className="news-time mono">{n.time}</span>
          <span className={"news-weight-dot " + weightCls}/>
        </div>
        <div className="news-card-body">
          <div className="news-card-meta">
            {n.sym && n.sym !== "MARKET" && n.sym !== "FED" && n.sym !== "BTC" && (
              <span className="news-card-sym mono">{n.sym.replace(".TW","")}</span>
            )}
            {(n.sym === "MARKET" || n.sym === "FED" || n.sym === "BTC") && (
              <span className="news-card-tag">{n.sym}</span>
            )}
            <span className={"news-card-mflag " + (n.market === "TW" ? "tw" : "us")}>
              {n.market === "TW" ? "TW" : "US"}
            </span>
            <span className="news-card-cat">{categoryLabel[n.category] || n.category}</span>
          </div>
          <h3 className="news-card-title">{n.title}</h3>
          <div className="news-card-foot">
            <span className="news-card-src dim">{n.src}</span>
            {n.weight === "high" && <span className="pill warn" style={{fontSize:"var(--fs-xs)"}}>重要</span>}
          </div>
        </div>
      </article>
    );
  };

  return (
    <div className="page news-page">
      {/* Hero header */}
      <header className="news-hero surface">
        <div className="news-hero-l">
          <h1 className="news-hero-title">新聞中心</h1>
          <p className="news-hero-sub dim">
            台美股即時新聞 · 已收錄 {allNews.length} 則 · {countByWeight.high} 則高重要
          </p>
        </div>
        <div className="news-hero-r">
          <div className="news-search">
            <Icon name="search" size={14}/>
            <input
              className="search-input"
              placeholder="搜尋標題、代號、來源…"
              value={q}
              onChange={(e) => setQ(e.target.value)}/>
            {q && <button className="btn ghost icon-btn" onClick={() => setQ("")}>
              <Icon name="x" size={12}/>
            </button>}
          </div>
        </div>
      </header>

      {/* Filter rail */}
      <div className="news-filter-rail surface">
        <div className="news-filter-group">
          <span className="news-filter-label">市場</span>
          <div className="seg news-seg">
            {["all", "TW", "US"].map(v => (
              <button key={v} className={market === v ? "active" : ""}
                      onClick={() => setMarket(v)}>
                {marketLabel[v]}
              </button>
            ))}
          </div>
        </div>

        <div className="news-filter-group">
          <span className="news-filter-label">分類</span>
          <div className="seg news-seg">
            {["all", "company", "macro", "tech"].map(v => (
              <button key={v} className={category === v ? "active" : ""}
                      onClick={() => setCategory(v)}>
                {categoryLabel[v]}
              </button>
            ))}
          </div>
        </div>

        <div className="news-filter-group">
          <span className="news-filter-label">權重</span>
          <div className="seg news-seg">
            {["all", "high", "med", "low"].map(v => (
              <button key={v} className={weight === v ? "active" : ""}
                      onClick={() => setWeight(v)}>
                {weightLabel[v]}
                <span className="news-seg-count mono">{countByWeight[v]}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="news-filter-group">
          <span className="news-filter-label">來源</span>
          <select className="select news-source-sel"
                  value={source}
                  onChange={(e) => setSource(e.target.value)}>
            {sources.map(s => (
              <option key={s} value={s}>{s === "all" ? "全部來源" : s}</option>
            ))}
          </select>
        </div>

        <div className="news-filter-spacer"/>

        <div className="news-filter-foot">
          <span className="dim mono" style={{fontSize:"var(--fs-xs)"}}>
            符合 <strong className="num">{filtered.length}</strong> / {allNews.length}
          </span>
          <button className="btn ghost" onClick={resetFilters}>
            <Icon name="refresh" size={12}/> 重設
          </button>
        </div>
      </div>

      {/* Timeline */}
      <div className="news-timeline">
        {filtered.length === 0 ? (
          <div className="news-empty surface">
            <Icon name="news" size={28}/>
            <h3>沒有符合條件的新聞</h3>
            <p className="dim">調整篩選或清空條件再試一次</p>
            <button className="btn primary" onClick={resetFilters}>
              <Icon name="refresh" size={13}/> 重設篩選
            </button>
          </div>
        ) : (
          <>
            {buckets.today.length > 0 && (
              <section className="news-bucket">
                <header className="news-bucket-head">
                  <span className="news-bucket-line"/>
                  <h2 className="news-bucket-title">
                    今日 <span className="mono dim">{buckets.today.length}</span>
                  </h2>
                  <span className="news-bucket-line"/>
                </header>
                <div className="news-grid">
                  {buckets.today.map((n, i) => <NewsCard key={"t" + i} n={n}/>)}
                </div>
              </section>
            )}
            {buckets.yesterday.length > 0 && (
              <section className="news-bucket">
                <header className="news-bucket-head">
                  <span className="news-bucket-line"/>
                  <h2 className="news-bucket-title">
                    昨日 <span className="mono dim">{buckets.yesterday.length}</span>
                  </h2>
                  <span className="news-bucket-line"/>
                </header>
                <div className="news-grid">
                  {buckets.yesterday.map((n, i) => <NewsCard key={"y" + i} n={n}/>)}
                </div>
              </section>
            )}
          </>
        )}
      </div>
    </div>
  );
};

window.NewsPage = NewsPage;
