/* global React, window, Icon, Sparkline, CHART */
/* ============================================================
   App shell + reusable components
   ============================================================ */
const { useState: useS } = React;

const NAV = [
  { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
  { id: 'compare', label: 'Price Compare', icon: 'chart' },
  { id: 'insights', label: 'AI Insights', icon: 'sparkles' },
  { id: 'reports', label: 'Reports', icon: 'reports' },
  { id: 'live', label: 'Live Studio', icon: 'live' },
  { id: 'leads', label: 'Leads / CRM', icon: 'leads' },
  { id: 'cma', label: 'CMA / Pricing', icon: 'cma' },
  { id: 'admin', label: 'Admin', icon: 'admin' },
];

const READY = { dashboard: 1, charts: 1, compare: 1, live: 1, leads: 1 };

function Sidebar({ view, setView, collapsed }) {
  return (
    <aside style={{
      gridArea: 'side', background: 'var(--panel)', borderRight: '1px solid var(--line)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <div style={{ height: 56, display: 'flex', alignItems: 'center', padding: collapsed ? '0 0 0 18px' : '0 18px', borderBottom: '1px solid var(--line)' }}>
        <img src="assets/az-logo-horizontal-color.png" alt="AZ" style={{ height: 22, display: collapsed ? 'none' : 'block' }} />
        {collapsed && <div style={{ width: 28, height: 28, borderRadius: 6, background: 'var(--accent)', color: '#16241B', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 13 }}>AZ</div>}
      </div>
      <div style={{ padding: '6px 0', flex: 1, overflowY: 'auto' }} className="scroll">
        {!collapsed && <div className="eyebrow" style={{ padding: '12px 22px 6px' }}>Workspace</div>}
        {NAV.map((n) => (
          <button key={n.id} className="nav-item" data-active={view === n.id}
            onClick={() => setView(n.id)} title={n.label}
            style={{ justifyContent: collapsed ? 'center' : 'flex-start', margin: collapsed ? '1px 8px' : undefined, width: collapsed ? 'calc(100% - 16px)' : undefined }}>
            <span className="nav-ic" style={{ display: 'flex' }}><Icon name={n.icon} size={18} /></span>
            {!collapsed && <span style={{ flex: 1 }}>{n.label}</span>}
            {!collapsed && !READY[n.id] && <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', color: 'var(--ink-3)', border: '1px solid var(--line)', borderRadius: 3, padding: '1px 4px' }}>P1</span>}
          </button>
        ))}
      </div>
      {!collapsed && (
        <div style={{ padding: 14, borderTop: '1px solid var(--line)' }}>
          <div style={{ background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 8, padding: 12 }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>Data coverage</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5 }}>TRREB Market Watch<br/>Updated <b style={{ color: 'var(--ink)' }}>May 1, 2026</b></div>
          </div>
        </div>
      )}
    </aside>
  );
}

function TopBar({ onToggle, region, setRegion, lang, setLang, exportN, regions }) {
  return (
    <header style={{
      gridArea: 'top', background: 'var(--panel)', borderBottom: '1px solid var(--line)',
      display: 'flex', alignItems: 'center', gap: 14, padding: '0 18px',
    }}>
      <button className="btn-quiet btn" onClick={onToggle} style={{ padding: 7 }} title="Toggle sidebar"><Icon name="layers" size={18} /></button>
      <div style={{ position: 'relative', flex: '0 1 380px', display: 'flex', alignItems: 'center' }}>
        <span style={{ position: 'absolute', left: 11, color: 'var(--ink-3)', display: 'flex' }}><Icon name="search" size={16} /></span>
        <input className="in" placeholder="Search regions, communities, reports, leads…" style={{ width: '100%', paddingLeft: 34, background: 'var(--panel-2)' }} />
      </div>
      <div style={{ flex: 1 }} />
      <div className="region-switch" style={{ display: 'flex', gap: 4, background: 'var(--panel-2)', borderRadius: 7, padding: 3, border: '1px solid var(--line)' }}>
        {regions.slice(0, 4).map((r) => (
          <button key={r.id} onClick={() => setRegion(r.id)} style={{
            border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
            padding: '6px 11px', borderRadius: 5,
            background: region === r.id ? 'var(--accent)' : 'transparent',
            color: region === r.id ? '#16241B' : 'var(--ink-2)',
          }}>{r.name.replace(' Region', '')}</button>
        ))}
      </div>
      <button className="chip" onClick={() => setLang(lang === 'EN' ? '中文' : lang === '中文' ? 'Bi' : 'EN')} title="Language">
        <Icon name="globe" size={15} /> {lang}
      </button>
      <button className="btn-quiet btn" style={{ position: 'relative', padding: 8 }} title="Export queue">
        <Icon name="download" size={18} />
        {exportN > 0 && <span style={{ position: 'absolute', top: 2, right: 2, background: 'var(--accent)', color: '#16241B', fontSize: 9, fontWeight: 800, borderRadius: 999, minWidth: 15, height: 15, display: 'grid', placeItems: 'center', padding: '0 3px' }}>{exportN}</span>}
      </button>
      <button className="btn-quiet btn" style={{ padding: 8 }} title="Notifications"><Icon name="bell" size={18} /></button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, paddingLeft: 6, borderLeft: '1px solid var(--line)' }}>
        <div style={{ width: 30, height: 30, borderRadius: 999, background: 'var(--az-dark-green,#1F281F)', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12 }}>AZ</div>
        <div style={{ lineHeight: 1.2 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700 }}>Arthur Zhao</div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>Broker · AZ Partners</div>
        </div>
      </div>
    </header>
  );
}

/* ---------- Page header ---------- */
function PageHead({ eyebrow, title, sub, actions }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, marginBottom: 18, flexWrap: 'wrap' }}>
      <div>
        {eyebrow && <div className="eyebrow" style={{ marginBottom: 7, color: 'var(--accent)' }}>{eyebrow}</div>}
        <h1 style={{ margin: 0, fontSize: 26, fontWeight: 700, letterSpacing: '-0.015em', lineHeight: 1.1 }}>{title}</h1>
        {sub && <p style={{ margin: '7px 0 0', fontSize: 13.5, color: 'var(--ink-2)', maxWidth: 640 }}>{sub}</p>}
      </div>
      {actions && <div style={{ display: 'flex', gap: 9, alignItems: 'center' }}>{actions}</div>}
    </div>
  );
}

