// Academy modules — Today, Schedule grid, Students, CRM/Leads.

const { useState: m2UseState } = React;
// Components defined in academy-dashboard.jsx
const ACard = window.ACard;
const ACardHeader = window.ACardHeader;

// ═══ TODAY AT THE BRANCH ═══════════════════════════════════════

function AToday({ branchId, lang }) {
  const t = lang === 'zh';
  const branch = TL_BRANCHES.find(b => b.id === branchId);
  const data = TL_BRANCH_TODAY;
  const occ = data.rooms.filter(r => r.status === 'occupied').length;
  const total = data.rooms.length;

  const STATUS = {
    occupied: { label: t ? '進行中' : 'In lesson', color: '#141414', ink: '#F8F8F8' },
    turnover: { label: t ? '換堂中' : 'Turnover',  color: '#FFE003', ink: '#141414' },
    empty:    { label: t ? '空置'   : 'Empty',     color: '#FFFFFF', ink: '#6B6B6B', border: true },
    maint:    { label: t ? '維修'   : 'Maint.',    color: '#EFEFEF', ink: '#6B6B6B' },
  };

  return (
    <div style={{ padding: '24px 28px', overflow: 'auto', height: '100%' }} className="tl-noscroll">
      <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 ? '今日營運 · 即時' : 'Live operations · ' + branch.name} · {data.asOf}
          </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></> : <>The branch <em style={{ fontStyle: 'italic' }}>right now.</em></>}
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 24, alignItems: 'flex-end' }}>
          <Stat n={`${occ}/${total}`} label={t ? '琴室使用中' : 'Studios in use'} />
          <Stat n={aFmtPct(occ/total)} label={t ? '使用率' : 'Utilisation'} />
          <Stat n="32" label={t ? '今日課堂' : 'Lessons today'} />
          <Stat n="14" label={t ? '老師在班' : 'Teachers on shift'} />
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
        {/* Studio grid */}
        <ACard>
          <ACardHeader title={t ? '琴室即時' : 'Studio status'} sub={t ? `截至 ${data.asOf}` : `as of ${data.asOf}`} />
          <div style={{ padding: 12, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {data.rooms.map(r => {
              const s = STATUS[r.status];
              return (
                <div key={r.id} style={{
                  background: s.color, color: s.ink,
                  padding: '12px 14px', minHeight: 96,
                  border: s.border ? '1px solid rgba(20,20,20,0.1)' : 'none',
                  position: 'relative',
                }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
                    <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.1em', fontWeight: 500 }}>{r.name}</div>
                    <div style={{ fontFamily: TL_FONTS.mono, fontSize: 8, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.65 }}>{r.instrument}</div>
                  </div>
                  {r.status === 'occupied' && (
                    <>
                      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 14, fontWeight: 500, lineHeight: 1.2 }}>{r.student}</div>
                      <div style={{ fontFamily: TL_FONTS.sans, fontSize: 10, opacity: 0.7, marginTop: 2 }}>{r.teacher}</div>
                      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, marginTop: 6, color: '#FFE003' }}>· {t ? '至' : 'ends'} {r.endsAt}</div>
                    </>
                  )}
                  {r.status === 'turnover' && (
                    <>
                      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 13, fontWeight: 500 }}>{t ? '換堂' : 'Turnover'}</div>
                      <div style={{ fontFamily: TL_FONTS.sans, fontSize: 10, marginTop: 2 }}>{r.teacher}</div>
                      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, marginTop: 6 }}>{r.nextStart} → {r.nextStudent}</div>
                    </>
                  )}
                  {r.status === 'empty' && (
                    <>
                      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 13, fontWeight: 500, fontStyle: 'italic' }}>{t ? '空置' : 'Empty'}</div>
                      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, marginTop: 12, color: '#A0A0A0' }}>{t ? '下一堂' : 'Next'} {r.nextStart} · {r.nextStudent}</div>
                    </>
                  )}
                  {r.status === 'maint' && (
                    <>
                      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 13, fontWeight: 500, fontStyle: 'italic', color: '#B14B4B' }}>{t ? '維修中' : 'Maintenance'}</div>
                      <div style={{ fontFamily: TL_FONTS.sans, fontSize: 10, color: '#6B6B6B', marginTop: 6 }}>{r.note}</div>
                    </>
                  )}
                </div>
              );
            })}
          </div>
          {/* legend */}
          <div style={{ display: 'flex', gap: 18, padding: '0 20px 16px', fontFamily: TL_FONTS.mono, fontSize: 9, color: '#6B6B6B', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            <Legend color="#141414" label={t ? '進行中' : 'In lesson'} />
            <Legend color="#FFE003" label={t ? '換堂' : 'Turnover'} />
            <Legend color="#FFFFFF" border label={t ? '空置' : 'Empty'} />
            <Legend color="#EFEFEF" label={t ? '維修' : 'Maintenance'} />
          </div>
        </ACard>

        {/* Alerts column */}
        <div>
          <ACard>
            <ACardHeader title={t ? '需要處理' : 'Needs attention'} sub={`${data.alerts.length} ${t ? '項提示' : 'alerts'}`} />
            {data.alerts.map(a => (
              <div key={a.id} style={{ padding: '14px 20px', borderTop: '1px solid rgba(20,20,20,0.06)', display: 'flex', gap: 12 }}>
                <span style={{
                  width: 8, height: 8, borderRadius: '50%', flexShrink: 0, marginTop: 6,
                  background: a.kind === 'late' ? '#FFE003' : a.kind === 'noshow' ? '#B14B4B' : '#141414',
                }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12, lineHeight: 1.4, color: '#141414' }}>{a.text}</div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 4 }}>{a.time}</div>
                </div>
                <TLIcon name="chevR" size={14} color="#A0A0A0" />
              </div>
            ))}
          </ACard>

          <div style={{ height: 12 }} />

          <ACard>
            <ACardHeader title={t ? '今日課堂分佈' : 'Today\u2019s lesson mix'} sub={t ? '依樂器' : 'By instrument'} />
            <div style={{ padding: '12px 20px 16px' }}>
              {[
                { i: 'Piano',     n: 14, en: 'Piano',     zh: '鋼琴' },
                { i: 'Violin',    n: 5,  en: 'Violin',    zh: '小提琴' },
                { i: 'Voice',     n: 4,  en: 'Voice',     zh: '聲樂' },
                { i: 'Cello',     n: 3,  en: 'Cello',     zh: '大提琴' },
                { i: 'Saxophone', n: 2,  en: 'Saxophone', zh: '色士風' },
                { i: 'Other',     n: 4,  en: 'Other',     zh: '其他' },
              ].map((x, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '80px 1fr 28px', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <span style={{ fontFamily: TL_FONTS.sans, fontSize: 11, color: '#333' }}>{t ? x.zh : x.en}</span>
                  <div style={{ height: 6, background: 'rgba(20,20,20,0.06)' }}>
                    <div style={{ height: '100%', width: `${(x.n / 14) * 100}%`, background: '#141414' }} />
                  </div>
                  <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: '#141414', textAlign: 'right' }}>{x.n}</span>
                </div>
              ))}
            </div>
          </ACard>
        </div>
      </div>
    </div>
  );
}

