const studentSchedule = [
  { day: "Mon", items: [
    { time: "9:00 AM", course: "CSC 201", title: "Data Structures", venue: "Engineering Block A", lecturer: "Dr. Amina Bello" },
    { time: "2:00 PM", course: "MTH 101", title: "Calculus I", venue: "Science S1", lecturer: "Dr. E. Okafor" }
  ] },
  { day: "Tue", items: [
    { time: "10:00 AM", course: "PHY 201", title: "Mechanics", venue: "Science S2", lecturer: "Dr. T. Ibrahim" },
    { time: "1:00 PM", course: "BUS 301", title: "Marketing", venue: "Business B2", lecturer: "Dr. M. Yusuf" }
  ] },
  { day: "Wed", items: [
    { time: "9:00 AM", course: "CSC 201", title: "Data Structures Lab", venue: "Engineering Lab 2", lecturer: "Dr. Amina Bello" }
  ] },
  { day: "Thu", items: [
    { time: "11:00 AM", course: "MTH 101", title: "Calculus I Tutorial", venue: "Science S1", lecturer: "Dr. E. Okafor" },
    { time: "3:00 PM", course: "PHY 201", title: "Mechanics Lab", venue: "Science S2", lecturer: "Dr. T. Ibrahim" }
  ] },
  { day: "Fri", items: [
    { time: "10:00 AM", course: "BUS 301", title: "Marketing Case Study", venue: "Business B2", lecturer: "Dr. M. Yusuf" }
  ] }
];

function getTodayScheduleIndex() {
  const scheduleIndex = [0, 0, 1, 2, 3, 4, 0][new Date().getDay()];
  return typeof scheduleIndex === "number" ? scheduleIndex : 0;
}

const studentCourses = [
  { code: "CSC 201", name: "Data Structures", pct: 74, state: "At risk", tone: "gold", history: ["Present", "Present", "Late", "Absent", "Present"] },
  { code: "MTH 101", name: "Calculus I", pct: 91, state: "Eligible", tone: "green", history: ["Present", "Present", "Present", "Present"] },
  { code: "PHY 201", name: "Mechanics", pct: 63, state: "Not eligible", tone: "red", history: ["Absent", "Present", "Left Early", "Absent"] },
  { code: "BUS 301", name: "Marketing", pct: 82, state: "Eligible", tone: "green", history: ["Present", "Present", "Late", "Present"] }
];

const studentNotifications = [
  { title: "Attendance confirmed", detail: "CSC 201 · verified check-in at Engineering Block A", time: "Just now", tone: "green" },
  { title: "Risk alert", detail: "PHY 201 attendance is 63% — below the 75% exam threshold", time: "Today, 8:04 AM", tone: "red" },
  { title: "Session opened", detail: "CSC 201 token valid until 10:12 · authorised check-in only", time: "Today, 9:58 AM", tone: "blue" },
  { title: "Device verified", detail: "iPhone 15 Pro signed today's attendance payload successfully", time: "Yesterday", tone: "teal" }
];

function StudentCourseRows({ courses, checkedIn, onOpenCourse }) {
  return (
    <div className="student-course-list">
      {courses.map((course) => {
        const pct = course.code === "CSC 201" && checkedIn ? 75 : course.pct;
        const isEligible = pct >= 75;
        return (
          <button className="student-course-row" key={course.code} onClick={() => onOpenCourse(course)} type="button">
            <div>
              <span>{course.code}</span>
              <strong>{course.name}</strong>
              <div className="row-bar"><div className={isEligible ? "" : "risk"} style={{ width: `${pct}%` }}></div></div>
            </div>
            <div className="student-course-meta">
              <strong className={isEligible ? "ok" : "risk"}>{pct}%</strong>
              <Badge tone={isEligible ? "green" : course.tone}>{isEligible ? "Eligible" : course.state}</Badge>
            </div>
            <span className="row-chevron"><Icon name="chevronright" size={13} /></span>
          </button>
        );
      })}
    </div>
  );
}

function StudentNotificationsView({ checkedIn, onBack }) {
  const visibleNotifications = studentNotifications.filter((item) => item.title !== "Attendance confirmed" || checkedIn);
  return (
    <div className="mobile-panel-stack">
      <SubViewHead onBack={onBack} title="Notifications" />
      <MobileList items={visibleNotifications.map((item) => ({
        title: item.title,
        detail: `${item.time} · ${item.detail}`,
        state: item.tone === "red" ? "Action" : "New",
        tone: item.tone
      }))} />
      <div className="mobile-note">Push delivery uses server-authorised session and risk events only.</div>
    </div>
  );
}

