/* global React, Mascot, Confetti, Btn, ProgressBar, StreakBadge, Icon */
const { useState, useEffect, useRef, useMemo } = React;

// Local hook by design — duplicated into screens-1 and screens-3; no shared module under no-bundler constraint.
function useIsNarrow(breakpoint = 720) {
  const [narrow, setNarrow] = useState(() =>
    typeof window !== 'undefined' ? window.innerWidth <= breakpoint : false
  );
  useEffect(() => {
    setNarrow(window.innerWidth <= breakpoint);
    const onResize = () => setNarrow(window.innerWidth <= breakpoint);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [breakpoint]);
  return narrow;
}

// ============================================================
// IDLE MOOD ROTATION — cycles through chill moods every few seconds
// ============================================================
function useIdleMood(moods = ['idle', 'idle-wave', 'idle-dance', 'mild-happy', 'idle-yawn'], interval = 4200) {
  const [i, setI] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setI(x => (x + 1) % moods.length), interval);
    return () => clearInterval(t);
  }, [moods.length, interval]);
  return moods[i];
}

// ============================================================
// COURSE PICKER
// ============================================================
function CoursePicker({ courses, onPickCourse, onExport, onImport, theme }) {
  const isNarrow = useIsNarrow();
  const idleMood = useIdleMood(['idle-wave', 'idle', 'idle-dance', 'mild-happy']);
  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: isNarrow ? '24px 16px 60px' : '48px 32px 80px' }}>
      <header style={{ display: 'flex', alignItems: 'center', gap: 24, marginBottom: 40, flexWrap: 'wrap' }}>
        <div className="float-y" style={{ flexShrink: 0 }}>
          <Mascot mood={idleMood} size={120} theme={theme} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, flex: '1 1 320px', minWidth: 0 }}>
          <h1 style={{ fontSize: 'clamp(32px, 4.4vw, 52px)', lineHeight: 1.05, margin: 0 }}>Hey, ready to study?</h1>
          <p style={{ color: 'var(--ink-soft)', fontSize: 18, fontWeight: 600, margin: 0 }}>
            Pick a course — Lucius is waiting.
          </p>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 24 }}>
        {courses.map((c, i) => (
          <CourseCard key={c.id} course={c} index={i} onClick={() => c.type !== 'placeholder' && onPickCourse(c)} theme={theme} />
        ))}
      </div>

      <footer style={{ marginTop: 56, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <Btn variant="ghost" icon={<Icon name="sparkle" size={18}/>} onClick={onExport}>Export progress</Btn>
        <Btn variant="ghost" icon={<Icon name="sparkle" size={18}/>} onClick={onImport}>Import progress</Btn>
      </footer>
    </div>
  );
}

function CourseCard({ course, index, onClick, theme }) {
  const isPlaceholder = course.type === 'placeholder';
  const accentBg = `oklch(92% 0.08 ${course.accentHue})`;

  if (isPlaceholder) {
    return (
      <div
        className="card"
        style={{
          minHeight: 240,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          background: 'transparent',
          borderStyle: 'dashed',
          boxShadow: 'none',
          color: 'var(--muted)',
          cursor: 'default',
          gap: 12,
        }}
      >
        <div style={{
          width: 56, height: 56, borderRadius: '50%',
          border: 'var(--outline-width) dashed var(--muted)',
          display: 'grid', placeItems: 'center',
        }}>
          <Icon name="plus" size={28} color="var(--muted)" strokeWidth={3} />
        </div>
        <div style={{ fontWeight: 800 }}>Add a course</div>
        <div style={{ fontSize: 13, color: 'var(--muted)' }}>Drop a manifest to start</div>
      </div>
    );
  }

  const acc = (course.progress && course.progress.answered > 0)
    ? Math.round((course.progress.correct / course.progress.answered) * 100)
    : 0;

  return (
    <div
      className="card card-tap pop-in"
      onClick={onClick}
      style={{
        animationDelay: `${index * 80}ms`,
        minHeight: 240,
        background: 'var(--surface)',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      {/* corner sticker */}
      <div style={{
        position: 'absolute', top: -12, right: -12,
        width: 80, height: 80, borderRadius: '50%',
        background: accentBg,
        opacity: 0.6,
      }}/>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 18 }}>
        <div style={{
          width: 56, height: 56, borderRadius: 'var(--radius)',
          background: 'var(--primary)', color: 'var(--primary-ink)',
          display: 'grid', placeItems: 'center',
          border: 'var(--outline-width) solid var(--line)',
          boxShadow: 'var(--shadow-pop-sm)',
          flexShrink: 0,
        }}>
          <Icon name={course.icon} size={28} strokeWidth={2.5} />
        </div>
        <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
          <div className="chip" style={{ alignSelf: 'flex-start', whiteSpace: 'nowrap' }}>{course.examCode || course.type}</div>
          <h2 style={{ fontSize: 24, lineHeight: 1.15 }}>{course.name}</h2>
        </div>
      </div>

      <div style={{ fontSize: 14, color: 'var(--ink-soft)', marginBottom: 18, fontWeight: 700 }}>
        {course.questionCount} questions · {course.domains.length} domain{course.domains.length === 1 ? '' : 's'}
      </div>

      {course.progress && course.progress.answered > 0 && (
        <>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, fontSize: 11, fontWeight: 800, marginBottom: 8, color: 'var(--ink-soft)', textTransform: 'uppercase', letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>
            <span>{course.progress.answered} answered</span>
            <span>{acc}%</span>
          </div>
          <ProgressBar value={course.progress.correct} max={course.progress.answered} />
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 18, flexWrap: 'wrap' }}>
            <StreakBadge days={course.progress.streakDays} theme={theme} />
            <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>{course.progress.lastStudied}</div>
          </div>
        </>
      )}
    </div>
  );
}

