// ParentView — student progress portal (mobile).
// Single scrollable screen with: hero, this week, upcoming, latest handbook,
// skill chart, repertoire, practice streak, teacher messages.

const { useState: pvUseState } = React;

function PVHeader({ c, student, streak, onLangToggle }) {
  return (
    <div style={{ padding: '8px 24px 22px', background: c.bg }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <TLLogo height={56} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {onLangToggle && (
            <button onClick={onLangToggle} style={{
              background: 'transparent', border: `1px solid ${c.line}`,
              padding: '6px 10px', cursor: 'pointer',
              fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.08em', color: c.ink2,
            }}>{t('lang.toggle')}</button>
          )}
          <div style={{
            padding: '4px 8px', background: c.accent, color: c.accentInk,
            fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600,
          }}>{t('role.parent')}</div>
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <TLLabel color={c.ink3}>{t('parent.heroSub', { name: tlLang() === 'zh' ? '林芷晴' : 'Sophie' })}</TLLabel>
          <h1 style={{
            fontFamily: TL_FONTS.serif, fontSize: 34, fontWeight: 500,
            lineHeight: 1, margin: '6px 0 0', letterSpacing: '-0.02em', color: c.ink,
          }}>{tlLang() === 'zh'
            ? <>春季學期 · <em style={{ fontStyle: 'italic' }}>第 12 週</em></>
            : <>Spring term, <em style={{ fontStyle: 'italic' }}>week 12</em></>}</h1>
        </div>
        <div style={{
          width: 40, height: 40, background: '#E8DCC8', color: '#141414',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: TL_FONTS.serif, fontSize: 16, fontWeight: 500,
        }}>SL</div>
      </div>

      {/* hero metrics row */}
      <div style={{
        marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
        border: `1px solid ${c.line}`, background: c.surface,
      }}>
        <Metric c={c} value="14" label={t('parent.metric.lessons')} sub={t('parent.metric.lessonsSub')} />
        <Metric c={c} value={streak + ''} label={t('parent.metric.streak')} sub={t('parent.metric.streakSub')} border accent />
        <Metric c={c} value="3.6" label={t('parent.metric.overall')} sub={t('parent.metric.overallSub')} />
      </div>
    </div>
  );
}

function Metric({ c, value, label, sub, border, accent }) {
  return (
    <div style={{
      padding: '16px 14px',
      background: accent ? c.accent : 'transparent',
      borderLeft: border ? `1px solid ${c.line}` : 'none',
      borderRight: border ? `1px solid ${c.line}` : 'none',
    }}>
      <div style={{ fontFamily: TL_FONTS.serif, fontSize: 28, fontWeight: 500, lineHeight: 1, color: accent ? c.accentInk : c.ink, letterSpacing: '-0.02em' }}>{value}</div>
      <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: accent ? 'rgba(20,20,20,0.7)' : c.ink3, marginTop: 6 }}>{label}</div>
      <div style={{ fontFamily: TL_FONTS.sans, fontSize: 11, color: accent ? 'rgba(20,20,20,0.85)' : c.ink2, marginTop: 4 }}>{sub}</div>
    </div>
  );
}

function PVSection({ c, num, title, action, children }) {
  return (
    <div style={{ padding: '28px 24px 4px', borderTop: `1px solid ${c.line}` }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: c.muted, letterSpacing: '0.1em' }}>{num}</span>
          <h3 style={{ fontFamily: TL_FONTS.serif, fontSize: 20, fontWeight: 500, margin: 0, color: c.ink, letterSpacing: '-0.01em' }}>{title}</h3>
        </div>
        {action && <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3, letterSpacing: '0.1em', textTransform: 'uppercase' }}>{action}</span>}
      </div>
      {children}
    </div>
  );
}