function StudentCheckInDetail({ checkedIn, dataset, onBack, onRunCheckIn, showToast }) {
  const steps = [
    { key: "token", title: "Session token", detail: "Server-issued for CSC 201, expires 10:12" },
    { key: "enrolment", title: "Course enrolment", detail: "Ademola is registered for CSC 201" },
    { key: "device", title: "Device signature", detail: "Secure Enclave key signs the payload" },
    { key: "location", title: "Location check", detail: "12m from venue · radius 60m" },
    { key: "nonce", title: "Anti-replay nonce", detail: "One-time value consumed by the server" }
  ];
  const [passedCount, setPassedCount] = React.useState(checkedIn ? steps.length : -1);
  const [done, setDone] = React.useState(false);
  const [justDone, setJustDone] = React.useState(false);
  const timersRef = React.useRef([]);

  React.useEffect(() => () => timersRef.current.forEach(clearTimeout), []);

  const running = passedCount >= 0 && !done && !checkedIn;
  const allPassed = checkedIn || done;

  function runCheckIn() {
    if (checkedIn || running || done) return;
    steps.forEach((step, index) => {
      timersRef.current.push(setTimeout(() => {
        setPassedCount(index);
        if (index === steps.length - 1) {
          timersRef.current.push(setTimeout(() => {
            onRunCheckIn();
            setDone(true);
            setJustDone(true);
            showToast("Check-in recorded · synced to server");
          }, 380));
        }
      }, 430 * (index + 1)));
    });
  }

  return (
    <div className="mobile-panel-stack">
      <SubViewHead onBack={onBack} title="Authorised check-in" />
      <div className={`mobile-check-state ${allPassed ? "success" : ""}`}>
        <div className={`check-circle compact ${running ? "working" : ""} ${justDone ? "pop" : ""}`}>{allPassed ? "✓" : "•"}</div>
        <h2>{allPassed ? "Attendance recorded" : running ? "Verifying…" : "Ready to check in"}</h2>
        <p>{dataset.courseCode} · {dataset.venue}</p>
      </div>

      <div className="check-step-list">
        {steps.map((step, index) => {
          const rowState = allPassed || index <= passedCount ? "passed" : running && index === passedCount + 1 ? "active" : "";
          return (
            <div className={`step-row ${rowState}`} key={step.key}>
              <span className="step-glyph">
                {rowState === "passed" ? "✓" : rowState === "active" ? <span className="step-spinner"></span> : index + 1}
              </span>
              <span className="step-copy">
                <strong>{step.title}</strong>
                <span>{step.detail}</span>
              </span>
              <small className="step-state">{rowState === "passed" ? "Pass" : rowState === "active" ? "Checking" : "Queued"}</small>
            </div>
          );
        })}
      </div>

      <div className="mobile-action-grid">
        <Button disabled={allPassed || running} onClick={runCheckIn} tone={allPassed ? "default" : "success"}>
          {allPassed ? "Synced ✓" : running ? "Verifying…" : "Check in now"}
        </Button>
        <GhostButton onClick={onBack}>Done</GhostButton>
      </div>
      <div className="mobile-note">Offline queue only accepts events from a live, server-authorised session token.</div>
    </div>
  );
}

function StudentCourseDetail({ course, checkedIn, onBack }) {
  const pct = course.code === "CSC 201" && checkedIn ? 75 : course.pct;
  const isEligible = pct >= 75;
  const history = course.history.map((status, index) => ({
    title: `Jul ${22 - index * 3}, 2026`,
    detail: `${course.code} · ${course.name}`,
    state: status,
    tone: status === "Present" ? "green" : status === "Late" ? "gold" : "red"
  }));

  return (
    <div className="mobile-panel-stack">
      <SubViewHead onBack={onBack} title={course.code} />
      <div className="student-ring-card">
        <div className="student-ring" style={{ "--ring-deg": `${pct * 3.6}deg` }}>
          <span>{pct}%</span>
        </div>
        <div>
          <h2>{course.name}</h2>
          <p>{isEligible ? "Eligible for examination" : "Below 75% threshold"}</p>
          <Badge tone={isEligible ? "green" : course.tone}>{isEligible ? "Eligible" : course.state}</Badge>
        </div>
      </div>
      <ProgressBar value={pct} />
      <h3 className="mobile-section-heading">Recent sessions</h3>
      <MobileList items={history} />
      <div className="mobile-note">History comes from verified attendance records — manual records are flagged for audit.</div>
    </div>
  );
}

