// Academy institutional view — tablet (iPad), 1180 × 820 working area.
// Multi-branch with switcher. Executive dashboard hero.
// Modules: Today · Schedule · Students · Marketing.
// Same Tom Lee editorial system, denser.

const { useState: aUseState, useMemo: aUseMemo } = React;

// — small helpers ————————————————————————————————————————

const aFmtMoney = (m) => `HK$${m.toFixed(2)}M`;
const aFmtPct  = (n, sign = false) => `${sign && n > 0 ? '+' : ''}${(n*100).toFixed(0)}%`;
const aFmtPct1 = (n) => `${(n*100).toFixed(1)}%`;

// Sparkline component
function ASparkline({ data, w = 120, h = 32, color = '#141414', fill }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * (h - 4) - 2;
    return [x, y];
  });
  const path = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ',' + p[1].toFixed(1)).join(' ');
  const area = path + ` L ${w},${h} L 0,${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      {fill && <path d={area} fill={fill} opacity="0.18" />}
      <path d={path} stroke={color} strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.5" fill={color} />
    </svg>
  );
}

// Bar trend
function ATrendBars({ data, w = 280, h = 64, color = '#141414', accent = '#FFE003' }) {
  const max = Math.max(...data.map(d => d.revenue));
  const bw = w / data.length - 4;
  return (
    <svg width={w} height={h + 18} style={{ display: 'block' }}>
      {data.map((d, i) => {
        const bh = (d.revenue / max) * h;
        const x = i * (w / data.length) + 2;
        const y = h - bh;
        const last = i === data.length - 1;
        return (
          <g key={i}>
            <rect x={x} y={y} width={bw} height={bh} fill={last ? accent : color} />
            <text x={x + bw/2} y={h + 12} textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="#6B6B6B">{d.month}</text>
          </g>
        );
      })}
    </svg>
  );
}

// Funnel bar
function AFunnelBar({ count, max, label, rate }) {
  const w = (count / max) * 100;
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontFamily: TL_FONTS.sans, fontSize: 11, color: '#333', marginBottom: 4 }}>
        <span>{label}</span>
        <span style={{ fontFamily: TL_FONTS.mono, color: '#141414' }}>{count} <span style={{ color: '#A0A0A0' }}>· {aFmtPct(rate)}</span></span>
      </div>
      <div style={{ height: 6, background: 'rgba(20,20,20,0.06)' }}>
        <div style={{ width: `${w}%`, height: '100%', background: '#141414' }} />
      </div>
    </div>
  );
}

// — Branch switcher header ————————————————————————————————————

function AHeader({ branchId, setBranchId, lang }) {
  const [open, setOpen] = aUseState(false);
  const branch = TL_BRANCHES.find(b => b.id === branchId);
  return (
    <div style={{
      height: 56, background: '#141414', color: '#F8F8F8',
      display: 'flex', alignItems: 'center', padding: '0 24px',
      borderBottom: '1px solid rgba(255,255,255,0.08)', position: 'relative', flexShrink: 0,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{
          background: '#FFE003', color: '#141414',
          padding: '4px 9px',
          fontFamily: TL_FONTS.sans, fontSize: 12, fontWeight: 700,
          letterSpacing: '0.04em',
        }}>TOM LEE</div>
        <span style={{ fontFamily: TL_FONTS.serif, fontStyle: 'italic', fontSize: 15, color: '#F8F8F8', letterSpacing: '-0.01em' }}>Music</span>
      </div>
      <div style={{ width: 1, height: 22, background: 'rgba(255,255,255,0.2)', margin: '0 18px' }} />
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#FFE003' }}>
        {lang === 'zh' ? '學院營運平台' : 'Academy Operations'}
      </div>

      <div style={{ flex: 1 }} />

      {/* Branch switcher */}
      <button onClick={() => setOpen(o => !o)} style={{
        background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
        color: '#F8F8F8', padding: '7px 14px', cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: 10,
        fontFamily: TL_FONTS.sans, fontSize: 12,
      }}>
        <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          {branch.hq ? (lang === 'zh' ? '總部' : 'HQ') : (lang === 'zh' ? '分行' : 'Branch')}
        </span>
        <strong style={{ fontWeight: 500 }}>{lang === 'zh' ? branch.nameZh : branch.name}</strong>
        <TLIcon name="chevD" size={12} color="#F8F8F8" />
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 54, right: 64, zIndex: 20,
          width: 260, background: '#1E1E1E', border: '1px solid rgba(255,255,255,0.12)',
          padding: 4,
        }}>
          {TL_BRANCHES.map(b => (
            <button key={b.id} onClick={() => { setBranchId(b.id); setOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              width: '100%', padding: '10px 14px', background: b.id === branchId ? 'rgba(255,224,3,0.1)' : 'transparent',
              border: 'none', cursor: 'pointer', textAlign: 'left',
              fontFamily: TL_FONTS.sans, fontSize: 12, color: '#F8F8F8',
              borderTop: b.hq ? '1px solid rgba(255,255,255,0.1)' : 'none',
              marginTop: b.hq ? 4 : 0, paddingTop: b.hq ? 14 : 10,
            }}>
              <span style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>{lang === 'zh' ? b.nameZh : b.name}</div>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2 }}>{b.studios} {lang === 'zh' ? '琴室' : 'studios'}</div>
              </span>
              {b.id === branchId && <TLIcon name="check" size={14} color="#FFE003" />}
            </button>
          ))}
        </div>
      )}

      <div style={{ width: 16 }} />
      <div style={{
        width: 28, height: 28, borderRadius: '50%',
        background: '#FFE003', color: '#141414',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: TL_FONTS.mono, fontSize: 10, fontWeight: 600,
      }}>JL</div>
    </div>
  );
}

// — Sidebar nav ————————————————————————————————————————————

function ASidebar({ tab, setTab, lang }) {
  const items = [
    { id: 'dash',     en: 'Dashboard',     zh: '總覽',      icon: 'home' },
    { id: 'today',    en: 'Today',         zh: '今日',      icon: 'clock' },
    { id: 'sched',    en: 'Schedule',      zh: '時間表',    icon: 'cal' },
    { id: 'stud',     en: 'Students',      zh: '學生',      icon: 'user' },
    { id: 'progress', en: 'Progress',      zh: '進度',      icon: 'chart' },
    { id: 'inbox',    en: 'Conversations', zh: '通訊',      icon: 'msg' },
    { id: 'crm',      en: 'Leads / CRM',   zh: '招生',      icon: 'send' },
  ];
  return (
    <div style={{
      width: 184, background: '#F8F8F8', borderRight: '1px solid rgba(20,20,20,0.08)',
      padding: '20px 0', flexShrink: 0,
    }}>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#A0A0A0', padding: '0 24px 14px' }}>
        {lang === 'zh' ? '主目錄' : 'Modules'}
      </div>
      {items.map(it => {
        const active = tab === it.id;
        return (
          <button key={it.id} onClick={() => setTab(it.id)} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            width: '100%', padding: '11px 24px',
            background: active ? '#141414' : 'transparent',
            color: active ? '#F8F8F8' : '#333',
            border: 'none', cursor: 'pointer', textAlign: 'left',
            fontFamily: TL_FONTS.sans, fontSize: 13,
            borderLeft: active ? '3px solid #FFE003' : '3px solid transparent',
          }}>
            <TLIcon name={it.icon} size={16} color={active ? '#FFE003' : '#6B6B6B'} stroke={1.6} />
            <span style={{ fontWeight: active ? 500 : 400 }}>{lang === 'zh' ? it.zh : it.en}</span>
          </button>
        );
      })}

      <div style={{ height: 1, background: 'rgba(20,20,20,0.08)', margin: '20px 24px' }} />
      <div style={{ padding: '0 24px' }}>
        <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#A0A0A0', marginBottom: 10 }}>
          {lang === 'zh' ? '即將推出' : 'Coming soon'}
        </div>
        {[
          { en: 'Teachers',    zh: '老師' },
          { en: 'Finance',     zh: '財務' },
          { en: 'Exams',       zh: '考試' },
          { en: 'Reports',     zh: '報表' },
        ].map((x, i) => (
          <div key={i} style={{
            fontFamily: TL_FONTS.sans, fontSize: 12, color: '#A0A0A0',
            padding: '7px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <span>{lang === 'zh' ? x.zh : x.en}</span>
            <span style={{ fontFamily: TL_FONTS.mono, fontSize: 8, color: '#A0A0A0', letterSpacing: '0.1em' }}>SOON</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.AHeader = AHeader;
window.ASidebar = ASidebar;
window.ASparkline = ASparkline;
window.ATrendBars = ATrendBars;
window.AFunnelBar = AFunnelBar;
window.aFmtMoney = aFmtMoney;
window.aFmtPct = aFmtPct;
window.aFmtPct1 = aFmtPct1;