function Stat({ n, label }) {
  return (
    <div style={{ textAlign: 'right' }}>
      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 26, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>{n}</div>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#A0A0A0', marginTop: 4 }}>{label}</div>
    </div>
  );
}
function Legend({ color, border, label }) {
  return (
    <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <span style={{ width: 10, height: 10, background: color, border: border ? '1px solid rgba(20,20,20,0.2)' : 'none' }} />
      {label}
    </span>
  );
}

// ═══ SCHEDULE GRID ═════════════════════════════════════════════

function ASchedule({ branchId, lang }) {
  const t = lang === 'zh';
  return (
    <div style={{ padding: '24px 28px', overflow: 'auto', height: '100%' }} className="tl-noscroll">
      <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 ? '時間表 · 星期二 4 月 28 日' : 'Schedule · Tue, Apr 28'}
          </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></> : <>The day, <em style={{ fontStyle: 'italic' }}>laid out.</em></>}
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <button style={{ width: 32, height: 32, background: 'transparent', border: '1px solid rgba(20,20,20,0.15)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <TLIcon name="chevL" size={14} />
          </button>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 11, padding: '0 14px' }}>{t ? 'Apr 28 (二)' : 'Apr 28 (Tue)'}</div>
          <button style={{ width: 32, height: 32, background: 'transparent', border: '1px solid rgba(20,20,20,0.15)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <TLIcon name="chevR" size={14} />
          </button>
          <div style={{ width: 12 }} />
          <button style={{ background: 'transparent', border: '1px solid rgba(20,20,20,0.15)', padding: '7px 12px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer' }}>{t ? '日' : 'Day'}</button>
          <button style={{ background: '#141414', color: '#F8F8F8', border: 'none', padding: '7px 12px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer' }}>{t ? '週' : 'Week'}</button>
          <div style={{ width: 12 }} />
          <button style={{ background: '#FFE003', color: '#141414', border: 'none', padding: '7px 14px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
            <TLIcon name="plus" size={12} /> {t ? '新增課堂' : 'New lesson'}
          </button>
        </div>
      </div>

      <ACard>
        {/* Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: `120px repeat(${TL_GRID_HOURS.length}, 1fr)`, fontFamily: TL_FONTS.sans, fontSize: 11 }}>
          {/* Header row */}
          <div style={{ background: '#F8F8F8', padding: '10px 14px', borderBottom: '1px solid rgba(20,20,20,0.08)', borderRight: '1px solid rgba(20,20,20,0.06)', fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#6B6B6B' }}>
            {t ? '琴室' : 'Studio'}
          </div>
          {TL_GRID_HOURS.map((h, i) => (
            <div key={i} style={{ background: '#F8F8F8', padding: '10px 8px', borderBottom: '1px solid rgba(20,20,20,0.08)', borderRight: '1px solid rgba(20,20,20,0.04)', fontFamily: TL_FONTS.mono, fontSize: 10, color: '#333', textAlign: 'center' }}>
              {h}
            </div>
          ))}

          {TL_GRID_ROOMS.map((room, ri) => (
            <React.Fragment key={ri}>
              <div style={{ padding: '10px 14px', borderBottom: '1px solid rgba(20,20,20,0.05)', borderRight: '1px solid rgba(20,20,20,0.06)', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                <div style={{ fontFamily: TL_FONTS.serif, fontSize: 13, fontWeight: 500 }}>{room.name}</div>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 2 }}>{room.type}</div>
              </div>
              {room.slots.map((s, si) => {
                const kind = tlGridCellKind(s);
                const isSophie = s.includes('Sophie');
                const isMsChen = s.includes('Chen');
                const highlight = isSophie || isMsChen;
                let bg = '#FFFFFF', ink = '#141414', border = '1px solid rgba(20,20,20,0.05)';
                if (kind === 'ok')    { bg = highlight ? '#FFE003' : '#141414'; ink = highlight ? '#141414' : '#F8F8F8'; }
                if (kind === 'group') { bg = '#262626'; ink = '#FFE003'; }
                if (kind === 'trial') { bg = '#FFFFFF'; ink = '#141414'; border = '2px dashed #FFE003'; }
                return (
                  <div key={si} style={{
                    padding: '8px 8px', borderBottom: '1px solid rgba(20,20,20,0.05)', borderRight: '1px solid rgba(20,20,20,0.04)',
                    background: bg, color: ink, minHeight: 50,
                    border: kind === 'trial' ? border : undefined,
                    display: 'flex', alignItems: 'center',
                    fontSize: 10, lineHeight: 1.3,
                  }}>
                    {s ? (
                      <span style={{ fontFamily: kind === 'trial' ? TL_FONTS.sans : TL_FONTS.sans, fontWeight: 500 }}>{s}</span>
                    ) : null}
                  </div>
                );
              })}
            </React.Fragment>
          ))}
        </div>

        {/* legend */}
        <div style={{ display: 'flex', gap: 18, padding: '14px 20px', fontFamily: TL_FONTS.mono, fontSize: 9, color: '#6B6B6B', letterSpacing: '0.06em', textTransform: 'uppercase', borderTop: '1px solid rgba(20,20,20,0.06)' }}>
          <Legend color="#141414" label={t ? '已預約' : 'Booked'} />
          <Legend color="#FFE003" label={t ? '已建立流程的課堂 (Sophie / Ms. Chen)' : 'Connected to handbook (Sophie / Ms. Chen)'} />
          <Legend color="#262626" label={t ? '小組課' : 'Group class'} />
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, border: '2px dashed #FFE003' }} />{t ? '試堂' : 'Trial'}</span>
        </div>
      </ACard>
    </div>
  );
}

// ═══ STUDENTS ══════════════════════════════════════════════════

function AStudents({ branchId, lang, onOpenStudent }) {
  const t = lang === 'zh';
  const [selected, setSelected] = m2UseState('s1');
  // Clicking a row now opens the full student detail page.
  const openStudent = (id) => { setSelected(id); if (onOpenStudent) onOpenStudent(id); };

  const rows = [
    { id: 's1', name: 'Sophie Lam',     parent: 'Mrs. Lam',    age: 9,  inst: 'Piano',  level: 'Grade 3', stage: 'Enrolled · Y2', tenure: '1y 4m', attend: 1.00, fees: 'Paid', tag: 'recital' },
    { id: 's2', name: 'Marcus Wong',    parent: 'Mr. Wong',    age: 12, inst: 'Violin', level: 'Grade 5', stage: 'Exam prep',     tenure: '4y 2m', attend: 0.95, fees: 'Paid', tag: 'exam' },
    { id: 's3', name: 'Emily Cheung',   parent: 'Mrs. Cheung', age: 7,  inst: 'Piano',  level: 'Grade 1', stage: 'Enrolled · Y1', tenure: '8m',    attend: 0.92, fees: 'Paid' },
    { id: 's4', name: 'Daniel Ip',      parent: 'Mrs. Ip',     age: 14, inst: 'Guitar', level: 'Grade 6', stage: 'Enrolled · Y2', tenure: '3y 1m', attend: 0.88, fees: 'Due',  tag: 'fees' },
    { id: 's5', name: 'Chloe Tang',     parent: 'Mr. Tang',    age: 10, inst: 'Cello',  level: 'Grade 4', stage: 'Enrolled · Y2', tenure: '2y 6m', attend: 0.97, fees: 'Paid' },
    { id: 's6', name: 'Aiden Ho',       parent: 'Mrs. Ho',     age: 11, inst: 'Saxophone', level: 'Grade 3', stage: 'Enrolled · Y1', tenure: '11m',   attend: 0.85, fees: 'Paid' },
    { id: 's7', name: 'Isabella Mak',   parent: 'Mr. Mak',     age: 8,  inst: 'Flute',  level: 'Grade 2', stage: 'Enrolled · Y1', tenure: '7m',    attend: 0.90, fees: 'Paid' },
    { id: 'st', name: 'Felix Chow',     parent: 'Mrs. Chow',   age: 6,  inst: 'Piano',  level: 'Trial',   stage: 'Trial',         tenure: '—',     attend: 1.00, fees: '—' },
  ];

  const sel = rows.find(r => r.id === selected);

  return (
    <div style={{ padding: '24px 28px', overflow: 'auto', height: '100%' }} className="tl-noscroll">
      <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 ? '學生 · 524 人' : 'Students · 524 enrolled'}
          </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></> : <>From trial to <em style={{ fontStyle: 'italic' }}>graduation.</em></>}
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input placeholder={t ? '搜尋學生 / 家長…' : 'Search students / parents…'} style={{
            width: 240, padding: '8px 12px', border: '1px solid rgba(20,20,20,0.15)',
            background: '#FFF', fontFamily: TL_FONTS.sans, fontSize: 12, outline: 'none',
          }}/>
          <button style={{ background: '#FFE003', color: '#141414', border: 'none', padding: '8px 14px', fontFamily: TL_FONTS.sans, fontSize: 11, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
            <TLIcon name="plus" size={12} /> {t ? '新增學生' : 'Add student'}
          </button>
        </div>
      </div>

      <ACard>
          <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 0.8fr 1.2fr 0.8fr 0.7fr 60px', padding: '10px 16px', background: '#F8F8F8', fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#6B6B6B', borderBottom: '1px solid rgba(20,20,20,0.08)' }}>
            <span>{t ? '學生' : 'Student'}</span>
            <span>{t ? '科目' : 'Subject'}</span>
            <span>{t ? '年資' : 'Tenure'}</span>
            <span>{t ? '生命週期' : 'Lifecycle'}</span>
            <span>{t ? '出席' : 'Attend.'}</span>
            <span>{t ? '學費' : 'Fees'}</span>
            <span></span>
          </div>
          {rows.map(r => {
            const active = r.id === selected;
            return (
              <button key={r.id} onClick={() => openStudent(r.id)} style={{
                display: 'grid', gridTemplateColumns: '1.6fr 1fr 0.8fr 1.2fr 0.8fr 0.7fr 60px',
                width: '100%', padding: '12px 16px', alignItems: 'center', textAlign: 'left',
                background: active ? 'rgba(255,224,3,0.16)' : 'transparent',
                border: 'none', borderBottom: '1px solid rgba(20,20,20,0.05)',
                cursor: 'pointer', fontFamily: TL_FONTS.sans, fontSize: 12, color: '#141414',
              }}>
                <span>
                  <div style={{ fontWeight: 500 }}>{r.name}{r.tag === 'recital' && <span style={{ marginLeft: 8, padding: '1px 6px', background: '#141414', color: '#FFE003', fontFamily: TL_FONTS.mono, fontSize: 8, letterSpacing: '0.1em' }}>RECITAL</span>}{r.tag === 'exam' && <span style={{ marginLeft: 8, padding: '1px 6px', background: '#141414', color: '#FFE003', fontFamily: TL_FONTS.mono, fontSize: 8, letterSpacing: '0.1em' }}>EXAM</span>}{r.tag === 'fees' && <span style={{ marginLeft: 8, padding: '1px 6px', background: '#B14B4B', color: '#F8F8F8', fontFamily: TL_FONTS.mono, fontSize: 8, letterSpacing: '0.1em' }}>FEES DUE</span>}</div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2 }}>{r.parent} · age {r.age}</div>
                </span>
                <span>
                  <div>{r.inst}</div>
                  <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2 }}>{r.level}</div>
                </span>
                <span style={{ fontFamily: TL_FONTS.mono, fontSize: 11 }}>{r.tenure}</span>
                <span style={{ fontSize: 11 }}>{r.stage}</span>
                <span style={{ fontFamily: TL_FONTS.mono, fontSize: 11, color: r.attend < 0.9 ? '#B14B4B' : '#141414' }}>{aFmtPct(r.attend)}</span>
                <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: r.fees === 'Due' ? '#B14B4B' : r.fees === '—' ? '#A0A0A0' : '#1F7A37' }}>{r.fees}</span>
                <span style={{ textAlign: 'right', fontFamily: TL_FONTS.mono, fontSize: 10, color: '#A0A0A0', letterSpacing: '0.08em' }}>OPEN →</span>
              </button>
            );
          })}
        </ACard>
    </div>
  );
}

