/* global React, window, Icon, PageHead, ScoreBadge, CHART, MONTHS, SERIES, BREAKDOWN, TABLE_ROWS, AI_INSIGHTS, PROP_COLORS, LineChart, ColumnChart, MixChart, CompareChart, niceNum */
/* ============================================================
   Market Charts — flagship analysis page
   ============================================================ */
const { useState: useMC, useEffect: useMCe } = React;

const STATS = {
  avgPrice: { label: 'Average Price', series: SERIES.avgPrice, unit: '', fmt: (v) => '$' + (v / 1000).toFixed(2) + 'M', kfmt: (v) => '$' + niceNum(v) + 'K' },
  sales:    { label: 'Transaction Volume', series: SERIES.sales, fmt: niceNum },
  snlr:     { label: 'SNLR', series: SERIES.snlr, unit: '%', fmt: (v) => v + '%' },
  moi:      { label: 'Months of Inventory', series: SERIES.moi, fmt: (v) => v.toFixed(1) },
  active:   { label: 'Active Listings', series: SERIES.active, fmt: niceNum },
  dom:      { label: 'Avg Days on Market', series: SERIES.dom, fmt: (v) => v + 'd' },
};

const CHART_TYPES = [
  { id: 'line', label: 'Line', icon: 'chart' },
  { id: 'column', label: 'Column', icon: 'trend' },
  { id: 'mix', label: 'Mix', icon: 'layers' },
  { id: 'compare', label: 'YoY / Compare', icon: 'trend' },
  { id: 'grid', label: '3×3 Grid', icon: 'grid', p1: true },
  { id: 'table', label: 'Summary Stats', icon: 'table' },
];

function Seg({ options, value, onChange }) {
  return (
    <div style={{ display: 'inline-flex', background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 6, padding: 3, gap: 2 }}>
      {options.map((o) => (
        <button key={o.v} onClick={() => onChange(o.v)} style={{
          border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, padding: '6px 12px', borderRadius: 4,
          background: value === o.v ? 'var(--accent)' : 'transparent', color: value === o.v ? '#16241B' : 'var(--ink-2)',
        }}>{o.label}</button>
      ))}
    </div>
  );
}

function FilterBar() {
  const filters = [
    ['Sale / Lease', 'Sale'], ['Property Type', 'Detached'], ['Location', 'York Region'],
    ['Beds', 'All'], ['Statistic', 'Average Price'], ['Breakdown', 'None'], ['Date', '24 months'],
  ];
  return (
    <div className="card" style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', position: 'sticky', top: 0, zIndex: 5 }}>
      {filters.map(([l, v]) => (
        <label key={l} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{l}</span>
          <select className="in" defaultValue={v} style={{ padding: '6px 8px', fontSize: 12.5 }}><option>{v}</option></select>
        </label>
      ))}
      <div style={{ flex: 1 }} />
      <button className="chip"><Icon name="filter" size={14} />Advanced</button>
      <button className="chip" data-on="true"><Icon name="save" size={14} />Aurora Detached 12M</button>
    </div>
  );
}

function ChartCanvas({ type, stat, loading }) {
  const s = STATS[stat];
  if (loading) return <div className="skeleton" style={{ height: 320, margin: '8px 0' }} />;
  if (type === 'line') return <LineChart months={MONTHS} series={s.series} fmt={stat === 'avgPrice' ? (v) => '$' + (v / 1000).toFixed(2) + 'M' : s.fmt} color={CHART.green} />;
  if (type === 'column') return <ColumnChart months={MONTHS} series={s.series} fmt={s.fmt} unit={s.unit || ''} color={CHART.green} />;
  if (type === 'mix') return <MixChart months={MONTHS} bars={SERIES.sales} line={SERIES.avgPrice} barColor="#C1E4C1" lineColor={CHART.green} />;
  if (type === 'compare') {
    const a = SERIES.avgPrice.slice(12), b = SERIES.avgPrice.slice(0, 12);
    return <div>
      <div style={{ display: 'flex', gap: 18, marginBottom: 4, fontSize: 12, fontWeight: 600 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 14, height: 3, background: CHART.green, borderRadius: 2 }} />2025–26</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 14, height: 3, background: CHART.steel, borderRadius: 2 }} />2024–25</span>
      </div>
      <CompareChart months={MONTHS.slice(12)} a={a} b={b} fmt={(v) => '$' + (v / 1000).toFixed(1) + 'M'} />
    </div>;
  }
  if (type === 'grid') {
    return <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
      {['Detached', 'Townhouse', 'Semi', 'Condo', 'GTA', 'Toronto', 'York', 'Peel', 'Durham'].map((t, i) => (
        <div key={t} className="card" style={{ padding: 10, background: 'var(--panel-2)' }}>
          <div style={{ fontSize: 11.5, fontWeight: 700, marginBottom: 4 }}>{t}</div>
          <LineChart months={MONTHS} series={SERIES.avgPrice.map((v) => v * (0.7 + i * 0.06))} height={120} color={i % 2 ? CHART.steel : CHART.green} showArea={false} fmt={(v) => '$' + (v / 1000).toFixed(1) + 'M'} />
        </div>
      ))}
    </div>;
  }
  if (type === 'table') return <SummaryStats />;
  return null;
}

