/* === Product Detail page === */
/* global React, LineChart, StackedAreaChart, DrawdownArea, useToast, Icons */
const { useState: useDetailState, useEffect: useDetailEffect } = React;

// 安全访问辅助函数
const safeArr = (arr, defaultVal = []) => Array.isArray(arr) ? arr : defaultVal;
const safeNum = (n, defaultVal = 0) => typeof n === "number" ? n : defaultVal;

// 根据时间范围获取数据的辅助函数 - 按实际日期计算
const getDataByTimeRange = (allData, datesArr, range) => {
  if (!allData || allData.length === 0 || !datesArr || datesArr.length === 0) return allData;
  
  const latestDate = new Date(datesArr[datesArr.length - 1]);
  let cutoffDate;
  
  switch (range) {
    case "6m":
      cutoffDate = new Date(latestDate);
      cutoffDate.setMonth(cutoffDate.getMonth() - 6);
      break;
    case "1y":
      cutoffDate = new Date(latestDate);
      cutoffDate.setFullYear(cutoffDate.getFullYear() - 1);
      break;
    case "all":
    default:
      return allData; // 返回全部数据
  }
  
  // 找到第一个在cutoffDate之后的数据点索引
  let startIdx = 0;
  for (let i = 0; i < datesArr.length; i++) {
    const d = new Date(datesArr[i]);
    if (d >= cutoffDate) {
      startIdx = i;
      break;
    }
  }
  
  return allData.slice(startIdx);
};

// 获取对应时间范围的日期数组 - 按实际日期计算
const getDatesByTimeRange = (datesArr, range) => {
  if (!datesArr || datesArr.length === 0) return datesArr;
  
  const latestDate = new Date(datesArr[datesArr.length - 1]);
  let cutoffDate;
  
  switch (range) {
    case "6m":
      cutoffDate = new Date(latestDate);
      cutoffDate.setMonth(cutoffDate.getMonth() - 6);
      break;
    case "1y":
      cutoffDate = new Date(latestDate);
      cutoffDate.setFullYear(cutoffDate.getFullYear() - 1);
      break;
    case "all":
    default:
      return datesArr; // 返回全部日期
  }
  
  // 找到第一个在cutoffDate之后的日期索引
  let startIdx = 0;
  for (let i = 0; i < datesArr.length; i++) {
    const d = new Date(datesArr[i]);
    if (d >= cutoffDate) {
      startIdx = i;
      break;
    }
  }
  
  return datesArr.slice(startIdx);
};