function PVPractice({ c }) {
  const days = TL_PRACTICE_S1;
  const max = 60;
  const dayLabels = ['M','T','W','T','F','S','S'];
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 90, marginBottom: 8 }}>
        {days.map((m, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center', gap: 4 }}>
            <div style={{
              width: '100%', height: `${(m / max) * 100}%`,
              background: m === 0 ? 'transparent' : (i >= 7 ? c.ink : c.ink3),
              border: m === 0 ? `1px dashed ${c.line}` : 'none',
              minHeight: m === 0 ? 4 : 4,
            }} />
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 4 }}>
        {days.map((_, i) => (
          <div key={i} style={{ flex: 1, textAlign: 'center', fontFamily: TL_FONTS.mono, fontSize: 9, color: c.ink3, letterSpacing: '0.06em' }}>
            {dayLabels[i % 7]}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14, paddingTop: 12, borderTop: `1px solid ${c.line2}` }}>
        <div>
          <TLLabel color={c.ink3}>{t('parent.weekly')}</TLLabel>
          <div style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, marginTop: 2, color: c.ink }}>3h 50m</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <TLLabel color={c.ink3}>{t('parent.goal')}</TLLabel>
          <div style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, marginTop: 2, color: c.ink }}>3h 30m <span style={{ color: c.success, fontSize: 14 }}>✓</span></div>
        </div>
      </div>
    </div>
  );
}

function PVChart({ c }) {
  // 4 dimensions over 4 months — small line chart in SVG
  const data = TL_SKILLS_S1;
  const dims = [
    { key: 'technique',  label: 'Technique',   color: c.ink },
    { key: 'musicality', label: 'Musicality',  color: c.accent },
    { key: 'sight',      label: 'Sight-read',  color: c.ink3 },
    { key: 'theory',     label: 'Theory',      color: c.ink2 },
  ];
  const W = 320, H = 130, P = { l: 28, r: 8, t: 12, b: 22 };
  const xStep = (W - P.l - P.r) / (data.length - 1);
  const y = v => P.t + ((5 - v) / (5 - 2)) * (H - P.t - P.b);

  return (
    <div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', overflow: 'visible' }}>
        {/* gridlines */}
        {[2,3,4,5].map(v => (
          <g key={v}>
            <line x1={P.l} y1={y(v)} x2={W - P.r} y2={y(v)} stroke={c.line2} strokeWidth="0.5" />
            <text x={P.l - 6} y={y(v) + 3} textAnchor="end" fontSize="8" fontFamily={TL_FONTS.mono} fill={c.muted}>{v}</text>
          </g>
        ))}
        {/* lines */}
        {dims.map(dim => {
          const pts = data.map((d, i) => `${P.l + i * xStep},${y(d[dim.key])}`).join(' ');
          return <polyline key={dim.key} points={pts} fill="none" stroke={dim.color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />;
        })}
        {/* dots last */}
        {dims.map(dim => (
          <circle key={dim.key} cx={P.l + (data.length - 1) * xStep} cy={y(data[data.length - 1][dim.key])} r="3" fill={dim.color} />
        ))}
        {/* x labels */}
        {data.map((d, i) => (
          <text key={i} x={P.l + i * xStep} y={H - 6} textAnchor="middle" fontSize="9" fontFamily={TL_FONTS.mono} fill={c.ink3} letterSpacing="0.05em">{d.date.toUpperCase()}</text>
        ))}
      </svg>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 12 }}>
        {dims.map(dim => (
          <div key={dim.key} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 10, height: 2, background: dim.color }} />
            <span style={{ fontFamily: TL_FONTS.sans, fontSize: 12, color: c.ink2 }}>{dim.label}</span>
            <span style={{ marginLeft: 'auto', fontFamily: TL_FONTS.mono, fontSize: 11, color: c.ink }}>{data[data.length - 1][dim.key]}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function PVUpcoming({ c }) {
  return (
    <div>
      {TL_UPCOMING_S1.map((u, i) => {
        const isToday = u.status === 'today';
        return (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 16,
            padding: '14px 0',
            borderBottom: i === TL_UPCOMING_S1.length - 1 ? 'none' : `1px solid ${c.line2}`,
          }}>
            <div style={{
              width: 56, padding: '8px 0',
              background: isToday ? c.ink : 'transparent',
              color: isToday ? c.bg : c.ink,
              border: isToday ? 'none' : `1px solid ${c.line}`,
              textAlign: 'center', flexShrink: 0,
            }}>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em' }}>{u.date.split(' · ')[0].toUpperCase()}</div>
              <div style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, lineHeight: 1, marginTop: 2 }}>{u.date.split('Apr ')[1] || u.date.split('May ')[1]}</div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: TL_FONTS.sans, fontSize: 15, color: c.ink, fontWeight: 500 }}>{u.time} · {u.teacher}</div>
              <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12, color: c.ink3, marginTop: 2 }}>{u.room} · 45 min</div>
            </div>
            {isToday && <span style={{
              fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em',
              padding: '4px 8px', background: c.accent, color: c.accentInk,
            }}>TODAY</span>}
          </div>
        );
      })}
    </div>
  );
}