/* ---------- KPI card ---------- */
function KPICard({ k, active, onClick }) {
  const up = k.dir === 'up';
  const col = k.dir === 'up' ? CHART.up : k.dir === 'down' ? CHART.down : 'var(--ink-3)';
  return (
    <button onClick={onClick} className="card" style={{
      padding: 'var(--card-pad)', textAlign: 'left', cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 8,
      outline: active ? '2px solid var(--accent)' : 'none', outlineOffset: -1, fontFamily: 'inherit', color: 'var(--ink)',
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{k.label}</div>
      <div className="tabnum" style={{ fontSize: 27, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1 }}>{k.value}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 12.5, fontWeight: 700, color: col }}>
          {k.dir !== 'flat' && <Icon name={up ? 'arrowUp' : 'arrowDown'} size={13} color={col} />}
          {k.delta}
        </span>
        <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{k.sub} · {k.yoy}</span>
      </div>
    </button>
  );
}

/* ---------- Score badge ---------- */
function ScoreBadge({ tone, children }) {
  const map = {
    green: { bg: 'rgba(100,188,100,0.16)', fg: '#2F6E4E', dot: CHART.green },
    amber: { bg: 'rgba(214,158,46,0.16)', fg: '#9A6B12', dot: CHART.amber },
    clay: { bg: 'rgba(194,85,63,0.14)', fg: '#9E3B27', dot: CHART.clay },
  };
  const c = map[tone] || map.green;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: c.bg, color: c.fg, fontSize: 11.5, fontWeight: 700, padding: '4px 10px', borderRadius: 999 }}>
      <span style={{ width: 7, height: 7, borderRadius: 999, background: c.dot }} />{children}
    </span>
  );
}

/* ---------- Tag pill ---------- */
function Tag({ children, color }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', fontSize: 11, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: color ? color + '22' : 'var(--panel-2)', color: color || 'var(--ink-2)', border: '1px solid ' + (color ? color + '44' : 'var(--line)') }}>{children}</span>;
}

Object.assign(window, { Sidebar, TopBar, PageHead, KPICard, ScoreBadge, Tag, NAV });