function SummaryStats() {
  const rows = [
    ['Average sale price', '$1,622K', '+1.1%', '+11.5%'],
    ['Median sale price', '$1,488K', '+0.9%', '+10.2%'],
    ['Transaction volume', '872', '+3.7%', '+11.8%'],
    ['Active listings', '6,080', '−2.6%', '−14.0%'],
    ['SNLR', '62%', '+5 pts', '+16 pts'],
    ['Months of inventory', '7.0', '−0.4', '−2.4'],
    ['Avg days on market', '19', '−1', '−14'],
    ['SP / LP', '105%', '+1 pt', '+4 pts'],
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 28px' }}>
      {rows.map(([l, v, mom, yoy], i) => (
        <div key={l} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto auto', alignItems: 'center', gap: 14, padding: '11px 0', borderBottom: '1px solid var(--line)' }}>
          <span style={{ fontSize: 13, fontWeight: 600 }}>{l}</span>
          <span className="tabnum" style={{ fontSize: 14, fontWeight: 800 }}>{v}</span>
          <span className="tabnum" style={{ fontSize: 11.5, fontWeight: 700, color: mom[0] === '−' ? CHART.clay : CHART.up, minWidth: 48, textAlign: 'right' }}>{mom}</span>
          <span className="tabnum" style={{ fontSize: 11.5, fontWeight: 700, color: yoy[0] === '−' ? CHART.clay : CHART.up, minWidth: 56, textAlign: 'right' }}>{yoy}</span>
        </div>
      ))}
    </div>
  );
}

function AIHighlights({ audience, setAudience }) {
  const data = AI_INSIGHTS[audience];
  const rows = [
    ['Big Picture', data.bigPicture],
    ['Latest Reading', data.latestReading],
    ['Moves & Streaks', data.streaks],
    ['Highs & Lows', data.highLow],
    ['Seasonal Trends', data.seasonal],
    [audience === 'live' ? 'Buyer & Seller' : audience === 'agent' ? 'Advice' : 'Buyer Advice', data.advice],
  ];
  const aud = [{ v: 'client', label: 'Client' }, { v: 'agent', label: 'Agent' }, { v: 'live', label: 'Live' }];
  return (
    <div className="card" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ padding: '14px var(--card-pad)', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13.5, fontWeight: 700 }}>
          <Icon name="sparkles" size={16} color="var(--accent)" /> AI Market Highlights
        </div>
      </div>
      <div style={{ padding: '10px var(--card-pad) 0' }}>
        <Seg options={aud} value={audience} onChange={setAudience} />
      </div>
      <div className="scroll" style={{ padding: 'var(--card-pad)', display: 'flex', flexDirection: 'column', gap: 15, overflowY: 'auto' }} key={audience}>
        {rows.map(([h, t], i) => (
          <div key={h} className="fade-up" style={{ animationDelay: (i * 40) + 'ms' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 5 }}>{h}</div>
            <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink)' }}>{t}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: '12px var(--card-pad)', borderTop: '1px solid var(--line)', background: 'var(--panel-2)', fontSize: 10.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
        引用：{AI_INSIGHTS.context} · {AI_INSIGHTS.sample}。所有数字来自下方历史表，预测以情景假设标注。
      </div>
    </div>
  );
}