function PVHandbook({ c }) {
  // Show last 3 entries as a vertical timeline
  const entries = TL_HANDBOOK_S1.slice(0, 3);
  return (
    <div>
      {entries.map((e, i) => (
        <div key={e.id} style={{
          display: 'flex', gap: 14, paddingBottom: i === entries.length - 1 ? 0 : 18,
          marginBottom: i === entries.length - 1 ? 0 : 18,
          borderBottom: i === entries.length - 1 ? 'none' : `1px solid ${c.line2}`,
        }}>
          <div style={{ width: 56, flexShrink: 0 }}>
            <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em', color: c.ink3 }}>
              {e.dateLabel.split(', ')[1].toUpperCase()}
            </div>
            <div style={{ fontFamily: TL_FONTS.serif, fontSize: 18, fontWeight: 500, lineHeight: 1, marginTop: 2, color: c.ink }}>
              {e.dateLabel.split(' ')[0]}
            </div>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            {!e.attended ? (
              <div style={{
                fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink3,
                padding: '8px 12px', background: c.surface2,
                fontStyle: 'italic',
              }}>Absent — sick leave.</div>
            ) : (
              <>
                <div style={{ fontFamily: TL_FONTS.serif, fontSize: 14, fontStyle: 'italic', color: c.ink, lineHeight: 1.5, marginBottom: 8 }}>
                  "{e.remark}"
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 8 }}>
                  {e.pieces.map((p, j) => (
                    <span key={j} style={{
                      fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.06em',
                      padding: '3px 6px', background: c.surface2, color: c.ink2,
                      textTransform: 'uppercase', border: `1px solid ${c.line2}`,
                    }}>{p.name.split(' — ')[1] || p.name.split(' — ')[0]}</span>
                  ))}
                </div>
                <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12, color: c.ink3, lineHeight: 1.45 }}>
                  <strong style={{ color: c.ink2, fontWeight: 500 }}>Homework · </strong>{e.homework}
                </div>
              </>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

function PVRepertoire({ c }) {
  return (
    <div>
      {TL_REPERTOIRE_S1.slice(0, 5).map((r, i) => (
        <div key={i} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '10px 0',
          borderBottom: i === 4 ? 'none' : `1px solid ${c.line2}`,
        }}>
          <span style={{
            width: 6, height: 6,
            background: r.status === 'Completed' ? c.ink : 'transparent',
            border: r.status === 'Completed' ? 'none' : `1px solid ${c.ink}`,
            flexShrink: 0,
          }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink, lineHeight: 1.3 }}>{r.piece}</div>
          </div>
          <div style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.08em', textTransform: 'uppercase', color: c.ink3 }}>
            {r.started}
          </div>
        </div>
      ))}
    </div>
  );
}

