// Main dashboard component — Modern variant, fully responsive

// ── Timezone helpers ──────────────────────────────────────────────────────────
// America/New_York handles EDT (UTC-4) / EST (UTC-5) DST automatically.
// Asia/Shanghai is always UTC+8 with no DST.
function parseTZ(isoStr, tzName) {
  if (!isoStr) return { date: "—", time: "—" };
  try {
    const d = new Date(isoStr);
    const datePart = new Intl.DateTimeFormat("en-US", {
      timeZone: tzName, month: "short", day: "numeric", year: "numeric",
    }).format(d);
    const timePart = new Intl.DateTimeFormat("en-US", {
      timeZone: tzName, hour: "2-digit", minute: "2-digit", hour12: false,
    }).format(d);
    return { date: datePart, time: timePart };
  } catch {
    return { date: "—", time: "—" };
  }
}

// ── Period selector ───────────────────────────────────────────────────────────
const PERIODS = ["1W", "1M", "3M", "6M", "1Y", "3Y"];

function PeriodBar({ period, onChange }) {
  return (
    <div className="period-bar">
      <span className="period-bar-label">RANGE</span>
      <div className="period-btns" role="group" aria-label="Sparkline time range">
        {PERIODS.map((p) => (
          <button
            key={p}
            className={`period-btn${period === p ? " active" : ""}`}
            onClick={() => onChange(p)}
            aria-pressed={period === p}
          >
            {p}
          </button>
        ))}
      </div>
    </div>
  );
}