function DStat({ label, val, sub }) {
  return (
    <div style={{ background: '#F8F8F8', padding: '10px 12px' }}>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 8, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#6B6B6B' }}>{label}</div>
      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 20, fontWeight: 500, marginTop: 4, letterSpacing: '-0.01em' }}>{val}</div>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2 }}>{sub}</div>
    </div>
  );
}
function ConnLink({ icon, title, sub }) {
  return (
    <div style={{ display: 'flex', gap: 12, padding: '10px 0', borderTop: '1px solid rgba(20,20,20,0.06)', alignItems: 'center' }}>
      <div style={{ width: 28, height: 28, background: '#141414', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <TLIcon name={icon} size={13} color="#FFE003" />
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12, fontWeight: 500 }}>{title}</div>
        <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2, letterSpacing: '0.04em' }}>{sub}</div>
      </div>
      <TLIcon name="chevR" size={14} color="#A0A0A0" />
    </div>
  );
}

// ═══ CRM / LEADS ═══════════════════════════════════════════════

function ACRM({ branchId, lang }) {
  const t = lang === 'zh';
  const STATUS_COLOR = {
    'New':           '#FFE003',
    'Trial booked':  '#141414',
    'Trial done':    '#141414',
    'Following up':  '#A0A0A0',
    'Enrolled':      '#1F7A37',
  };

  return (
    <div style={{ padding: '24px 28px', overflow: 'auto', height: '100%' }} className="tl-noscroll">
      <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 ? '招生與 CRM · 過去 30 日' : 'Leads & CRM · last 30 days'}
          </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></> : <>Every enquiry, <em style={{ fontStyle: 'italic' }}>followed up.</em></>}
          </h1>
        </div>
        <div style={{ display: 'flex', gap: 24, alignItems: 'flex-end' }}>
          <Stat n="412" label={t ? '查詢' : 'Enquiries'} />
          <Stat n="287" label={t ? '試堂預約' : 'Trials booked'} />
          <Stat n="118" label={t ? '入學' : 'Enrolled'} />
          <Stat n="26.5%" label={t ? '整體轉化' : 'Overall'} />
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 12 }}>
        <ACard>
          <ACardHeader title={t ? '需要跟進' : 'Needs follow-up'} sub={`${TL_LEADS.length} ${t ? '個個案' : 'leads'}`} action={
            <button style={{ background: '#141414', color: '#F8F8F8', border: 'none', padding: '6px 12px', fontFamily: TL_FONTS.sans, fontSize: 10, cursor: 'pointer' }}>
              {t ? '匯出' : 'Export'}
            </button>
          } />
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 0.9fr 0.7fr 0.7fr 32px', padding: '10px 16px', background: '#F8F8F8', fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#6B6B6B', borderBottom: '1px solid rgba(20,20,20,0.08)' }}>
            <span>{t ? '家庭' : 'Family'}</span>
            <span>{t ? '興趣' : 'Interest'}</span>
            <span>{t ? '分行' : 'Branch'}</span>
            <span>{t ? '來源' : 'Source'}</span>
            <span>{t ? '狀態' : 'Status'}</span>
            <span>{t ? '跟進' : 'Owner'}</span>
            <span></span>
          </div>
          {TL_LEADS.map(l => (
            <div key={l.id} style={{
              display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 0.9fr 0.7fr 0.7fr 32px',
              padding: '12px 16px', alignItems: 'center',
              borderBottom: '1px solid rgba(20,20,20,0.05)', fontFamily: TL_FONTS.sans, fontSize: 12,
            }}>
              <span>
                <div style={{ fontWeight: 500 }}>{l.name}</div>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2 }}>{l.child}</div>
              </span>
              <span>{l.interest}</span>
              <span style={{ fontSize: 11 }}>{l.branch}</span>
              <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: '#6B6B6B' }}>{l.source}</span>
              <span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: STATUS_COLOR[l.status] }} />
                  <span style={{ fontSize: 10 }}>{l.status}</span>
                </span>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: '#A0A0A0', marginTop: 2 }}>{l.when}</div>
              </span>
              <span style={{ fontSize: 11 }}>{l.owner}</span>
              <span><TLIcon name="chevR" size={14} color="#A0A0A0" /></span>
            </div>
          ))}
        </ACard>

        {/* funnel + sources */}
        <div>
          <ACard>
            <ACardHeader title={t ? '轉化漏斗' : 'Conversion funnel'} sub={t ? '過去 30 日' : 'last 30 days'} />
            <div style={{ padding: '14px 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>
          </ACard>
          <div style={{ height: 12 }} />
          <ACard>
            <ACardHeader title={t ? '查詢來源' : 'Source mix'} sub={t ? '本月' : 'this month'} />
            <div style={{ padding: '14px 20px 18px' }}>
              {[
                { name: 'Website',   n: 168 },
                { name: 'Referral',  n: 112 },
                { name: 'Walk-in',   n: 64  },
                { name: 'Instagram', n: 41  },
                { name: 'Facebook',  n: 27  },
              ].map((s, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '90px 1fr 36px', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <span style={{ fontFamily: TL_FONTS.sans, fontSize: 11 }}>{s.name}</span>
                  <div style={{ height: 6, background: 'rgba(20,20,20,0.06)' }}>
                    <div style={{ height: '100%', width: `${(s.n / 168) * 100}%`, background: '#141414' }} />
                  </div>
                  <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, textAlign: 'right' }}>{s.n}</span>
                </div>
              ))}
            </div>
          </ACard>
        </div>
      </div>
    </div>
  );
}

window.AToday = AToday;
window.ASchedule = ASchedule;
window.AStudents = AStudents;
window.ACRM = ACRM;
