// Presentational Home view shared by Adventure and Space Explorer.
const stxHomeDate = (day) => {
  try {
    return new Date(`${day}T00:00:00`).toLocaleDateString(
      "en-GB",
      { day: "numeric", month: "short" },
    );
  } catch (_) {
    return day || "";
  }
};

const stxLocalDay = (date = new Date()) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const StxAstronaut = () => (
  <svg
    className="stx-astronaut"
    viewBox="0 0 200 220"
    aria-hidden="true"
  >
    <defs>
      <linearGradient id="stx-suit" x1="0" y1="0" x2="1" y2="1">
        <stop stopColor="#f7f9ff"/>
        <stop offset="1" stopColor="#9aa6d6"/>
      </linearGradient>
      <linearGradient id="stx-visor" x1="0" y1="0" x2="1" y2="1">
        <stop stopColor="#26356c"/>
        <stop offset="1" stopColor="#0b1026"/>
      </linearGradient>
    </defs>
    <ellipse cx="100" cy="207" rx="57" ry="8" fill="#4de1ff" opacity=".16"/>
    <path d="M100 35V18m0 0 13-8" stroke="#4de1ff" strokeWidth="5" strokeLinecap="round"/>
    <circle cx="116" cy="8" r="7" fill="#ffc94d"/>
    <rect x="30" y="34" width="140" height="118" rx="58" fill="url(#stx-suit)"/>
    <rect
      x="39" y="43" width="122" height="94" rx="44"
      fill="#151b3b" stroke="#4de1ff" strokeWidth="5"
    />
    <rect x="54" y="58" width="92" height="62" rx="28" fill="url(#stx-visor)"/>
    <circle cx="82" cy="87" r="6" fill="#eaf0ff"/>
    <circle cx="118" cy="87" r="6" fill="#eaf0ff"/>
    <path
      d="M79 103q21 15 42 0" fill="none" stroke="#4de1ff"
      strokeWidth="5" strokeLinecap="round"
    />
    <path
      d="M44 137 24 164m132-27 20 27"
      stroke="url(#stx-suit)"
      strokeWidth="20"
      strokeLinecap="round"
    />
    <rect
      x="57"
      y="139"
      width="86"
      height="55"
      rx="22"
      fill="url(#stx-suit)"
      stroke="#4de1ff"
      strokeWidth="4"
    />
    <rect x="79" y="151" width="42" height="18" rx="7" fill="#151b3b"/>
    <circle cx="91" cy="160" r="4" fill="#ffc94d"/>
    <circle cx="109" cy="160" r="4" fill="#4de1ff"/>
    <path d="M76 190v13m48-13v13" stroke="#eaf0ff" strokeWidth="20" strokeLinecap="round"/>
    <path d="M60 207h31m18 0h31" stroke="#4de1ff" strokeWidth="9" strokeLinecap="round"/>
  </svg>
);

