import { useEffect, useRef } from "react";
import type { SimilarEra, SimilarDetail } from "../lib/api";
import { Tag } from "./ui";
import IndicatorCompareBars from "./IndicatorCompareBars";
import SeriesChart from "./SeriesChart";

export default function EraDetailPanel({
  similar,
  open,
  onClose,
}: {
  similar: SimilarEra;
  open: boolean;
  onClose: () => void;
}) {
  const panelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open || !similar.detail) return null;
  const d: SimilarDetail = similar.detail;
  const title = similar.regimeLabel
    ? `${similar.date}（${similar.regimeLabel}）`
    : similar.date;

  return (
    <div className="era-overlay" onClick={onClose} role="presentation">
      <div
        className="era-panel"
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="era-panel-title"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="era-panel-head">
          <div>
            <div className="era-panel-eyebrow">編年史檔案 · 歷史相似期</div>
            <h2 id="era-panel-title" className="era-panel-title">
              {title}
            </h2>
            <div className="era-panel-meta">
              相似度距離 <b>{similar.distance?.toFixed(2)}</b>
              {d.asOfDate && <span>　對照基準日 {d.asOfDate}</span>}
            </div>
          </div>
          <button type="button" className="era-close" onClick={onClose} aria-label="關閉">
            ×
          </button>
        </div>

        <div className="era-panel-body">
          <section className="era-section">
            <h3>為什麼像？</h3>
            <p>{d.whySimilar}</p>
            {(d.topDrivers?.length ?? 0) > 0 && (
              <div className="era-chips">
                {d.topDrivers!.map((t) => (
                  <Tag key={t} tone="gold">
                    {t}
                  </Tag>
                ))}
              </div>
            )}
          </section>

          <section className="era-section">
            <h3>指標對照 · 現在 vs 當時</h3>
            <p className="small muted">橫條代表各指標在長期歷史中的標準化位置（z-score）；越接近代表越像。</p>
            <IndicatorCompareBars rows={d.comparisons || []} />
          </section>

          {d.market && (
            <section className="era-section">
              <h3>當時股市怎麼走？（S&P 500）</h3>
              <div className="era-market-grid">
                <MarketStat label="當時水準" value={d.market.levelAt != null ? String(d.market.levelAt) : "—"} />
                <MarketStat
                  label="前 3 個月"
                  value={fmtRet(d.market.ret3mBefore)}
                  tone={retTone(d.market.ret3mBefore)}
                />
                <MarketStat
                  label="後 6 個月"
                  value={fmtRet(d.market.ret6mAfter)}
                  tone={retTone(d.market.ret6mAfter)}
                />
                <MarketStat
                  label="後 12 個月"
                  value={fmtRet(d.market.ret12mAfter)}
                  tone={retTone(d.market.ret12mAfter)}
                />
              </div>
              {d.market.trendLabel && (
                <p className="era-trend">
                  一年後走勢歸納：<Tag tone={retTone(d.market.ret12mAfter)}>{d.market.trendLabel}</Tag>
                </p>
              )}
              {d.market.chart?.length ? (
                <div className="chart-panel era-chart">
                  <SeriesChart data={d.market.chart} color="#6fe0d0" />
                  <div className="era-chart-cap small muted">相似期前後約 18 個月走勢（垂直線為相似月份）</div>
                </div>
              ) : null}
              <p className="small muted">歷史表現僅供參照，不代表未來會重複。</p>
            </section>
          )}

          {d.episode && (
            <section className="era-section era-episode">
              <h3>歷史案例 · {d.episode.title}</h3>
              <div className="small muted">{d.episode.period}</div>
              <p>{d.episode.summary}</p>
              {d.episode.lesson && (
                <blockquote className="era-lesson">
                  <span className="era-lesson-k">啟示</span>
                  {d.episode.lesson}
                </blockquote>
              )}
            </section>
          )}

          {(d.events?.length ?? 0) > 0 && (
            <section className="era-section">
              <h3>當時附近的大事件</h3>
              <ul className="era-events">
                {d.events!.map((e) => (
                  <li key={e.date + e.label}>
                    <span className="era-ev-date">{e.date}</span>
                    <span className="era-ev-label">{e.label}</span>
                    <span className="era-ev-timing muted small">{e.timing}</span>
                  </li>
                ))}
              </ul>
            </section>
          )}
        </div>
      </div>
    </div>
  );
}

function MarketStat({ label, value, tone }: { label: string; value: string; tone?: "up" | "down" | "cool" }) {
  return (
    <div className="era-mstat">
      <div className="era-mstat-k">{label}</div>
      <div className={"era-mstat-v" + (tone ? " " + tone : "")}>{value}</div>
    </div>
  );
}

function fmtRet(v: number | null | undefined) {
  if (v == null) return "—";
  return `${v >= 0 ? "+" : ""}${v}%`;
}

function retTone(v: number | null | undefined): "up" | "down" | "cool" | undefined {
  if (v == null) return "cool";
  if (v >= 3) return "up";
  if (v <= -3) return "down";
  return "cool";
}