// ── Main Dashboard ────────────────────────────────────────────────────────────
function Dashboard({ data, onRefresh, refreshing, theme, onToggleTheme }) {
  if (!data) return null;
  const { indices, mag7, hy_oas, cp_spreads, fed, yield_curve } = data;
  const indexKeys = ["spx", "ndx", "iwm"];

  // Period state — shared by Benchmark and Mag7 sparklines
  const [period, setPeriod] = React.useState("1Y");

  // Timezone-aware timestamps from the UTC generated_at field
  const etInfo  = React.useMemo(() => parseTZ(data.generated_at, "America/New_York"), [data.generated_at]);
  const bjtInfo = React.useMemo(() => parseTZ(data.generated_at, "Asia/Shanghai"),    [data.generated_at]);

  // Days until next FOMC
  const daysUntilFOMC = React.useMemo(() => {
    if (!fed?.next_meeting) return null;
    try {
      const next  = new Date(fed.next_meeting);
      const today = new Date();
      const diff  = Math.ceil((next - today) / (1000 * 60 * 60 * 24));
      return diff > 0 ? diff : 0;
    } catch { return null; }
  }, [fed?.next_meeting]);

  return (
    <div className="dash">

      {/* ── Header ── */}
      <header className="dash-header">
        <div className="brand">
          <button className="brand-mark" onClick={onToggleTheme} title="Toggle theme" aria-label="Toggle theme">◐</button>
          <h1 className="brand-title">Macro Market DashBoard</h1>
        </div>

        <div className="header-right">
          <div className="stamp">
            <span className="stamp-dot" />
            <div className="stamp-info">
              <div className="stamp-date">{etInfo.date}</div>
              <div className="stamp-tzrow">
                <span className="stamp-tz">
                  <span className="tz-label">ET</span>
                  <strong className="tz-time">{etInfo.time}</strong>
                </span>
                <span className="stamp-sep">·</span>
                <span className="stamp-tz">
                  <span className="tz-label">BJT</span>
                  <strong className="tz-time">{bjtInfo.time}</strong>
                </span>
              </div>
            </div>
          </div>
          <button
            className={`refresh-btn${refreshing ? " spinning" : ""}`}
            onClick={onRefresh}
            disabled={refreshing || !onRefresh}
            title="Re-fetch data.json"
          >↻</button>
        </div>
      </header>

      {/* ── Period selector — applies to all sparklines ── */}
      <PeriodBar period={period} onChange={setPeriod} />

      {/* ── Section 1: Benchmarks ── */}
      <h2 className="sec-label">Benchmarks</h2>
      <div className="grid-row1">
        {indexKeys.map((k) => {
          const t = indices?.[k];
          if (!t) return null;
          return (
            <article className="card" key={k}>
              <div className="card-top">
                <div>
                  <div className="card-label">{t.label}</div>
                  <div className="card-sub">{t.sub}</div>
                </div>
                <ChangeChip pct={t.change_pct} dir={t.dir} />
              </div>
              <PriceBlock price={t.price} abs={t.change_abs} dir={t.dir} />
              <div className="card-spark">
                <Sparkline
                  data={t.spark}
                  dir={t.dir}
                  h={64}
                  startDate={t.spark_start}
                  endDate={t.spark_end}
                  period={period}
                />
              </div>
            </article>
          );
        })}
      </div>

      {/* ── Section 2: Rate Spread ── */}
      <h2 className="sec-label">Rate Spread</h2>
      <div className="grid-row2">
        {[hy_oas, cp_spreads?.aa, cp_spreads?.a2p2, cp_spreads?.iorb, cp_spreads?.effr]
          .filter(Boolean)
          .map((card) => (
            <article className="card" key={card.label}>
              <div className="card-top">
                <div>
                  <div className="card-label">{card.label}</div>
                  <div className="card-sub">{card.sub}</div>
                </div>
                <ChangeChip
                  text={`${card.change_abs_bps >= 0 ? "+" : ""}${card.change_abs_bps} bps`}
                  dir={card.dir}
                />
              </div>
              <div className="card-price">
                {card.price}<span className="card-unit">%</span>
              </div>
              <div className="card-spark">
                <Sparkline
                  data={card.spark}
                  dir={card.dir}
                  h={64}
                  startDate={card.spark_start}
                  endDate={card.spark_end}
                  period={period}
                  inverted={true}
                  valueType="bps"
                />
              </div>
            </article>
          ))}
      </div>

      {/* ── Federal Reserve ── */}
      {fed && (
        <div className="fed-row-wrap">
          <article className="card card-fed">
            <div className="card-top">
              <div>
                <div className="card-label">{fed.label}</div>
                <div className="card-sub">{fed.sub}</div>
              </div>
              <span className="pill-neutral">RANGE</span>
            </div>
            <div className="card-price card-fed-range">{fed.range}</div>
            <div className="fed-meta">
              <div className="fed-row">
                <span className="fed-k">Last meeting</span>
                <span className="fed-v">{fed.as_of}</span>
              </div>
              {fed.next_meeting && (
                <div className="fed-row">
                  <span className="fed-k">Next meeting</span>
                  <span className="fed-v">{fed.next_meeting}</span>
                </div>
              )}
              {daysUntilFOMC != null && (
                <div className="fed-row fed-cd">
                  <span className="fed-k">Countdown</span>
                  <span className="fed-v fed-big">{daysUntilFOMC} days</span>
                </div>
              )}
            </div>
          </article>
        </div>
      )}

      {/* ── Section 3: Mag 7 (period selector applies) ── */}
      <h2 className="sec-label">Magnificent 7</h2>
      <div className="mag-grid">
        {mag7?.map((m) => (
          <article className="mini" key={m.sym}>
            <div className="mini-head">
              <span className="mini-sym">{m.sym}</span>
              <ChangeChip pct={m.change_pct} dir={m.dir} />
            </div>
            <div className="mini-name">{m.name}</div>
            <div className="mini-price">${m.price}</div>
            <div className={`mini-abs ${m.dir}`}>
              {m.change_abs >= 0 ? "+" : ""}{m.change_abs.toFixed(2)}
            </div>
            <div className="mini-spark">
              <Sparkline
                data={m.spark}
                dir={m.dir}
                h={42}
                startDate={m.spark_start}
                endDate={m.spark_end}
                period={period}
              />
            </div>
          </article>
        ))}
      </div>

      {/* ── Section 4: Treasury Yield Curve ── */}
      {yield_curve?.tenors && (
        <>
          <h2 className="sec-label">Treasury Yield Curve</h2>
          <article className="card card-curve">
            <YieldCurve data={yield_curve} />
          </article>
        </>
      )}

      <footer className="dash-footer">
        <span>Data: yfinance · FRED · treasury.gov</span>
        <span>Generated {data.generated_at}</span>
      </footer>
    </div>
  );
}

window.Dashboard = Dashboard;