const StxHomeClass = ({ nextClass, student }) => {
  const [now, setNow] = React.useState(Date.now());

  React.useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(timer);
  }, []);

  if (!nextClass) return <StxEmpty>No upcoming classes yet.</StxEmpty>;

  const start = zonedMoment(nextClass.day, nextClass.time, nextClass.tz);
  const end = zonedMoment(nextClass.day, nextClass.end, nextClass.tz);
  const seconds = start ? Math.floor((start - now) / 1000) : Infinity;
  const ended = end ? end <= now : false;
  const canJoin = !ended && seconds <= 300 && !!nextClass.meet;
  const countdown = Number.isFinite(seconds) && seconds > 0
    ? `${String(Math.floor(seconds / 60)).padStart(2, "0")}:` +
      String(seconds % 60).padStart(2, "0")
    : "Live now";
  const courseParts = String(nextClass.course || "Class session").split(/\s*·\s*/);
  const courseName = courseParts.shift();
  const courseLevel = nextClass.level || courseParts.join(" · ");
  const sessionLabel = nextClass.session_label
    || (nextClass.session_number && nextClass.session_total
      ? `Session ${nextClass.session_number} of ${nextClass.session_total}`
      : "");

  return (
    <div className="stx-class-row">
      <StxIconTile tint={2} icon={stxIcon("video", 28)}/>
      <div className="stx-class-info">
        <h3>
          <span>{courseName}</span>
          {courseLevel && <StxChip>{courseLevel}</StxChip>}
        </h3>
        <p>
          {student.batch || "Individual"}
          {student.teacher ? ` · ${student.teacher}` : ""}
        </p>
        <p>
          {stxHomeDate(nextClass.day)} · {nextClass.time}
        </p>
        {sessionLabel && <StxChip>{sessionLabel}</StxChip>}
        {seconds <= 900 && !ended && <StxChip>{countdown}</StxChip>}
      </div>
      {canJoin ? (
        <a
          className="stx-btn stx-btn-primary"
          href={normalizeUrl(nextClass.meet)}
          target="_blank"
          rel="noreferrer"
        >
          Join
        </a>
      ) : nextClass.meet ? (
        <div className="stx-class-action">
          <button
            type="button"
            className="stx-btn stx-btn-primary stx-disabled"
            aria-disabled="true"
            disabled
          >
            Join
          </button>
          {!ended && seconds > 300 && <small>Opens 5 min before class</small>}
        </div>
      ) : (
        <StxPill tone="warning">No meeting link</StxPill>
      )}
    </div>
  );
};