// ============================================================
// HOME / DASHBOARD MENU
// ============================================================
function Home({ course, onMode, onSwitchCourse, theme }) {
  const isNarrow = useIsNarrow();
  const acc = course.progress.answered > 0
    ? Math.round((course.progress.correct / course.progress.answered) * 100)
    : 0;
  // Pick mascot mood from streak: 7+ days = on fire, 3+ = mild happy, otherwise rotating idle
  const fireStreak = course.progress.streakDays >= 7;
  const happyStreak = course.progress.streakDays >= 3;
  const idleMood = useIdleMood(
    fireStreak ? ['fire-streak'] :
    happyStreak ? ['mild-happy', 'idle-wave', 'idle-dance', 'mild-happy'] :
    ['idle', 'idle-wave', 'idle-yawn', 'idle-dance']
  );
  const modes = [
    { id: 'drill',     label: 'Drill',      desc: 'Random practice. Pick a count and go.', icon: 'target',    color: 'var(--primary)',   ink: 'var(--primary-ink)' },
    { id: 'study',     label: 'Study',      desc: 'Spaced repetition. Hits weak spots.',  icon: 'lightning', color: 'var(--secondary)', ink: 'var(--ink)' },
  ];
  if (course.mockExam.enabled) {
    modes.push({ id: 'mock', label: 'Mock Exam', desc: `${course.mockExam.questionCount} questions · ${course.mockExam.durationMinutes} min`, icon: 'clock', color: 'var(--tertiary)', ink: 'var(--ink)' });
  }
  modes.push(
    { id: 'dashboard', label: 'Dashboard', desc: 'Trend, weak spots, due-now queue.', icon: 'chart', color: 'var(--surface-2)', ink: 'var(--ink)' },
    { id: 'cheatsheet', label: 'Cheat Sheet', desc: 'Concept reference. No quizzing.', icon: 'book', color: 'var(--surface-2)', ink: 'var(--ink)' },
  );

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: isNarrow ? '20px 16px 60px' : '32px 32px 80px' }}>
      <Btn variant="ghost" size="sm" icon={<Icon name="arrow-left" size={18}/>} onClick={onSwitchCourse}>
        Switch course
      </Btn>

      <header style={{
        display: 'grid',
        gridTemplateColumns: isNarrow ? '1fr' : '1fr auto',
        alignItems: 'center',
        gap: isNarrow ? 16 : 32,
        margin: isNarrow ? '16px 0 24px' : '24px 0 40px',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>
          <div className="chip chip-primary" style={{ alignSelf: 'flex-start', whiteSpace: 'nowrap' }}>
            <Icon name="briefcase" size={14}/> {course.examCode}
          </div>
          <h1 style={{ fontSize: 'clamp(34px, 4.6vw, 52px)' }}>{course.name}</h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
            <StreakBadge days={course.progress.streakDays} theme={theme} />
            <div className="chip">
              <Icon name="check" size={14} color="var(--correct)" strokeWidth={3}/>
              {acc}% accurate · {course.progress.answered} answered
            </div>
            {course.progress.dueNow > 0 && (
              <div className="chip chip-tertiary">
                <Icon name="clock" size={14}/> {course.progress.dueNow} due now
              </div>
            )}
          </div>
        </div>
        {!isNarrow && (
          <div className="float-y" style={{ animationDelay: '0.3s' }}>
            <Mascot mood={idleMood} size={150} theme={theme} />
          </div>
        )}
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 20 }}>
        {modes.map((m, i) => (
          <ModeCard key={m.id} mode={m} index={i} onClick={() => onMode(m.id)} />
        ))}
      </div>
    </div>
  );
}

function ModeCard({ mode, index, onClick }) {
  return (
    <div
      className="card card-tap pop-in"
      onClick={onClick}
      style={{
        animationDelay: `${index * 60}ms`,
        minHeight: 180,
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        background: mode.color,
        color: mode.ink,
      }}
    >
      <div style={{
        width: 52, height: 52, borderRadius: 'var(--radius)',
        background: 'var(--surface)',
        border: 'var(--outline-width) solid var(--line)',
        boxShadow: 'var(--shadow-pop-sm)',
        display: 'grid', placeItems: 'center',
        marginBottom: 16,
        color: 'var(--ink)',
      }}>
        <Icon name={mode.icon} size={26} />
      </div>
      <div>
        <h2 style={{ fontSize: 28, marginBottom: 6 }}>{mode.label}</h2>
        <div style={{ fontSize: 14, fontWeight: 700, opacity: 0.85 }}>{mode.desc}</div>
      </div>
    </div>
  );
}

Object.assign(window, { CoursePicker, Home });
