// Student Dashboard component for MyMarian

const WEEKLY_DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const EMPTY_WEEKLY_MINUTES = [0, 0, 0, 0, 0, 0, 0];

function formatDueDate(value) {
  if (!value) return 'No due date';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return String(value);
  return date.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
}

function Dashboard({ grade, setGrade, navigate, demoPlan, authUser = null, currentCourseId, setCurrentCourseId }) {
  const [dashboardData, setDashboardData] = React.useState(null);
  const [dashboardError, setDashboardError] = React.useState('');
  const [dashboardLoading, setDashboardLoading] = React.useState(false);

  const useOpenEdxApi = !!demoPlan || (!!authUser && !demoPlan);

  React.useEffect(() => {
    if (!useOpenEdxApi) {
      setDashboardData(null);
      setDashboardError('');
      return undefined;
    }

    let cancelled = false;
    setDashboardData(null);
    setDashboardLoading(true);
    setDashboardError('');

    const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
    const endpoint = demoPlan ? '/api/dashboard/demo' : '/api/dashboard';

    fetch(apiUrl(endpoint), { credentials: 'include', cache: 'no-store', headers })
      .then(async response => {
        const text = await response.text();
        let data = {};
        if (text) {
          try {
            data = JSON.parse(text);
          } catch (error) {
            data = { error: text };
          }
        }
        return { ok: response.ok, data };
      })
      .then(({ ok, data }) => {
        if (cancelled) return;
        if (!ok) {
          throw new Error(data.error || 'Unable to load dashboard data.');
        }
        if (!demoPlan && authUser && authUser.id && data.user && data.user.id && String(data.user.id) !== String(authUser.id)) {
          throw new Error('Dashboard session changed. Sign out, then sign in again with the account you want to use.');
        }
        setDashboardData(data);
      })
      .catch(error => {
        if (!cancelled) {
          const message = error.message === 'Failed to fetch'
            ? 'Could not reach the MyMarian backend API. npms running on http://127.0.0.1:8080 and this frontend is opened from http://127.0.0.1:5173.'
            : (error.message || 'Unable to load dashboard data.');
          setDashboardError(message);
        }
      })
      .finally(() => {
        if (!cancelled) setDashboardLoading(false);
      });

    return () => { cancelled = true; };
  }, [authUser, demoPlan, useOpenEdxApi]);

  const apiCourses = (dashboardData && dashboardData.courses) || [];
  const learner = (dashboardData && dashboardData.learner) || null;
  const learnerCourses = (learner && learner.courses) || apiCourses;

  const courses = (learnerCourses || [])
    .filter(course => course.id)
    .map(course => ({
      id: course.id,
      subject: course.subject || 'Course',
      title: course.title || course.id,
      progress: course.progress || 0,
      nextLesson: course.nextLesson || course.accessMessage || 'Continue learning',
      lessons: course.totalUnits || course.lessons || 0,
      done: course.completedUnits || course.done || 0,
      imageUrl: course.imageUrl,
      learningHomeUrl: course.learningHomeUrl,
      org: course.org,
      number: course.number,
      isEnrolled: course.isEnrolled,
      accessMessage: course.accessMessage,
      pacing: course.pacing,
    }));

  const clickhouse = dashboardData?.clickhouse;

  const totalProgress =
    clickhouse?.progress ??
   0;

  const streak =
    clickhouse?.streak ??
    0;

  const weeklyGoalMinutes =
    clickhouse?.goalMinutes ??
    60;

  const weeklyDoneMinutes =
    clickhouse?.completedMinutes ??
    0;

  const weeklyRemainingHours = Math.max(
    (weeklyGoalMinutes - weeklyDoneMinutes) / 60,
    0
  );

  const weeklyChartMinutes =
    Array.isArray(clickhouse?.dailyMinutes) && clickhouse.dailyMinutes.length
      ? clickhouse.dailyMinutes
      : EMPTY_WEEKLY_MINUTES;

  const xpTotal = useOpenEdxApi && dashboardData
    ? ((dashboardData.xp && dashboardData.xp.total) || 0)
    : 0;

  const videoStats = useOpenEdxApi && dashboardData ? dashboardData.video_hours : null;
  const quizStats = useOpenEdxApi && dashboardData ? dashboardData.quiz_progress : null;
  const deadlines = useOpenEdxApi && dashboardData ? (dashboardData.deadlines || []) : [];

  const continueCourse = (learner && learner.resumeCourse)
    ? courses.find(c => c.id === learner.resumeCourse.courseId) || courses[0]
    : courses.reduce((best, course) => {
      if (!best || (course.progress < 100 && course.progress < best.progress)) return course;
      return best;
    }, courses[0]);

  const openCourse = (course) => {
    if (course && course.id) {
      setCurrentCourseId(course.id);
      // Pass course data to player component
      if (typeof window !== 'undefined' && window.currentCourse) {
        window.currentCourse = {
          id: course.id,
          title: course.title,
          subject: course.subject,
          org: course.org,
          number: course.number,
        };
      }
    }
    navigate('player');
  };

  const upcomingAssessments = useOpenEdxApi && quizStats && quizStats.quizzes && quizStats.quizzes.length
    ? quizStats.quizzes.filter(quiz => !quiz.completed).slice(0, 5).map(quiz => ({
      subject: 'Assessment',
      title: quiz.title,
      due: `${quiz.score}% score`,
      questions: 0,
      grade,
    }))
    : useOpenEdxApi && deadlines.length
      ? deadlines.slice(0, 5).map(item => ({
        subject: item.subject || 'Course',
        title: item.activity,
        due: item.dueDate ? formatDueDate(item.dueDate) : (item.note || 'Study Lesson'),
        questions: 0,
        grade,
      }))
      : [];

  const displayName = (authUser && authUser.name) || (demoPlan ? 'Demo Student' : 'Student');
  const region = (authUser && authUser.region) || 'Ethiopia';
  const openedxMeta = dashboardData && dashboardData.openedx;
  const dashboardReady = !useOpenEdxApi || (dashboardData && !dashboardLoading);

  return (
    <div style={{ fontFamily: 'Plus Jakarta Sans, sans-serif', color: BRAND.text, minHeight: '100%' }}>
      {/* Header strip */}
      <div style={{
        background: BRAND.dark,
        padding: '28px 36px 24px',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <EthiopianPattern opacity={0.08} color={BRAND.gold} />
        <FloatingGradient color={BRAND.gold} top="-30%" right="-5%" size={400} opacity={0.18} speed={18} blur={80} />
        <FloatingGradient color={BRAND.primary} bottom="-60%" left="20%" size={500} opacity={0.25} speed={22} blur={90} />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 16 }}>
            <div>
              <p style={{ color: `${BRAND.gold}cc`, fontSize: 13, fontWeight: 500, margin: '0 0 4px', letterSpacing: 0.5 }}>GOOD MORNING</p>
              <h1 style={{ fontFamily: 'Playfair Display, Georgia, serif', color: '#fff', fontSize: 28, margin: 0, fontWeight: 700 }}>
                {displayName}
              </h1>
              <p style={{ color: '#ffffff80', fontSize: 13, margin: '4px 0 0', fontWeight: 400 }}>
                {openedxMeta ? (
                  <>
                    Open edX · {openedxMeta.siteName}
                  </>
                ) : (
                  <>
                    {region} — Grade {grade} Student · MyMarian
                  </>
                )}
              </p>
            </div>
            {/* Streak badge */}
            <div style={{
              background: `${BRAND.gold}22`,
              border: `1.5px solid ${BRAND.gold}55`,
              borderRadius: 12,
              padding: '12px 20px',
              textAlign: 'center',
            }}>
              <div style={{ fontSize: 28 }}>🔥</div>
              <div style={{ color: BRAND.gold, fontWeight: 800, fontSize: 22, lineHeight: 1 }}>
                <AnimatedCounter value={streak} duration={1500} />
              </div>
              <div style={{ color: '#ffffff80', fontSize: 11, marginTop: 2 }}>day streak</div>
            </div>
          </div>

          {/* Enrolled grade — locked to user's signup grade */}
          {!useOpenEdxApi && (
            <div style={{ display: 'flex', gap: 10, marginTop: 20, flexWrap: 'wrap', alignItems: 'center' }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                background: BRAND.primary, color: '#fff',
                padding: '8px 18px', borderRadius: 99,
                fontSize: 13, fontWeight: 700, letterSpacing: 0.4,
                boxShadow: `0 4px 14px ${BRAND.primary}55`,
              }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: BRAND.gold }} />
                Enrolled · Grade {grade}
              </span>
              <span style={{ color: '#ffffff66', fontSize: 11 }}>Your curriculum is set to Grade {grade}. Contact support to change.</span>
            </div>
          )}
        </div>
      </div>

      <div style={{ padding: '28px 36px', display: 'flex', flexDirection: 'column', gap: 28 }}>
        {demoPlan && (
          <div style={{
            background: `linear-gradient(135deg, ${BRAND.gold}18, ${BRAND.primary}10)`,
            border: `1.5px solid ${BRAND.gold}55`, borderRadius: 12,
            padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ fontSize: 22 }}>✦</span>
              <div>
                <div style={{ fontSize: 13, fontWeight: 800, color: BRAND.dark }}>
                  You're exploring the {demoPlan.charAt(0).toUpperCase() + demoPlan.slice(1)} plan in demo mode
                </div>
                <div style={{ fontSize: 11, color: BRAND.muted, marginTop: 2 }}>
                  Sample data only · Sign up to keep your real progress
                </div>
              </div>
            </div>
            <CTAButton variant="primary" small onClick={() => navigate('signup')} className="mm-btn">Sign up to save</CTAButton>
          </div>
        )}

        {/* Loading state */}
        {useOpenEdxApi && dashboardLoading && (
          <div style={{ padding: '40px 20px', textAlign: 'center', color: BRAND.muted }}>
            Loading your dashboard...
          </div>
        )}

        {/* Error state */}
        {useOpenEdxApi && dashboardError && (
          <div style={{
            background: `#f8d7da`,
            border: `1px solid #f5c6cb`,
            borderRadius: 12,
            padding: '14px 18px',
            color: '#721c24',
            fontSize: 13,
          }}>
            {dashboardError}
          </div>
        )}

        {/* Stats row */}
        {dashboardReady && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
            {[
              { label: 'Overall Progress', value: totalProgress, suffix: '%', sub: `${courses.length} courses`, color: BRAND.primary },
              { label: 'Weekly Study Goal', value: weeklyRemainingHours, suffix: 'h', sub: `${(weeklyDoneMinutes / 60).toFixed(1)}h done`, color: BRAND.gold },
              { label: 'Experience Points', value: xpTotal, suffix: ' XP', sub: 'All time', color: '#10b981' },
              { label: 'Upcoming Deadlines', value: upcomingAssessments.length, suffix: '', sub: 'This week', color: '#c0392b' },
            ].map((stat, i) => (
              <Reveal key={stat.label} delay={i * 100}>
                <div className="mm-card-lift" style={{
                  background: BRAND.surface,
                  borderRadius: 12,
                  border: `1px solid ${BRAND.border}`,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                  padding: '20px 22px',
                  height: '100%',
                }}>
                  <div style={{ fontSize: 12, color: BRAND.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>{stat.label}</div>
                  <div style={{ fontSize: 32, fontWeight: 800, color: stat.color, margin: '6px 0 2px', fontFamily: 'Playfair Display, Georgia, serif' }}>
                    <AnimatedCounter value={stat.value} suffix={stat.suffix} duration={1600} />
                  </div>
                  <div style={{ fontSize: 12, color: BRAND.muted }}>{stat.sub}</div>
                  {stat.label === 'Overall Progress' && <ProgressBar value={totalProgress} color={BRAND.primary} style={{ marginTop: 10 }} />}
                  {stat.label === 'Weekly Study Goal' && <ProgressBar value={weeklyDoneMinutes} max={weeklyGoalMinutes} color={BRAND.gold} style={{ marginTop: 10 }} />}
                </div>
              </Reveal>
            ))}
          </div>
        )}

        {/* Weekly activity */}
        {dashboardReady && (
          <Card style={{ padding: '22px 26px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>Weekly Study Activity</h3>
              <span style={{ fontSize: 12, color: BRAND.muted }}>Minutes per day</span>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', height: 72 }}>
              {WEEKLY_DAYS.map((day, i) => {
                const max = Math.max(...weeklyChartMinutes, 1);
                const value = weeklyChartMinutes[i] || 0;
                const h = value ? Math.max(8, (value / max) * 72) : 4;
                const now = new Date();
                const isToday = i === now.getDay();
                return (
                  <div key={day} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                    <div style={{
                      width: '100%', height: h,
                      background: isToday ? BRAND.gold : value > 0 ? BRAND.primary : '#e5e7eb',
                      borderRadius: '4px 4px 0 0',
                      opacity: isToday ? 1 : 0.75,
                      transition: 'height 0.4s ease',
                    }} />
                    <span style={{ fontSize: 10, color: isToday ? BRAND.gold : BRAND.muted, fontWeight: isToday ? 700 : 400 }}>{day}</span>
                  </div>
                );
              })}
            </div>
          </Card>
        )}

        {/* Last visited */}
        {continueCourse && dashboardReady && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <h2 style={{ margin: 0, fontFamily: 'Playfair Display, Georgia, serif', fontSize: 20, fontWeight: 700 }}>Continue Learning</h2>
            </div>
            <Card style={{ padding: 0, overflow: 'hidden' }}>
              <div style={{ display: 'flex', gap: 0 }}>
                <div style={{
                  width: 6,
                  background: SUBJECT_COLORS[continueCourse.subject] || BRAND.primary,
                  flexShrink: 0,
                }} />
                <div style={{ padding: '20px 24px', flex: 1, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
                  <div>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                      <span style={{
                        background: `${SUBJECT_COLORS[continueCourse.subject] || BRAND.primary}18`,
                        color: SUBJECT_COLORS[continueCourse.subject] || BRAND.primary,
                        padding: '2px 10px', borderRadius: 99,
                        fontSize: 11, fontWeight: 700, letterSpacing: 0.3,
                      }}>{(continueCourse.subject || 'Course').toUpperCase()}</span>
                      <span style={{ fontSize: 11, color: BRAND.muted }}>
                        {useOpenEdxApi ? 'Continue' : `Grade ${grade}`} · {useOpenEdxApi ? 'In progress' : `Lesson ${continueCourse.done} of ${continueCourse.lessons}`}
                      </span>
                    </div>
                    <h3 style={{ margin: '0 0 4px', fontSize: 17, fontWeight: 700 }}>{continueCourse.title}</h3>
                    <p style={{ margin: 0, color: BRAND.muted, fontSize: 13 }}>Next: {continueCourse.nextLesson}</p>
                    <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
                      <ProgressBar value={continueCourse.progress} color={SUBJECT_COLORS[continueCourse.subject] || BRAND.primary} />
                      <span style={{ fontSize: 12, color: BRAND.muted, whiteSpace: 'nowrap' }}>{continueCourse.progress}% complete</span>
                    </div>
                  </div>
                  <CTAButton onClick={() => openCourse(continueCourse)} variant="primary" style={{ whiteSpace: 'nowrap' }}>
                    ▶ Resume Lesson
                  </CTAButton>
                </div>
              </div>
            </Card>
          </div>
        )}

        {/* Enrolled courses */}
        {courses && courses.length > 0 && dashboardReady && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <h2 style={{ margin: 0, fontFamily: 'Playfair Display, Georgia, serif', fontSize: 20, fontWeight: 700 }}>
                {useOpenEdxApi ? 'My Open edX Courses' : `Grade ${grade} Courses`}
              </h2>
              <span style={{ fontSize: 12, color: BRAND.muted }}>{courses.length} {useOpenEdxApi ? 'enrolled' : 'courses'}</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
              {courses.map((course, idx) => {
                const subColor = SUBJECT_COLORS[course.subject] || BRAND.primary;
                return (
                  <Reveal key={course.id} delay={idx * 70}>
                    <Card style={{ padding: 0, cursor: 'pointer', height: '100%' }} onClick={() => openCourse(course)}>
                      <div style={{ display: 'flex', alignItems: 'stretch' }}>
                        <div style={{ width: 5, background: subColor, borderRadius: '12px 0 0 12px', flexShrink: 0 }} />
                        <div style={{ padding: '16px 18px', flex: 1 }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                            <span style={{
                              background: `${subColor}18`, color: subColor,
                              padding: '2px 9px', borderRadius: 99,
                              fontSize: 10, fontWeight: 700, letterSpacing: 0.4,
                            }}>{(course.subject || 'Course').toUpperCase()}</span>
                            <span style={{ fontSize: 12, fontWeight: 700, color: subColor }}>
                              <AnimatedCounter value={course.progress} suffix="%" duration={1400} />
                            </span>
                          </div>
                          <h4 style={{ margin: '8px 0 4px', fontSize: 14, fontWeight: 700, lineHeight: 1.3 }}>{course.title}</h4>
                          <p style={{ margin: '0 0 10px', fontSize: 11, color: BRAND.muted }}>Next: {course.nextLesson}</p>
                          <ProgressBar value={course.progress} color={subColor} height={5} />
                          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
                            <span style={{ fontSize: 10, color: BRAND.muted }}>{course.done}/{course.lessons} lessons</span>
                          </div>
                        </div>
                      </div>
                    </Card>
                  </Reveal>
                );
              })}
            </div>
          </div>
        )}

        {dashboardReady && courses.length === 0 && (
          <Card style={{ padding: '22px 26px' }}>
            <h2 style={{ margin: '0 0 6px', fontFamily: 'Playfair Display, Georgia, serif', fontSize: 20, fontWeight: 700 }}>
              No enrolled courses yet
            </h2>
            <p style={{ margin: 0, color: BRAND.muted, fontSize: 13, lineHeight: 1.6 }}>
              Live Open edX enrollments will appear here after the enrollment sync finishes.
            </p>
          </Card>
        )}

        {/* Upcoming assessments */}
        {upcomingAssessments && upcomingAssessments.length > 0 && dashboardReady && (
          <div>
            <h2 style={{ margin: '0 0 14px', fontFamily: 'Playfair Display, Georgia, serif', fontSize: 20, fontWeight: 700 }}>
              Upcoming Assessments
            </h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {upcomingAssessments.map((q, i) => {
                const subColor = SUBJECT_COLORS[q.subject] || BRAND.primary;
                return (
                  <Card key={i} style={{ padding: '14px 20px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
                      <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
                        <div style={{
                          width: 40, height: 40, borderRadius: 10,
                          background: `${subColor}18`, color: subColor,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: 20,
                        }}>📋</div>
                        <div>
                          <div style={{ fontWeight: 700, fontSize: 14 }}>{q.title}</div>
                          <div style={{ fontSize: 12, color: BRAND.muted, marginTop: 2 }}>
                            <span style={{ color: subColor, fontWeight: 600 }}>{q.subject}</span> · {q.questions ? `${q.questions} questions` : ''} Grade {q.grade}
                          </div>
                        </div>
                      </div>
                      <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                        <span style={{ fontSize: 12, color: BRAND.muted }}>Due: {q.due}</span>
                        <CTAButton onClick={() => navigate('quiz')} small variant="primary">Start Quiz</CTAButton>
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          </div>
        )}

        {dashboardReady && upcomingAssessments.length === 0 && (
          <Card style={{ padding: '22px 26px' }}>
            <h2 style={{ margin: '0 0 6px', fontFamily: 'Playfair Display, Georgia, serif', fontSize: 20, fontWeight: 700 }}>
              No upcoming assessments
            </h2>
            <p style={{ margin: 0, color: BRAND.muted, fontSize: 13, lineHeight: 1.6 }}>
              Assignments and quizzes will appear here when they are returned by Open edX analytics.
            </p>
          </Card>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
