// Mine Safe Academy — mobile app screens (inside the iOS frame).
(function () {
  const NS = window.MineSafeGlobalDesignSystem_760fd2;
  const { Icon, Button, Badge, StatusChip, ProgressBar, ProgressRing, QuizOption, Alert, Avatar, ThemeToggle, LanguageSelect } = NS;

  const YELLOW = 'var(--brand-yellow)', INK = 'var(--brand-ink)';

  function TopBar({ title, onBack, right }) {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '6px 16px 12px',
        background: 'var(--surface-card)', borderBottom: '1px solid var(--border-subtle)',
      }}>
        {onBack
          ? <button onClick={onBack} aria-label="Back" style={{ border: 'none', background: 'none', padding: 0, cursor: 'pointer', color: 'var(--text-strong)', display: 'flex' }}><Icon name="chevron-left" size={26} /></button>
          : <img src="../../assets/minesafe-logo.png" alt="Mine Safe" style={{ height: 26 }} />}
        <div style={{ flex: 1, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--text-strong)', textAlign: onBack ? 'center' : 'left' }}>{title}</div>
        {right || <div style={{ width: 26 }} />}
      </div>
    );
  }

  function BottomNav({ tab, onTab }) {
    const items = [['home', 'home', 'Home'], ['courses', 'graduation-cap', 'Courses'], ['downloads', 'download', 'Offline'], ['profile', 'user', 'Profile']];
    return (
      <div style={{
        display: 'flex', borderTop: '1px solid var(--border-subtle)', background: 'var(--surface-card)',
        padding: '8px 6px 6px',
      }}>
        {items.map(([id, icon, label]) => (
          <button key={id} onClick={() => onTab(id)} style={{
            flex: 1, border: 'none', background: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            color: tab === id ? 'var(--brand-yellow-press)' : 'var(--text-faint)',
          }}>
            <Icon name={icon} size={22} />
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 10.5, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</span>
          </button>
        ))}
      </div>
    );
  }

  function Screen({ children, pad = true }) {
    return <div style={{ flex: 1, overflowY: 'auto', background: 'var(--surface-page)', padding: pad ? 16 : 0 }}>{children}</div>;
  }

  // Compact mobile course row
  function CourseRow({ c, onClick }) {
    return (
      <button onClick={onClick} style={{
        display: 'flex', gap: 12, width: '100%', textAlign: 'left', alignItems: 'center',
        background: 'var(--surface-card)', border: '1px solid var(--border-subtle)',
        borderRadius: 'var(--radius-lg)', padding: 12, cursor: 'pointer',
      }}>
        <div style={{
          width: 52, height: 52, flex: '0 0 auto', borderRadius: 'var(--radius-md)', overflow: 'hidden',
          background: c.cover ? `center/cover no-repeat url("${c.cover}")` : INK,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{!c.cover && <Icon name="graduation-cap" size={24} color={YELLOW} />}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--brand-yellow-press)', fontFamily: 'var(--font-display)' }}>{c.level}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15.5, color: 'var(--text-strong)', lineHeight: 1.2, margin: '2px 0 6px' }}>{c.title}</div>
          {c.status === 'completed'
            ? <StatusChip status="completed" />
            : c.progress > 0
              ? <ProgressBar value={c.progress} size="sm" />
              : <span style={{ fontSize: 12, color: 'var(--text-muted)', display: 'inline-flex', gap: 5, alignItems: 'center' }}><Icon name="layers" size={13} />{c.lessons} lessons · {c.duration}</span>}
        </div>
        <Icon name="chevron-right" size={18} color="var(--text-faint)" />
      </button>
    );
  }

  function Home({ d, onOpen, onTab }) {
    const cont = d.courses.find(c => c.id === 'level9');
    return (
      <>
        <TopBar title="Academy" right={<Avatar name={d.user.name} size="sm" />} />
        <Screen>
          <div style={{ marginBottom: 14 }}>
            <div className="ms-overline">Welcome back</div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)', lineHeight: 1.1, marginTop: 3 }}>Hi, {d.user.name.split(' ')[0]}.</div>
            <div style={{ fontSize: 13.5, color: 'var(--text-muted)', marginTop: 3 }}>2 modules due this week.</div>
          </div>

          {/* Continue card — dark */}
          <div style={{ position: 'relative', overflow: 'hidden', background: INK, borderRadius: 'var(--radius-lg)', padding: 18, marginBottom: 20 }}>
            <div style={{ position: 'absolute', inset: 0, opacity: 0.06, background: 'repeating-linear-gradient(135deg,#fff,#fff 2px,transparent 2px,transparent 14px)' }} />
            <div style={{ position: 'relative', display: 'flex', gap: 14, alignItems: 'center' }}>
              <ProgressRing value={cont.progress} size={64} thickness={7} label={<span style={{ color: '#fff', fontSize: 15 }}>{cont.progress}%</span>} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: YELLOW, fontFamily: 'var(--font-display)' }}>Continue</div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, color: '#fff', lineHeight: 1.15, margin: '2px 0' }}>{cont.title}</div>
                <div style={{ fontSize: 12.5, color: 'var(--grey-300)' }}>Module 4 · Operator responsibilities</div>
              </div>
            </div>
            <div style={{ position: 'relative', marginTop: 14 }}>
              <Button variant="primary" fullWidth iconLeft="play" onClick={() => onOpen(cont.id)}>Resume</Button>
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
            <h3 style={{ fontSize: 17 }}>My courses</h3>
            <button onClick={() => onTab('courses')} style={{ border: 'none', background: 'none', color: 'var(--brand-yellow-press)', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 12.5, textTransform: 'uppercase', letterSpacing: '0.04em', cursor: 'pointer', whiteSpace: 'nowrap', flex: '0 0 auto' }}>See all</button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {d.courses.slice(0, 4).map(c => <CourseRow key={c.id} c={c} onClick={() => onOpen(c.id)} />)}
          </div>
        </Screen>
      </>
    );
  }

  function Courses({ d, onOpen }) {
    return (
      <>
        <TopBar title="Courses" />
        <Screen>
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', marginBottom: 14, paddingBottom: 2 }}>
            {['All', 'Core Collision', 'Pedestrian', 'Monitoring', 'Underground'].map((f, i) => (
              <span key={f} style={{
                padding: '6px 13px', borderRadius: 999, whiteSpace: 'nowrap', fontSize: 12.5, fontWeight: 600,
                fontFamily: 'var(--font-display)', textTransform: 'uppercase', letterSpacing: '0.04em',
                background: i === 0 ? INK : 'var(--surface-card)', color: i === 0 ? '#fff' : 'var(--text-body)',
                border: `1px solid ${i === 0 ? INK : 'var(--border-default)'}`,
              }}>{f}</span>
            ))}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {d.courses.map(c => <CourseRow key={c.id} c={c} onClick={() => onOpen(c.id)} />)}
          </div>
        </Screen>
      </>
    );
  }

  function Course({ c, onBack, onLesson, onQuiz }) {
    return (
      <>
        <TopBar title="Course" onBack={onBack} />
        <Screen pad={false}>
          <div style={{ position: 'relative', overflow: 'hidden', background: INK, padding: 20, color: '#fff' }}>
            {c.cover && <div style={{ position: 'absolute', inset: 0, background: `center/cover no-repeat url("${c.cover}")`, opacity: 0.4 }} />}
            {c.cover && <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(26,26,26,0.5),rgba(26,26,26,0.92))' }} />}
            <div style={{ position: 'absolute', inset: 0, opacity: 0.06, background: 'repeating-linear-gradient(135deg,#fff,#fff 2px,transparent 2px,transparent 14px)' }} />
            <div style={{ position: 'relative' }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: YELLOW, fontFamily: 'var(--font-display)' }}>{c.category} · {c.level}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 23, lineHeight: 1.1, margin: '6px 0 12px' }}>{c.title}</div>
              <div style={{ display: 'flex', gap: 16, fontSize: 13, color: 'var(--grey-300)', marginBottom: 14 }}>
                <span style={{ display: 'inline-flex', gap: 5, alignItems: 'center' }}><Icon name="layers" size={15} color={YELLOW} />{c.lessons} modules</span>
                <span style={{ display: 'inline-flex', gap: 5, alignItems: 'center' }}><Icon name="clock" size={15} color={YELLOW} />{c.duration}</span>
              </div>
              <ProgressBar value={c.progress} tone="brand" size="sm" />
            </div>
          </div>
          <div style={{ padding: 16 }}>
            <h3 style={{ fontSize: 16, marginBottom: 10 }}>Course content</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {(c.modules || []).map((m, i) => {
                const locked = m.status === 'locked';
                return (
                  <button key={i} disabled={locked} onClick={() => (m.type === 'quiz' ? onQuiz() : onLesson())} style={{
                    display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left',
                    background: 'var(--surface-card)', border: '1px solid var(--border-subtle)',
                    borderRadius: 'var(--radius-md)', padding: '11px 12px', cursor: locked ? 'not-allowed' : 'pointer', opacity: locked ? 0.55 : 1,
                  }}>
                    <span style={{ width: 28, height: 28, flex: '0 0 auto', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: m.status === 'completed' ? 'var(--safe)' : 'var(--grey-100)', color: m.status === 'completed' ? '#fff' : 'var(--text-muted)', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                      {m.status === 'completed' ? <Icon name="check" size={15} /> : locked ? <Icon name="lock" size={13} /> : i + 1}
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--text-strong)' }}>{m.title}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-muted)', display: 'flex', gap: 6, alignItems: 'center', marginTop: 1 }}><Icon name={m.type === 'quiz' ? 'clipboard-check' : m.type === 'reading' ? 'file-text' : m.type === 'tutorial' ? 'monitor-play' : 'video'} size={13} /><span style={{ textTransform: 'capitalize' }}>{m.type}</span> · {m.duration}</div>
                    </div>
                    {!locked && <Icon name="chevron-right" size={17} color="var(--text-faint)" />}
                  </button>
                );
              })}
            </div>
          </div>
        </Screen>
      </>
    );
  }

  function Lesson({ poster, src, onBack, onNext }) {
    const ref = React.useRef(null);
    const [playing, setPlaying] = React.useState(false);
    const [pct, setPct] = React.useState(0);
    const toggle = () => { const v = ref.current; if (!v) return; if (v.paused) { v.play(); setPlaying(true); } else { v.pause(); setPlaying(false); } };
    const onTime = () => { const v = ref.current; if (v && v.duration) setPct(v.currentTime / v.duration * 100); };
    return (
      <>
        <TopBar title="Lesson" onBack={onBack} right={<button aria-label="Save" style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-body)', display: 'flex' }}><Icon name="bookmark" size={22} /></button>} />
        <Screen pad={false}>
          <div style={{ position: 'relative', aspectRatio: '16/10', background: 'var(--brand-black)' }}>
            <video ref={ref} src={src} poster={poster} playsInline preload="metadata" onClick={toggle}
              onTimeUpdate={onTime} onEnded={() => setPlaying(false)}
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
            {!playing && <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(0,0,0,0.15),rgba(0,0,0,0.5))', pointerEvents: 'none' }} />}
            {!playing && <button onClick={toggle} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 60, height: 60, borderRadius: '50%', background: YELLOW, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-lg)' }}><Icon name="play" size={26} color={INK} /></button>}
            <div style={{ position: 'absolute', left: 12, right: 12, bottom: 10 }}>
              <div style={{ height: 3, background: 'rgba(255,255,255,0.25)', borderRadius: 999, overflow: 'hidden' }}><div style={{ width: `${pct}%`, height: '100%', background: YELLOW }} /></div>
            </div>
          </div>
          <div style={{ padding: 16 }}>
            <div className="ms-overline">Module 1 · Video</div>
            <h2 style={{ fontSize: 21, marginTop: 5 }}>What Level 9 intervention does</h2>
            <p style={{ fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-body)', marginTop: 10 }}>The Level 9 CxD scans continuously for pedestrians and machines. When a hazard enters the warning zone the operator is alerted; if no action is taken, the system applies a controlled automated stop.</p>
            <div style={{ marginTop: 16 }}>
              <Button variant="primary" fullWidth iconRight="arrow-right" onClick={onNext}>Next: Pre-start checklist</Button>
            </div>
          </div>
        </Screen>
      </>
    );
  }

  function Quiz({ onBack, onDone }) {
    const q = window.MSA_DATA.quiz;
    const [choice, setChoice] = React.useState(null);
    const [submitted, setSubmitted] = React.useState(false);
    const correct = choice === q.correct;
    const stateFor = (i) => !submitted ? (choice === i ? 'selected' : 'default') : (i === q.correct ? 'correct' : i === choice ? 'incorrect' : 'default');
    return (
      <>
        <TopBar title="Assessment" onBack={onBack} />
        <Screen>
          <div style={{ marginBottom: 12 }}>
            <div className="ms-overline">{q.context}</div>
            <div style={{ marginTop: 8 }}><ProgressBar value={30} size="sm" /></div>
          </div>
          <h2 style={{ fontSize: 20, lineHeight: 1.25, marginBottom: 14 }}>{q.q}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {q.options.map((opt, i) => <QuizOption key={i} index={i} state={stateFor(i)} selected={choice === i} onClick={() => !submitted && setChoice(i)}>{opt}</QuizOption>)}
          </div>
          {submitted && <div style={{ marginTop: 14 }}><Alert tone={correct ? 'safe' : 'danger'} title={correct ? 'Correct' : 'Not quite'}>{correct ? 'Level 9 applies a controlled automated stop.' : 'Level 9 applies a controlled automated stop when the operator does not respond.'}</Alert></div>}
          <div style={{ marginTop: 16 }}>
            {!submitted
              ? <Button variant="primary" fullWidth disabled={choice === null} onClick={() => setSubmitted(true)}>Submit answer</Button>
              : <Button variant="primary" fullWidth iconRight="arrow-right" onClick={onDone}>Next question</Button>}
          </div>
        </Screen>
      </>
    );
  }

  function Downloads({ d, onOpen }) {
    const offline = d.courses.filter(c => c.progress > 0 || c.status === 'completed');
    return (
      <>
        <TopBar title="Offline" />
        <Screen>
          <Alert tone="info" title="Learn without signal" style={{ marginBottom: 14 }}>Downloaded courses play underground and in low-connectivity areas. They sync when you reconnect.</Alert>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {offline.map(c => <CourseRow key={c.id} c={c} onClick={() => onOpen(c.id)} />)}
          </div>
        </Screen>
      </>
    );
  }

  function Profile({ d }) {
    const [lang, setLang] = React.useState(window.__msLang || 'en');
    const Row = ({ icon, label, right }) => (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 4px', borderBottom: '1px solid var(--border-subtle)' }}>
        <Icon name={icon} size={19} color="var(--text-muted)" />
        <span style={{ flex: 1, fontSize: 14.5, color: 'var(--text-strong)', fontWeight: 500 }}>{label}</span>
        {right}
      </div>
    );
    return (
      <>
        <TopBar title="Profile" />
        <Screen>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
            <Avatar name={d.user.name} size="lg" />
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--text-strong)' }}>{d.user.name}</div>
              <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>{d.user.role} · {d.user.site}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 10, marginBottom: 20 }}>
            <div style={{ flex: 1, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: 14, textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)' }}>{d.stats.completed}</div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Completed</div>
            </div>
            <div style={{ flex: 1, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: 14, textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)' }}>{d.stats.certs}</div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Certificates</div>
            </div>
          </div>
          <div className="ms-overline" style={{ marginBottom: 4 }}>Settings</div>
          <Row icon="globe" label="Language" right={<LanguageSelect value={lang} onChange={(c) => { setLang(c); window.__msLang = c; }} />} />
          <Row icon="sun-moon" label="Appearance" right={<ThemeToggle />} />
          <Row icon="bell" label="Notifications" right={<Icon name="chevron-right" size={18} color="var(--text-faint)" />} />
          <Row icon="circle-help" label="Help & support" right={<Icon name="chevron-right" size={18} color="var(--text-faint)" />} />
          <div style={{ marginTop: 20 }}><Button variant="outline" fullWidth iconLeft="log-out">Sign out</Button></div>
        </Screen>
      </>
    );
  }

  function MobileApp() {
    const d = window.MSA_DATA;
    const [tab, setTab] = React.useState('home');
    const [view, setView] = React.useState({ name: 'home' });
    const course = view.courseId ? d.courses.find(c => c.id === view.courseId) : d.courses[0];

    const go = (v) => setView(v);
    let body, showNav = true;
    if (view.name === 'home') body = <Home d={d} onOpen={id => go({ name: 'course', courseId: id })} onTab={t => { setTab(t); go({ name: t }); }} />;
    else if (view.name === 'courses') body = <Courses d={d} onOpen={id => go({ name: 'course', courseId: id })} />;
    else if (view.name === 'downloads') body = <Downloads d={d} onOpen={id => go({ name: 'course', courseId: id })} />;
    else if (view.name === 'profile') body = <Profile d={d} />;
    else if (view.name === 'course') { showNav = false; body = <Course c={course} onBack={() => go({ name: tab })} onLesson={() => go({ name: 'lesson', courseId: course.id })} onQuiz={() => go({ name: 'quiz', courseId: course.id })} />; }
    else if (view.name === 'lesson') { showNav = false; body = <Lesson poster={course.cover} src={window.MSA_DATA.sampleVideo} onBack={() => go({ name: 'course', courseId: course.id })} onNext={() => go({ name: 'quiz', courseId: course.id })} />; }
    else if (view.name === 'quiz') { showNav = false; body = <Quiz onBack={() => go({ name: 'course', courseId: course.id })} onDone={() => go({ name: 'course', courseId: course.id })} />; }

    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--surface-page)' }}>
        {body}
        {showNav && <BottomNav tab={tab} onTab={(t) => { setTab(t); go({ name: t }); }} />}
      </div>
    );
  }

  Object.assign(window, { MSA_Mobile: MobileApp });
})();