function PVMessages({ c }) {
  return (
    <div>
      <div style={{ display: 'flex', gap: 12, padding: '14px 16px', background: c.surface, border: `1px solid ${c.line}`, marginBottom: 8 }}>
        <div style={{ width: 36, height: 36, background: '#D4C4B0', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: TL_FONTS.serif, fontWeight: 500 }}>CW</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 2 }}>
            <span style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink, fontWeight: 500 }}>Ms. Chen</span>
            <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: c.ink3, letterSpacing: '0.08em' }}>2D AGO</span>
          </div>
          <div style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink2, lineHeight: 1.4 }}>
            Just a heads up — the spring recital sign-up opens Friday. Sophie's Arabesque is shaping up beautifully…
          </div>
        </div>
      </div>
      <button style={{
        width: '100%', padding: '12px', background: 'transparent',
        border: `1px solid ${c.line}`, color: c.ink2, cursor: 'pointer',
        fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      }}>
        <TLIcon name="reply" size={12} color={c.ink2} /> Reply to Ms. Chen
      </button>
    </div>
  );
}

function PVTabBar({ c, active }) {
  const tabs = [
    { id: 'home', icon: 'home', label: t('parent.tab.home') },
    { id: 'cal',  icon: 'cal',  label: t('parent.tab.lessons') },
    { id: 'book', icon: 'book', label: t('parent.tab.handbook') },
    { id: 'msg',  icon: 'msg',  label: t('parent.tab.messages') },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      background: c.bg, borderTop: `1px solid ${c.line}`,
      display: 'flex', padding: '8px 0 28px',
    }}>
      {tabs.map(t => (
        <div key={t.id} style={{
          flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
          color: t.id === active ? c.ink : c.muted,
        }}>
          <TLIcon name={t.icon} size={18} color={t.id === active ? c.ink : c.muted} />
          <span style={{ fontFamily: TL_FONTS.mono, fontSize: 8, letterSpacing: '0.1em', textTransform: 'uppercase' }}>{t.label}</span>
        </div>
      ))}
    </div>
  );
}

function ParentView({ dark, onLangChange }) {
  const c = TL_TOKENS[dark ? 'dark' : 'light'];
  const student = TL_STUDENTS[0];
  const [, force] = pvUseState(0);
  const toggleLang = () => {
    window.__tlLang = (window.__tlLang === 'zh' ? 'en' : 'zh');
    if (onLangChange) onLangChange(window.__tlLang);
    force(x => x + 1);
  };

  return (
    <div style={{ height: '100%', position: 'relative', background: c.bg, overflow: 'hidden' }}>
      <div className="tl-noscroll" style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', WebkitOverflowScrolling: 'touch', paddingBottom: 90, color: c.ink }}>
        <PVHeader c={c} student={student} streak={11} onLangToggle={toggleLang} />

        <PVSection c={c} num="01" title={t('parent.upcoming')}>
          <PVUpcoming c={c} />
        </PVSection>

        <PVSection c={c} num="02" title={t('parent.latest')} action={t('parent.viewAll')}>
          <PVHandbook c={c} />
        </PVSection>

        <PVSection c={c} num="03" title={t('parent.skill')} action={t('parent.last4')}>
          <PVChart c={c} />
        </PVSection>

        <PVSection c={c} num="04" title={t('parent.practice')}>
          <PVPractice c={c} />
        </PVSection>

        <PVSection c={c} num="05" title={t('parent.repertoire')} action={t('parent.npieces', { n: 6 })}>
          <PVRepertoire c={c} />
        </PVSection>

        <PVSection c={c} num="06" title={t('parent.messages')}>
          <PVMessages c={c} />
        </PVSection>

        <div style={{ padding: '40px 24px 60px', textAlign: 'center' }}>
          <TLLabel color={c.muted}>{t('parent.foot')}</TLLabel>
        </div>
      </div>
      <PVTabBar c={c} active="home" />
    </div>
  );
}

Object.assign(window, { ParentView });