function PageProductDetail({ productId, onNav, openDrawer, setProductId }) {
  // 安全获取所有需要的数据
  const products = safeArr(window.IRDATA?.products);
  const categories = safeArr(window.IRDATA?.CATEGORIES);
  const dates = safeArr(window.IRDATA?.DATES);
  const [timeseriesLoaded, setTimeseriesLoaded] = useDetailState(false);
  const [timeRange, setTimeRange] = useDetailState("1y"); // 默认显示1年

  // 懒加载时序数据
  useDetailEffect(() => {
    if (productId && window.IRDATA?.loadTimeseries) {
      window.IRDATA.loadTimeseries(productId).then(() => {
        setTimeseriesLoaded(prev => !prev);
      });
    }
  }, [productId]);

  // 如果没有产品数据，显示加载中
  if (!products || products.length === 0) {
    return (
      <div className="card">
        <div className="card-body" style={{ padding: "80px 20px", textAlign: "center" }}>
          <div className="coming-soon-icon">📊</div>
          <h3>产品数据加载中...</h3>
          <p>请稍候或刷新页面</p>
        </div>
      </div>
    );
  }

  // 安全查找产品
  let p = products.find((x) => x && x.id === productId);
  if (!p) {
    p = products[0]; // 使用第一个产品作为备用
  }
  if (!p) {
    return (
      <div className="card">
        <div className="card-body" style={{ padding: "80px 20px", textAlign: "center" }}>
          <div className="coming-soon-icon">⚠️</div>
          <h3>未找到产品数据</h3>
          <p>请返回产品池选择产品</p>
          <button className="btn btn-primary" onClick={() => onNav("pool-list")}>
            返回产品池
          </button>
        </div>
      </div>
    );
  }

  // 安全获取分类
  let safeCat = { color: "#0f5cff", name: "未分类" };
  if (p.catId) {
    const cat = categories.find(c => c && c.id === p.catId);
    if (cat) {
      safeCat = cat;
    }
  }

  const toast = useToast();

  const [legendOff, setLegendOff] = useDetailState(new Set());
  const isOff = (k) => legendOff.has(k);
  const toggleLegend = (k) => {
    const s = new Set(legendOff);
    s.has(k) ? s.delete(k) : s.add(k);
    setLegendOff(s);
  };

  // 获取当前时间范围过滤后的日期
  const filteredDates = getDatesByTimeRange(dates, timeRange);

  // 获取当前时间范围过滤后的净值数据
  const filteredNavSeries = getDataByTimeRange(safeArr(p.navSeries), dates, timeRange);
  const filteredBenchSeries = getDataByTimeRange(safeArr(p.benchmarkSeries), dates, timeRange);
  const filteredPeerSeries = getDataByTimeRange(safeArr(p.peerSeries), dates, timeRange);

  const lineSeries = [
    { key: "self",  name: p.name || "产品", color: safeCat.color, data: filteredNavSeries },
    { key: "bench", name: "模拟基准",  color: "#6c7a93", data: filteredBenchSeries },
    { key: "peer",  name: "模拟同类中位数", color: "#00a99d", data: filteredPeerSeries },
  ].filter((s) => !isOff(s.key));

  // 获取当前时间范围过滤后的回撤数据
  const filteredDrawdown = getDataByTimeRange(safeArr(p.drawdown), dates, timeRange);

  // strategy metrics
  const sm = p.strategyMetrics || {};

  const allocColors = ["#0f5cff", "#00a99d", "#ff7a1a", "#6b4ce6"];
  const allocWithSeries = safeArr(p.allocation);
  const allocDates = safeArr(p.allocationDates);

  // 获取当前时间范围过滤后的策略数据 - 使用策略自己的日期
  const filteredAllocWithSeries = allocWithSeries.map(s => ({
    ...s,
    series: getDataByTimeRange(safeArr(s.series), allocDates, timeRange)
  }));

  // 获取过滤后的策略日期
  const filteredAllocDates = getDatesByTimeRange(allocDates, timeRange);

  return (
    <React.Fragment>
      {/* Product picker bar */}
      <div className="filter-bar">
        <span className="filter-label">查看产品：</span>
        <select className="select" value={p.id || ""} onChange={(e) => setProductId(e.target.value)} style={{ minWidth: 200 }}>
          {products.map((pp) => (
            <option key={pp.id || pp.code} value={pp.id}>
              {pp.name || "产品"} · {pp.code || ""}
            </option>
          ))}
        </select>
        <div className="spacer" />
        <button className="btn" onClick={() => onNav("pool-compare")}>加入对比</button>
        <button className="btn primary" onClick={() => toast.push("已导出 PDF 评价报告（模拟）")}>导出报告</button>
      </div>

      {/* Profile */}
      <div className="card" style={{ marginBottom: 16, overflow: "hidden" }}>
        <div style={{
          background: `linear-gradient(95deg, ${safeCat.color} 0%, ${safeCat.color}aa 100%)`,
          color: "#fff", padding: "18px 22px", position: "relative",
        }}>
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{
              width: 44, height: 44, borderRadius: 8,
              background: "rgba(255,255,255,0.15)",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontFamily: "var(--mono)", fontSize: 13, fontWeight: 600,
              border: "1px solid rgba(255,255,255,0.25)",
            }}>{p.rating || "N/A"}</div>
            <div>
              <div style={{ fontSize: 20, fontWeight: 600 }}>{p.name || "产品名称"}</div>
              <div style={{ fontSize: 12.5, opacity: 0.9, marginTop: 4, display: "flex", gap: 18 }}>
                <span>{p.code || ""}</span>
                <span>管理人：<b style={{ fontFamily: "var(--mono)" }}>{p.manager || ""}</b></span>
                <span>类型：{p.type || ""}</span>
                <span>分类：{safeCat.name}</span>
              </div>
            </div>
            <div className="spacer" />
            <div style={{ display: "flex", gap: 20, fontSize: 11 }}>
              <div>
                <div style={{ opacity: 0.7 }}>最新净值</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600 }}>
                  {typeof p.nav === "number" ? p.nav.toFixed(4) : "N/A"}
                </div>
              </div>
              <div>
                <div style={{ opacity: 0.7 }}>年化收益</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600 }}>
                  {(safeNum(p.annualReturn) * 100).toFixed(2)}%
                </div>
              </div>
              <div>
                <div style={{ opacity: 0.7 }}>夏普</div>
                <div className="num" style={{ fontSize: 18, fontWeight: 600 }}>
                  {safeNum(p.sharpe).toFixed(2)}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style={{ padding: "14px 22px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 4 }}>系统结论</div>
            <div style={{ fontSize: 12.5, color: "var(--fg)", lineHeight: 1.7 }}>{p.conclusion || ""}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--red)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 4 }}>主要风险</div>
            <div style={{ fontSize: 12.5, color: "var(--fg)", lineHeight: 1.7 }}>{p.risk || ""}</div>
          </div>
        </div>
      </div>

      {/* === 4 modules in 2x2 grid === */}
      <div className="grid" style={{ gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 14, marginBottom: 16 }}>
        {/* === 业绩表现 === */}
        <div className="card">
          <div className="card-header">
            <div className="card-title"><span className="bar" />业绩表现</div>
            <div style={{ display: "flex", gap: 4 }}>
              <button 
                className={"btn sm" + (timeRange === "6m" ? " primary" : "")} 
                onClick={() => setTimeRange("6m")}
              >近 6M</button>
              <button 
                className={"btn sm" + (timeRange === "1y" ? " primary" : "")} 
                onClick={() => setTimeRange("1y")}
              >近 1Y</button>
              <button 
                className={"btn sm" + (timeRange === "all" ? " primary" : "")} 
                onClick={() => setTimeRange("all")}
              >成立以来</button>
            </div>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <div style={{ padding: "14px 18px 6px" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)", display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
                <span style={{ width: 4, height: 4, borderRadius: 2, background: "var(--primary)" }} />
                净值走势
                <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>产品 vs 基准 vs 同类中位数</span>
              </div>
              <div className="chart-legend">
                {[
                  { key: "self", name: p.name || "产品", color: safeCat.color },
                  { key: "bench", name: "模拟基准", color: "#6c7a93" },
                  { key: "peer", name: "模拟同类中位数", color: "#00a99d" },
                ].map((it) => (
                  <div key={it.key} className={"l-item " + (isOff(it.key) ? "muted" : "")} onClick={() => toggleLegend(it.key)}>
                    <span className="l-swatch" style={{ background: it.color, height: 3 }} />
                    {it.name}
                  </div>
                ))}
              </div>
              <LineChart
                series={lineSeries}
                dates={filteredDates}
                height={170}
                format="nav"
                onPointClick={(idx) => {
                  openDrawer({ kind: "info", payload: {
                    title: `净值点 · ${filteredDates[idx] || ""}`,
                    sub: p.name || "产品",
                    kvs: [
                      { k: p.name || "产品", v: <span className="num">{filteredNavSeries[idx]?.toFixed(4) || "N/A"}</span> },
                      { k: "模拟基准", v: <span className="num">{filteredBenchSeries[idx]?.toFixed(4) || "N/A"}</span> },
                      { k: "同类中位数", v: <span className="num">{filteredPeerSeries[idx]?.toFixed(4) || "N/A"}</span> },
                      { k: "超额", v: <span className="num good">{filteredNavSeries[idx] && filteredBenchSeries[idx] ? ((filteredNavSeries[idx] / filteredBenchSeries[idx] - 1) * 100).toFixed(2) + "%" : "N/A"}</span> },
                    ],
                    body: "点击净值曲线任意点，可查看当日产品净值、基准、同类对比及超额收益。",
                  } });
                }} />
            </div>
            <div style={{ height: 1, background: "var(--divider)", margin: "0 18px" }} />
            <div style={{ padding: "12px 18px 16px" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)", display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
                <span style={{ width: 4, height: 4, borderRadius: 2, background: "var(--primary)" }} />
                收益指标
                <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>累计与年化口径</span>
              </div>
              {(() => {
                const navArr = safeArr(p.navSeries);
                const last = navArr[navArr.length - 1];
                const startVal = navArr[0];
                const weekRef = navArr[Math.max(0, navArr.length - 6)];
                const weekChg = typeof last === "number" && typeof weekRef === "number" ? last / weekRef - 1 : 0;
                const sinceChg = typeof last === "number" && typeof startVal === "number" ? last / startVal - 1 : 0;
                const items = [
                  { label: "累计净值", val: typeof last === "number" ? last.toFixed(4) : "N/A", color: "var(--fg)" },
                  { label: "本周净值涨跌", val: (weekChg * 100).toFixed(2) + "%", color: weekChg >= 0 ? "var(--red)" : "var(--green)" },
                  { label: "成立以来净值涨跌", val: (sinceChg * 100).toFixed(2) + "%", color: sinceChg >= 0 ? "var(--red)" : "var(--green)" },
                  { label: "成立以来年化收益", val: (safeNum(p.annualReturn) * 100).toFixed(2) + "%", color: safeNum(p.annualReturn) >= 0 ? "var(--red)" : "var(--green)" },
                ];
                return (
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 10 }}>
                    {items.map((m, i) => (
                      <div key={i} className="s-metric">
                        <div className="l">{m.label}</div>
                        <div className="v" style={{ color: m.color }}>{m.val}</div>
                      </div>
                    ))}
                  </div>
                );
              })()}
            </div>
          </div>
        </div>

        {/* === 风险控制 (merged: drawdown chart + 4 metrics) === */}
        <div className="card">
          <div className="card-header">
            <div className="card-title"><span className="bar" style={{ background: "var(--red)" }} />风险控制</div>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <div style={{ padding: "14px 18px 6px" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)", display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
                <span style={{ width: 4, height: 4, borderRadius: 2, background: "var(--red)" }} />
                回撤曲线
                <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>历史净值相对前高的跌幅</span>
              </div>
              <DrawdownArea
                data={filteredDrawdown}
                dates={filteredDates}
                color="#ef3f3f"
                height={170}
                threshold={[{ y: -0.06, color: "#ef3f3f", label: "阈值 -6%" }]}
              />
            </div>
            <div style={{ height: 1, background: "var(--divider)", margin: "0 18px" }} />
            <div style={{ padding: "12px 18px 16px" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)", display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
                <span style={{ width: 4, height: 4, borderRadius: 2, background: "var(--orange)" }} />
                风险指标
                <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>关键风险口径汇总</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 10 }}>
                {[
                  { label: "当前回撤", val: (safeNum(p.currentDrawdown) * 100).toFixed(2) + "%", color: "var(--orange)" },
                  { label: "最大回撤", val: (safeNum(p.maxDrawdown) * 100).toFixed(2) + "%", color: "var(--red)" },
                  { label: "夏普比率", val: safeNum(p.sharpe).toFixed(2), color: "var(--primary)" },
                  { label: "卡玛比率", val: safeNum(p.calmar).toFixed(2), color: "var(--purple)" },
                ].map((m, i) => (
                  <div key={i} className="s-metric">
                    <div className="l">{m.label}</div>
                    <div className="v" style={{ color: m.color }}>{m.val}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* === 收益质量 === */}
        <div className="card">
          <div className="card-header"><div className="card-title"><span className="bar" style={{ background: "var(--teal)" }} />收益质量</div></div>
          <div className="card-body">
            <div className="empty" style={{ padding: "48px 18px" }}>
              <div className="icon">{Icons.empty}</div>
              收益质量指标待接入
              <div style={{ fontSize: 11, marginTop: 4 }}>归因模块预计 2026 Q3 上线</div>
            </div>
          </div>
        </div>

        {/* === 策略行为 (merged: allocation + strategy metrics) === */}
        <div className="card">
          <div className="card-header">
            <div className="card-title"><span className="bar" style={{ background: "var(--purple)" }} />策略行为</div>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <div style={{ padding: "14px 18px 6px" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)", display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
                <span style={{ width: 4, height: 4, borderRadius: 2, background: "var(--primary)" }} />
                配置变化
                <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>四类策略权重的逐月推移</span>
              </div>
              <div className="chart-legend">
                {filteredAllocWithSeries.map((s, i) => (
                  <div key={i} className="l-item">
                    <span className="l-swatch" style={{ background: s.color || allocColors[i], height: 9, width: 14, borderRadius: 2 }} />
                    {s.name}
                  </div>
                ))}
              </div>
              {filteredAllocWithSeries.length > 0 ? (
                <StackedAreaChart
                  series={filteredAllocWithSeries.map((s, i) => ({
                    name: s.name,
                    color: s.color || allocColors[i],
                    data: safeArr(s.series),
                  }))}
                  labels={filteredAllocDates.length > 0 ? filteredAllocDates : Array.from({ length: safeArr(filteredAllocWithSeries[0]?.series).length }, (_, i) => `M${i + 1}`)}
                  height={160}
                />
              ) : (
                <div className="empty" style={{ padding: "40px 18px" }}>暂无配置数据</div>
              )}
            </div>
            <div style={{ height: 1, background: "var(--divider)", margin: "0 18px" }} />
            <div style={{ padding: "12px 18px 16px" }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-2)", display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
                <span style={{ width: 4, height: 4, borderRadius: 2, background: "var(--purple)" }} />
                策略指标
                <span className="muted" style={{ fontWeight: 400, fontSize: 11 }}>调仓与集中度</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 10 }}>
                <div className="s-metric">
                  <div className="l">策略配置能力</div>
                  <div className="v">{safeNum(sm.strategic, 0.7).toFixed(2)}</div>
                </div>
                <div className="s-metric">
                  <div className="l">战术择时能力</div>
                  <div className="v">{safeNum(sm.tactical, 0.65).toFixed(2)}</div>
                </div>
                <div className="s-metric">
                  <div className="l">基金选择能力</div>
                  <div className="v">{safeNum(sm.selection, 0.8).toFixed(2)}</div>
                </div>
                <div className="s-metric">
                  <div className="l">综合得分</div>
                  <div className="v">{safeNum(p.score, 0.75).toFixed(2)}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { PageProductDetail });