const StxHomeView = ({
  student,
  leaderboard,
  nextClass,
  attendance,
  stats,
  session,
  go,
  nav,
}) => {
  const theme = useStx().theme;
  const xp = student.xp || 0;
  const level = Math.floor(xp / 500) + 1;
  const xpLevel = xp % 500;
  const name = (student.name || session?.name || "there").split(" ")[0];
  const summary = attendance.summary || {};
  const records = (attendance.records || []).slice(0, 2);
  const attended = (summary.present || 0) + (summary.late || 0);
  const total = attended
    + (summary.missed || 0)
    + (summary.absent || 0)
    + (summary.tech_issue || 0);
  const rate = total ? attended / total * 100 : 0;
  const nextClassToday = nextClass?.day === stxLocalDay();
  const quick = [
    ["Courses", "courses", "/app/student/courses", "book"],
    ["Quizzes", "quiz", "/app/student/quiz", "quiz"],
    ["Homework", "homework", "/app/student/homework", "homework"],
    ["Progress", "progress", "/app/student/progress", "chart"],
  ].filter(([, key, path]) => (
    stxNavItems(nav).some((item) => item.key === key && item.path === path)
  ));
  const statItems = [
    ["Lessons", stats.lessons || 0, "lessons"],
    ["Quizzes", stats.quizzes || 0, "quiz"],
    ["Units", stats.units || 0, "units"],
    ["Certificates", stats.certificates || 0, "trophy"],
  ];

  return (
    <div className="stx-home stx-page">
      <section className="stx-hero">
        <div className="stx-hero-greeting">
          {theme === "playground" && typeof StxpgHeroGreeting !== "undefined" ? (
            <StxpgHeroGreeting name={name} level={level}/>
          ) : theme === "ocean" && typeof StxOceanHeroGreeting !== "undefined" ? (
            <StxOceanHeroGreeting name={name} level={level}/>
          ) : theme === "dino" && typeof StxDinoHeroGreeting !== "undefined" ? (
            <StxDinoHeroGreeting name={name} level={level}/>
          ) : (
            <>
              <StxPageTitle>
                Hey {name},
                <br/>
                let’s learn!
              </StxPageTitle>
              {theme === "space" && <StxAstronaut/>}
            </>
          )}
        </div>
        <StxCard className="stx-level">
          <h2>
            <span>Level {level}</span>
            {theme === "ocean" && typeof StxOceanCoralIcon !== "undefined" && (
              <span className="stx-ocean-coral-badge" aria-hidden="true">
                <StxOceanCoralIcon/>
              </span>
            )}
            {theme === "dino" && typeof StxDinoClawIcon !== "undefined" && (
              <span className="stx-dino-claw-badge" aria-hidden="true">
                <StxDinoClawIcon/>
              </span>
            )}
          </h2>
          <div className="stx-level-line">
            <StxProgress
              value={xpLevel}
              max={500}
              label={`Level ${level} progress`}
            />
            <b>{xpLevel.toLocaleString()} / 500 XP</b>
          </div>
        </StxCard>
        <div className="stx-hero-stats">
          <StxCard>
            <StxIconTile tint={4} icon={stxIcon("flame", 22)}/>
            <b>{(student.streak_days || 0).toLocaleString()}</b>
            <span>day streak</span>
          </StxCard>
          <StxCard>
            <StxIconTile tint={4} icon={stxIcon("coin", 22)}/>
            <b>{(student.coins ?? 0).toLocaleString()}</b>
            <span>coins</span>
          </StxCard>
          <StxCard>
            <StxIconTile tint={3} icon={stxIcon("star", 22)}/>
            <b>{xp.toLocaleString()}</b>
            <span>XP</span>
          </StxCard>
        </div>
      </section>

      <div className="stx-home-top">
        <StxCard>
          <h2>{nextClassToday ? "Today’s class" : "Next class"}</h2>
          <StxHomeClass nextClass={nextClass} student={student}/>
        </StxCard>
        <StxCard>
          <h2>Quick access</h2>
          <div className="stx-quick">
            {quick.map(([label, , path, icon], index) => (
              <button type="button" key={path} onClick={() => go(path)}>
                <StxIconTile tint={index + 1} icon={stxIcon(icon, 27)}/>
                <b>{label}</b>
              </button>
            ))}
          </div>
        </StxCard>
      </div>

      <div className="stx-home-lower">
        <StxCard className="stx-attendance">
          <h2>Attendance</h2>
          <div className="stx-attendance-summary">
            <StxDonut value={rate} empty={!total}/>
            <div>
              {records.length ? records.map((record) => {
                const present = record.status === "present" || record.status === "late";
                const pending = record.status === "pending";
                return (
                  <div className="stx-attendance-record" key={record.session_id}>
                    <b>{stxHomeDate(record.day)}</b>
                    <StxPill tone={pending ? "warning" : present ? "success" : "danger"}>
                      <span className="stx-status-icon" aria-hidden="true">
                        {pending ? "•" : stxIcon(present ? "check" : "close", 14)}
                      </span>
                      {pending ? "Pending" : present ? "Present" : "Absent"}
                    </StxPill>
                  </div>
                );
              }) : (
                <StxEmpty>No classes yet</StxEmpty>
              )}
            </div>
          </div>
          <p>{total ? `${attended} of ${total} attended` : "No marked classes yet"}</p>
        </StxCard>

        <StxCard>
          <h2>Top students</h2>
          <StxChip className="stx-batch-chip">{student.batch || "Your class"}</StxChip>
          <div className="stx-leaderboard">
            {leaderboard.length ? leaderboard.slice(0, 8).map((entry) => (
              <div
                key={entry.id}
                className={entry.id === student.id ? "stx-you" : ""}
              >
                <span>{entry.rank}</span>
                <Avatar
                  name={entry.name?.[0] || "S"}
                  color={entry.color || "var(--stx-primary)"}
                  size={34}
                />
                <b>
                  {entry.name?.split(" ")[0]}{" "}
                  {entry.id === student.id && <small>(you)</small>}
                </b>
                <strong>{(entry.xp || 0).toLocaleString()} XP</strong>
              </div>
            )) : (
              <StxEmpty>No classmates yet</StxEmpty>
            )}
          </div>
        </StxCard>

        <StxCard>
          <h2>My stats</h2>
          <div className="stx-my-stats">
            {statItems.map(([label, value, icon], index) => (
              <div key={label}>
                <StxIconTile tint={index + 1} icon={stxIcon(icon, 22)}/>
                <b>{value.toLocaleString()}</b>
                <span>{label}</span>
              </div>
            ))}
          </div>
        </StxCard>
      </div>
    </div>
  );
};

window.StxHomeView = StxHomeView;