function StudentHomeView({ dataset, checkedIn, notifUnread, onOpenCheckIn, onOpenCourse, onOpenNotifications }) {
  return (
    <div className="mobile-panel-stack">
      <div className="student-home-header">
        <div className="student-avatar">AO</div>
        <div>
          <strong>Ademola Oladipo</strong>
          <span>{dataset.tenant} · Computer Science</span>
        </div>
        <button aria-label="Notifications" className="bell-btn" onClick={onOpenNotifications} type="button">
          <Icon name="bell" size={17} />
          {notifUnread && <span className="bell-dot">{checkedIn ? "4" : "3"}</span>}
        </button>
      </div>

      <div className="student-live-card">
        <div className="live-chip-row">
          <Badge tone="green">LIVE NOW</Badge>
          <span className="live-time">10:00 – 11:30</span>
        </div>
        <h2>{dataset.course}</h2>
        <p>{dataset.venue} · {dataset.lecturer}</p>
        <Button onClick={onOpenCheckIn} tone={checkedIn ? "default" : "success"}>{checkedIn ? "Checked In ✓" : "Check In"}</Button>
      </div>

      <div className="mobile-stat-grid">
        <MobileStat label="Overall attendance" value={checkedIn ? "83%" : "82%"} tone="teal" />
        <MobileStat label="Exam eligibility" value={checkedIn ? "On track" : "1 risk"} tone={checkedIn ? "green" : "gold"} />
      </div>

      <div className="student-timetable-card">
        <h3>Today's timetable</h3>
        {studentSchedule[getTodayScheduleIndex()].items.map((item) => (
          <div className="student-timetable-row" key={`${item.course}-${item.time}`}>
            <span>{item.time}</span>
            <div>
              <strong>{item.title} {item.course === "CSC 201" && <em className="now-tag">Live</em>}</strong>
              <p>{item.venue}</p>
            </div>
          </div>
        ))}
      </div>

      <h3 className="mobile-section-heading">Registered courses</h3>
      <StudentCourseRows checkedIn={checkedIn} courses={studentCourses} onOpenCourse={onOpenCourse} />
    </div>
  );
}

function StudentTimetableView() {
  const [dayIndex, setDayIndex] = React.useState(() => getTodayScheduleIndex());
  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Timetable</h2>
      <div className="student-day-tabs">
        {studentSchedule.map((day, index) => (
          <button className={dayIndex === index ? "active" : ""} key={day.day} onClick={() => setDayIndex(index)} type="button">{day.day}</button>
        ))}
      </div>
      <MobileList items={studentSchedule[dayIndex].items.map((item) => ({
        title: `${item.course} · ${item.title}`,
        detail: `${item.time} · ${item.venue} · ${item.lecturer}`,
        state: dayIndex === 0 && item.course === "CSC 201" ? "Live" : "Scheduled",
        tone: dayIndex === 0 && item.course === "CSC 201" ? "green" : "blue"
      }))} />
      <div className="mobile-note">Timetable entries are the source for authorised attendance sessions.</div>
    </div>
  );
}

function StudentAttendanceView({ checkedIn, onOpenCourse }) {
  const overall = checkedIn ? 83 : 82;
  return (
    <div className="mobile-panel-stack">
      <h2 className="mobile-view-title">Attendance & eligibility</h2>
      <div className="student-ring-card overall">
        <div className="student-ring" style={{ "--ring-deg": `${overall * 3.6}deg` }}>
          <span>{overall}%</span>
        </div>
        <div>
          <h2>Overall attendance</h2>
          <p>Across 4 registered courses this semester</p>
        </div>
      </div>
      <StudentCourseRows checkedIn={checkedIn} courses={studentCourses} onOpenCourse={onOpenCourse} />
      <div className="mobile-note danger">
        Rule-based attendance alert: PHY 201 is below the examination eligibility threshold. Attend the next 3 sessions to recover.
      </div>
    </div>
  );
}

