// Academy modules — Dashboard, Today, Schedule, Students, CRM.

const { useState: mUseState } = React;

// ═══ DASHBOARD ═════════════════════════════════════════════════

function ADashboard({ branchId, lang }) {
  const isHQ = branchId === 'all';
  const latest = TL_KPI_TREND[TL_KPI_TREND.length - 1];
  const prev   = TL_KPI_TREND[TL_KPI_TREND.length - 2];
  const dRev   = (latest.revenue - prev.revenue) / prev.revenue;
  const dStud  = latest.students - prev.students;
  const dLes   = latest.lessons - prev.lessons;
  const dConv  = latest.trialConv - prev.trialConv;

  const t = lang === 'zh';

  return (
    <div style={{ padding: '24px 28px', overflow: 'auto', height: '100%' }} className="tl-noscroll">
      {/* page heading */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#A0A0A0' }}>
            {t ? '主要指標 · 過去六個月' : 'Executive overview · trailing 6 months'}
          </div>
          <h1 style={{ fontFamily: TL_FONTS.serif, fontSize: 36, fontWeight: 500, lineHeight: 1.1, margin: '6px 0 4px', paddingBottom: 4, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>
            {t ? <>四月<em style={{ fontStyle: 'italic' }}>表現摘要</em></> : <>April, <em style={{ fontStyle: 'italic' }}>at a glance</em></>}
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{ background: 'transparent', border: '1px solid rgba(20,20,20,0.15)', padding: '8px 14px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer' }}>
            {t ? '匯出 PDF' : 'Export PDF'}
          </button>
          <button style={{ background: '#141414', color: '#F8F8F8', border: 'none', padding: '8px 14px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer' }}>
            {t ? '本月報告' : 'Monthly report'}
          </button>
        </div>
      </div>

      {/* KPI tiles */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
        <KpiTile
          label={t ? '本月收入' : 'Revenue · MTD'}
          value={aFmtMoney(latest.revenue)}
          delta={aFmtPct(dRev, true)}
          deltaUp={dRev > 0}
          spark={TL_KPI_TREND.map(x => x.revenue)}
        />
        <KpiTile
          label={t ? '在學學生' : 'Active students'}
          value={latest.students.toLocaleString()}
          delta={`+${dStud}`}
          deltaUp
          spark={TL_KPI_TREND.map(x => x.students)}
        />
        <KpiTile
          label={t ? '本月課堂' : 'Lessons this month'}
          value={latest.lessons.toLocaleString()}
          delta={`+${dLes}`}
          deltaUp
          spark={TL_KPI_TREND.map(x => x.lessons)}
        />
        <KpiTile
          label={t ? '試堂轉化率' : 'Trial → enrol'}
          value={aFmtPct(latest.trialConv)}
          delta={aFmtPct(dConv, true)}
          deltaUp={dConv > 0}
          spark={TL_KPI_TREND.map(x => x.trialConv)}
          accent
        />
      </div>

      {/* Two-column row: revenue chart + branch league */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
        <Card>
          <CardHeader title={t ? '月度收入' : 'Monthly revenue'} sub={t ? '單位：百萬港元' : 'HK$ millions'} />
          <div style={{ padding: '8px 20px 18px' }}>
            <ATrendBars data={TL_KPI_TREND} w={500} h={120} />
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, paddingTop: 12, borderTop: '1px solid rgba(20,20,20,0.06)', fontFamily: TL_FONTS.mono, fontSize: 10, color: '#6B6B6B' }}>
              <span>YTD <strong style={{ color: '#141414', fontFamily: TL_FONTS.mono }}>HK$22.4M</strong></span>
              <span>{t ? '預測' : 'Forecast'} HK$68.2M</span>
              <span style={{ color: '#1F7A37' }}>{t ? '達標 +4.2%' : '+4.2% vs target'}</span>
            </div>
          </div>
        </Card>

        <Card>
          <CardHeader title={t ? '分行排名' : 'Branch league'} sub={t ? '本月學生及收入' : 'Students · revenue · this month'} />
          <div>
            {TL_BRANCH_PERF.map((b, i) => {
              const isCurrent = !isHQ && b.id === branchId;
              return (
                <div key={b.id} style={{
                  display: 'grid', gridTemplateColumns: '24px 1fr auto auto auto', gap: 12,
                  padding: '10px 20px', alignItems: 'center',
                  borderTop: i === 0 ? 'none' : '1px solid rgba(20,20,20,0.05)',
                  background: isCurrent ? 'rgba(255,224,3,0.16)' : 'transparent',
                }}>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: '#A0A0A0' }}>{String(i+1).padStart(2,'0')}</div>
                  <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12, fontWeight: isCurrent ? 500 : 400 }}>{b.name}</div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 11, color: '#333', textAlign: 'right', minWidth: 36 }}>{b.students}</div>
                  <div style={{ width: 60 }}>
                    <div style={{ height: 4, background: 'rgba(20,20,20,0.06)', position: 'relative' }}>
                      <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${b.util*100}%`, background: '#141414' }} />
                    </div>
                    <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#6B6B6B', marginTop: 2, textAlign: 'right' }}>{aFmtPct(b.util)} util</div>
                  </div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: b.growth >= 0 ? '#1F7A37' : '#B14B4B', minWidth: 36, textAlign: 'right' }}>
                    {aFmtPct(b.growth, true)}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      {/* Two-column row: lifecycle + funnel */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 12, marginBottom: 16 }}>
        <Card>
          <CardHeader title={t ? '學生生命週期' : 'Student lifecycle'} sub={t ? '尖沙咀分行 · 524 名學生' : 'Tsim Sha Tsui · 524 students'} />
          <div style={{ padding: '6px 20px 20px' }}>
            <div style={{ display: 'flex', height: 28, marginTop: 8 }}>
              {TL_STUDENT_LIFECYCLE.map((s, i) => {
                const total = TL_STUDENT_LIFECYCLE.reduce((a,b) => a + b.count, 0);
                const w = (s.count / total) * 100;
                return <div key={i} style={{ width: `${w}%`, background: s.color, position: 'relative' }} title={`${s.stage}: ${s.count}`} />;
              })}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8, marginTop: 14 }}>
              {TL_STUDENT_LIFECYCLE.map((s, i) => (
                <div key={i}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ width: 8, height: 8, background: s.color }} />
                    <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#6B6B6B', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{s.stage}</span>
                  </div>
                  <div style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, marginTop: 4, letterSpacing: '-0.01em' }}>{s.count}</div>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card>
          <CardHeader title={t ? '招生漏斗 · 過去 30 日' : 'Trial funnel · last 30 days'} sub={t ? '由查詢到首期繳費' : 'Enquiry to first-term paid'} />
          <div style={{ padding: '12px 20px 18px' }}>
            {TL_FUNNEL.map((s, i) => {
              const max = TL_FUNNEL[0].count;
              return <AFunnelBar key={i} count={s.count} max={max} label={s.stage} rate={s.rate} />;
            })}
            <div style={{ marginTop: 8, padding: 12, background: '#141414', color: '#F8F8F8', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: TL_FONTS.sans, fontSize: 11, color: '#A0A0A0' }}>{t ? '由查詢到入學' : 'Enquiry → enrolled'}</span>
              <span style={{ fontFamily: TL_FONTS.serif, fontSize: 24, fontWeight: 500, color: '#FFE003' }}>26.5%</span>
            </div>
          </div>
        </Card>
      </div>

      {/* Tie-in callout */}
      <Card>
        <div style={{ padding: '16px 20px', display: 'flex', gap: 20, alignItems: 'center' }}>
          <div style={{ width: 6, height: 44, background: '#FFE003' }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#6B6B6B' }}>
              {t ? '與家長 / 老師流程連結' : 'Connected to teacher & parent flow'}
            </div>
            <div style={{ fontFamily: TL_FONTS.serif, fontSize: 16, fontWeight: 500, marginTop: 4, lineHeight: 1.35 }}>
              {t ? <>本月 Sophie Lam 已完成 4 次課堂、Ms. Chen 提交 4 份手冊、家長已查閱全部 4 份。<em style={{ fontStyle: 'italic', color: '#6B6B6B' }}> 所有指標即時關聯。</em></>
                 : <>This month Sophie Lam completed 4 lessons · Ms. Chen submitted 4 handbooks · parent opened all 4. <em style={{ fontStyle: 'italic', color: '#6B6B6B' }}>Every metric ties back to a real lesson.</em></>}
            </div>
          </div>
          <button style={{ background: '#141414', color: '#F8F8F8', border: 'none', padding: '10px 16px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
            {t ? '查看 Sophie 個案' : 'View Sophie\u2019s case'}
            <TLIcon name="arrowR" size={12} color="#FFE003" />
          </button>
        </div>
      </Card>
    </div>
  );
}

function KpiTile({ label, value, delta, deltaUp, spark, accent }) {
  return (
    <div style={{
      background: accent ? '#141414' : '#FFFFFF',
      color: accent ? '#F8F8F8' : '#141414',
      padding: '16px 18px', position: 'relative',
      border: accent ? 'none' : '1px solid rgba(20,20,20,0.08)',
    }}>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.16em', textTransform: 'uppercase', color: accent ? '#A0A0A0' : '#6B6B6B' }}>
        {label}
      </div>
      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 30, fontWeight: 500, lineHeight: 1, marginTop: 8, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>
        {value}
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 12 }}>
        <span style={{
          fontFamily: TL_FONTS.mono, fontSize: 10,
          color: deltaUp ? (accent ? '#FFE003' : '#1F7A37') : '#B14B4B',
        }}>{delta}</span>
        <ASparkline data={spark} w={90} h={28} color={accent ? '#FFE003' : '#141414'} fill={accent ? '#FFE003' : '#141414'} />
      </div>
    </div>
  );
}

function Card({ children }) {
  return <div style={{ background: '#FFFFFF', border: '1px solid rgba(20,20,20,0.08)' }}>{children}</div>;
}
function CardHeader({ title, sub, action }) {
  return (
    <div style={{ padding: '14px 20px 16px', borderBottom: '1px solid rgba(20,20,20,0.06)', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
      <div>
        <div style={{ fontFamily: TL_FONTS.serif, fontSize: 16, fontWeight: 500, letterSpacing: '-0.01em' }}>{title}</div>
        {sub && <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#A0A0A0', marginTop: 4 }}>{sub}</div>}
      </div>
      {action}
    </div>
  );
}

window.ADashboard = ADashboard;
window.AKpiTile = KpiTile;
window.ACard = Card;
window.ACardHeader = CardHeader;