function HistTable() {
  const cols = ['Period', 'Sales', 'New', 'Active', 'Avg Price', 'SNLR', 'MOI', 'DOM', 'SP/LP'];
  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px var(--card-pad)', borderBottom: '1px solid var(--line)' }}>
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>Historical Stats — last 12 months</h3>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-quiet" style={{ fontSize: 12 }}><Icon name="download" size={14} />CSV</button>
          <button className="btn btn-quiet" style={{ fontSize: 12 }}><Icon name="sparkles" size={14} />Summarize</button>
        </div>
      </div>
      <div className="scroll" style={{ overflowX: 'auto' }}>
        <table className="tabnum" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
          <thead>
            <tr>{cols.map((c, i) => (
              <th key={c} style={{ position: i === 0 ? 'sticky' : 'static', left: 0, background: 'var(--panel-2)', textAlign: i ? 'right' : 'left', padding: '10px 16px', fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', borderBottom: '1px solid var(--line)', whiteSpace: 'nowrap' }}>{c}</th>
            ))}</tr>
          </thead>
          <tbody>
            {TABLE_ROWS.map((r, i) => (
              <tr key={r.period} style={{ borderBottom: '1px solid var(--line-2)' }}>
                <td style={{ position: 'sticky', left: 0, background: 'var(--panel)', padding: '10px 16px', fontWeight: 700, whiteSpace: 'nowrap' }}>{r.period}</td>
                <td style={{ textAlign: 'right', padding: '10px 16px' }}>{r.sales}</td>
                <td style={{ textAlign: 'right', padding: '10px 16px', color: 'var(--ink-2)' }}>{r.newList.toLocaleString()}</td>
                <td style={{ textAlign: 'right', padding: '10px 16px', color: 'var(--ink-2)' }}>{r.active.toLocaleString()}</td>
                <td style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 700 }}>${(r.avg / 1000).toFixed(2)}M</td>
                <td style={{ textAlign: 'right', padding: '10px 16px' }}>{r.snlr}%</td>
                <td style={{ textAlign: 'right', padding: '10px 16px' }}>{r.moi.toFixed(1)}</td>
                <td style={{ textAlign: 'right', padding: '10px 16px' }}>{r.dom}</td>
                <td style={{ textAlign: 'right', padding: '10px 16px' }}>{r.splp}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function MarketCharts({ audience, setAudience, setView }) {
  const [type, setType] = useMC('line');
  const [stat, setStat] = useMC('avgPrice');
  const [loading, setLoading] = useMC(false);
  const reload = (fn) => { setLoading(true); fn(); setTimeout(() => setLoading(false), 520); };

  return (
    <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <PageHead eyebrow="Market Charts" title="Custom market analysis"
        actions={<>
          <button className="btn btn-ghost"><Icon name="save" size={15} />Save</button>
          <button className="btn btn-ghost"><Icon name="download" size={15} />PNG</button>
          <button className="btn btn-primary" onClick={() => setView('live')}><Icon name="play" size={14} />Add to Live</button>
        </>} />
      <FilterBar />

      <div style={{ display: 'grid', gridTemplateColumns: '138px minmax(0,1fr) 312px', gap: 16, alignItems: 'start' }}>
        {/* chart type rail */}
        <div className="card" style={{ padding: 8 }}>
          <div className="eyebrow" style={{ padding: '6px 8px' }}>Chart type</div>
          {CHART_TYPES.map((c) => (
            <button key={c.id} onClick={() => reload(() => setType(c.id))} style={{
              display: 'flex', alignItems: 'center', gap: 9, width: '100%', textAlign: 'left', border: 'none', cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, padding: '9px 9px', borderRadius: 6, marginTop: 2,
              background: type === c.id ? 'rgba(100,188,100,0.16)' : 'transparent', color: type === c.id ? 'var(--ink)' : 'var(--ink-2)',
            }}>
              <Icon name={c.icon} size={15} color={type === c.id ? 'var(--accent)' : 'currentColor'} />
              <span style={{ flex: 1 }}>{c.label}</span>
              {c.p1 && <span style={{ fontSize: 8.5, fontWeight: 700, color: 'var(--ink-3)', border: '1px solid var(--line)', borderRadius: 3, padding: '1px 3px' }}>P1</span>}
            </button>
          ))}
        </div>

        {/* canvas */}
        <div className="card" style={{ padding: 'var(--card-pad)', minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, flexWrap: 'wrap', gap: 10 }}>
            <div>
              <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{STATS[stat] ? STATS[stat].label : 'Summary'} <span style={{ color: 'var(--ink-3)', fontWeight: 600, fontSize: 13 }}>· York Detached</span></h3>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3 }}>Source: TRREB Market Watch · 样本 18,472 listings · Updated May 1, 2026</div>
            </div>
            {type !== 'table' && type !== 'grid' && (
              <Seg options={Object.keys(STATS).slice(0, 4).map((k) => ({ v: k, label: STATS[k].label.split(' ')[0] }))} value={stat} onChange={(v) => reload(() => setStat(v))} />
            )}
          </div>
          <ChartCanvas type={type} stat={stat} loading={loading} />
        </div>

        {/* AI */}
        <div style={{ position: 'sticky', top: 70, maxHeight: 'calc(100vh - 130px)' }}>
          <AIHighlights audience={audience} setAudience={setAudience} />
        </div>
      </div>

      <HistTable />
    </div>
  );
}
window.MarketCharts = MarketCharts;