function StudentProfileView({ dataset, onLogout, onOpenDevice }) {
  return (
    <div className="mobile-panel-stack">
      <div className="student-profile-card">
        <div className="student-avatar large">AO</div>
        <h2>Ademola Oladipo</h2>
        <p>19/CSC/001 · Computer Science</p>
        <Badge tone="teal">{dataset.tenant}</Badge>
      </div>
      <div className="mobile-list">
        <button className="mobile-list-row tappable" onClick={onOpenDevice} type="button">
          <div>
            <strong>Registered device</strong>
            <span>iPhone 15 Pro · Secure Enclave public key</span>
          </div>
          <Icon name="chevronright" size={15} />
        </button>
        <div className="mobile-list-row">
          <div>
            <strong>Reinstall recovery</strong>
            <span>Hardware fingerprint + university email confirmation</span>
          </div>
          <Badge tone="blue">Self-service</Badge>
        </div>
        <div className="mobile-list-row">
          <div>
            <strong>Lost device</strong>
            <span>Suspend on web, re-bind after admin identity check</span>
          </div>
          <Badge tone="gold">Protected</Badge>
        </div>
        <div className="mobile-list-row">
          <div>
            <strong>Notifications</strong>
            <span>Session opened, attendance confirmed, risk alerts</span>
          </div>
          <Badge tone="green">On</Badge>
        </div>
      </div>
      <GhostButton className="danger" onClick={onLogout}>
        <Icon name="logout" size={14} />
        Sign out of CampusOS
      </GhostButton>
      <div className="login-footer">CampusOS v0.9 demo build</div>
    </div>
  );
}

function StudentDeviceDetailView({ onBack, showToast }) {
  return (
    <div className="mobile-panel-stack">
      <SubViewHead onBack={onBack} title="Device trust" />
      <div className="device-trust-card">
        <Icon name="smartphone" size={22} />
        <div>
          <strong>iPhone 15 Pro</strong>
          <span>Bound to Ademola Oladipo · 19/CSC/001</span>
        </div>
        <Badge tone="green">Trusted</Badge>
      </div>
      <MobileList items={[
        { title: "Key algorithm", detail: "EC P-256 · private key never leaves Secure Enclave", state: "Hardware", tone: "teal" },
        { title: "Key fingerprint", detail: "3F:9A:C2:71:0E:5B:D4:88:21:6A", state: "Verified", tone: "green" },
        { title: "Bound since", detail: "Sep 12, 2025 · re-verified today at 09:58", state: "Active", tone: "blue" },
        { title: "Biometric unlock", detail: "Face ID gates signing of attendance payloads", state: "Enabled", tone: "green" }
      ]} />
      <GhostButton className="danger" onClick={() => showToast("Suspend request sent to campus admin")}>Report lost / suspend device</GhostButton>
      <div className="mobile-note">Suspension blocks check-ins immediately. Re-binding requires an admin identity check on the web portal.</div>
    </div>
  );
}

function StudentMobileView({ dataset, checkedIn, activeTab, onLogout, onRunCheckIn }) {
  const [detailMode, setDetailMode] = React.useState(null);
  const [selectedCourse, setSelectedCourse] = React.useState(null);
  const [notifUnread, setNotifUnread] = React.useState(true);
  const [toastElement, showToast] = useLocalToast();

  function openCourse(course) {
    setSelectedCourse(course);
    setDetailMode("course");
  }

  let view = null;
  if (detailMode === "checkin") {
    view = <StudentCheckInDetail checkedIn={checkedIn} dataset={dataset} onBack={() => setDetailMode(null)} onRunCheckIn={onRunCheckIn} showToast={showToast} />;
  } else if (detailMode === "course" && selectedCourse) {
    view = <StudentCourseDetail checkedIn={checkedIn} course={selectedCourse} onBack={() => setDetailMode(null)} />;
  } else if (detailMode === "notifications") {
    view = <StudentNotificationsView checkedIn={checkedIn} onBack={() => setDetailMode(null)} />;
  } else if (detailMode === "device") {
    view = <StudentDeviceDetailView onBack={() => setDetailMode(null)} showToast={showToast} />;
  } else if (activeTab === "Timetable") {
    view = <StudentTimetableView />;
  } else if (activeTab === "Attendance") {
    view = <StudentAttendanceView checkedIn={checkedIn} onOpenCourse={openCourse} />;
  } else if (activeTab === "Profile") {
    view = <StudentProfileView dataset={dataset} onLogout={onLogout} onOpenDevice={() => setDetailMode("device")} />;
  } else {
    view = (
      <StudentHomeView
        checkedIn={checkedIn}
        dataset={dataset}
        notifUnread={notifUnread}
        onOpenCheckIn={() => setDetailMode("checkin")}
        onOpenCourse={openCourse}
        onOpenNotifications={() => {
          setNotifUnread(false);
          setDetailMode("notifications");
        }}
      />
    );
  }

  return (
    <>
      {view}
      {toastElement}
    </>
  );
}

Object.assign(window, {
  StudentMobileView,
  studentCourses
});
