// Main App + Navigation + Right Rail + Booking Modal

const BookingConfirmModal = ({ booking, onClose, onGo }) => {
  if (!booking) return null;
  const { tutor, slot, duration, date, day } = booking;
  return (
    <div style={{
      position: "fixed", inset: 0, background: "rgba(27, 23, 64, 0.4)",
      display: "grid", placeItems: "center", zIndex: 100,
      animation: "pop 0.3s ease",
      backdropFilter: "blur(4px)"
    }}
    onClick={onClose}
    >
      <div className="card" style={{
        maxWidth: 480, width: "92%",
        padding: 32,
        position: "relative",
        animation: "pop 0.4s cubic-bezier(.5,1.6,.4,1)",
        background: "white"
      }}
      onClick={e => e.stopPropagation()}
      >
        <Confetti count={40} />
        <button
          onClick={onClose}
          style={{
            position: "absolute", top: 12, right: 12,
            width: 36, height: 36, borderRadius: "50%",
            border: "2px solid var(--ink)", background: "white",
            cursor: "pointer", display: "grid", placeItems: "center"
          }}
        ><Icon name="close" size={16} /></button>

        <div style={{ textAlign: "center", marginBottom: 18, position: "relative", zIndex: 1 }}>
          <Stella size={140} hat />
          <span className="sticker" style={{
            position: "absolute", top: 12, right: 60,
            background: "var(--mint)", transform: "rotate(8deg)"
          }}>🎉 จองสำเร็จ!</span>
        </div>

        <h2 style={{ fontSize: 28, textAlign: "center", marginBottom: 6 }}>
          จองคลาสสำเร็จ!
        </h2>
        <p style={{ textAlign: "center", color: "var(--ink-soft)", fontSize: 14, fontWeight: 600, marginBottom: 18 }}>
          เราจะส่งแจ้งเตือนถึงเธอ ก่อนคลาสเริ่ม 30 นาที ผ่าน <b style={{ color: "#06C755" }}>LINE</b> นะ! 📩
        </p>

        <div style={{
          padding: 18, borderRadius: 18,
          background: "var(--paper-2)",
          border: "2px solid var(--ink)",
          marginBottom: 18
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
            <div style={{
              width: 52, height: 52, borderRadius: 16,
              background: tutor.avatarBg, border: "2px solid var(--ink)",
              display: "grid", placeItems: "center", fontSize: 28
            }}>{tutor.emoji}</div>
            <div>
              <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 17 }}>{tutor.name}</div>
              <div style={{ fontSize: 12, color: "var(--muted)", fontWeight: 700 }}>{tutor.subjectIcon} {tutor.subject}</div>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, fontSize: 13 }}>
            <div>
              <div style={{ color: "var(--muted)", fontWeight: 700, fontSize: 11 }}>📅 วันที่</div>
              <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 16 }}>{day} {date} พ.ค.</div>
            </div>
            <div>
              <div style={{ color: "var(--muted)", fontWeight: 700, fontSize: 11 }}>⏰ เวลา</div>
              <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 16 }}>{String(slot).padStart(2, "0")}:00 · {duration} ชม.</div>
            </div>
            <div>
              <div style={{ color: "var(--muted)", fontWeight: 700, fontSize: 11 }}>💰 รวม</div>
              <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 16, color: "var(--coral-deep)" }}>฿{(tutor.rate * duration).toLocaleString()}</div>
            </div>
            <div>
              <div style={{ color: "var(--muted)", fontWeight: 700, fontSize: 11 }}>🎁 รับ</div>
              <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 16 }}>+{Math.round(50 * duration)} XP</div>
            </div>
          </div>
        </div>

        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn" style={{ flex: 1 }} onClick={() => { onClose(); onGo("schedule"); }}>
            ดูตารางเรียน
          </button>
          <button className="btn primary" style={{ flex: 1 }} onClick={() => { onClose(); onGo("chat"); }}>
            <Icon name="line" size={14} color="white" /> ทักครูใน LINE
          </button>
        </div>
      </div>
    </div>
  );
};

// Right rail — context-aware
const RightRail = ({ screen, go }) => {
  return (
    <aside className="right-rail">
      {/* Mascot */}
      <div className="card tint-purple" style={{ textAlign: "center", padding: 18, position: "relative" }}>
        <Stella size={100} mood="wink" hat />
        <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 16, marginTop: 6 }}>Stella บอกว่า...</div>
        <p style={{ fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.5, margin: "6px 0 0", fontWeight: 600 }}>
          "วันนี้พักทำการบ้านเลขก่อนคลาส 16:00 ดีมั้ย? ใช้เวลาแค่ 25 นาที! 💪"
        </p>
        <button className="btn sm primary" style={{ marginTop: 10 }}>
          เริ่มเลย <Icon name="arrow" size={12} color="white" />
        </button>
      </div>

      {/* Today */}
      <div>
        <div style={{ fontSize: 11, fontWeight: 800, color: "var(--muted)", letterSpacing: "0.1em", marginBottom: 10 }}>วันนี้ · พฤ. 15 พ.ค.</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div className="card flat" style={{ padding: 14, background: "var(--yellow)" }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: "var(--ink-soft)" }}>16:00 · 1 ชม.</div>
            <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 15 }}>🧮 Math กับครูพีช</div>
            <button className="btn sm primary" style={{ marginTop: 8, width: "100%" }} onClick={() => go("classroom")}>
              <Icon name="play" size={12} color="white" /> เข้าห้อง
            </button>
          </div>
        </div>
      </div>

      {/* Next up */}
      <div>
        <div style={{ fontSize: 11, fontWeight: 800, color: "var(--muted)", letterSpacing: "0.1em", marginBottom: 10 }}>มาถึงต่อไป</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {UPCOMING.slice(1).map((u, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: 8, borderRadius: 12, background: "var(--paper-2)" }}>
              <div style={{
                width: 38, textAlign: "center",
                padding: 4, borderRadius: 10,
                background: `var(--${u.color})`, border: "2px solid var(--ink)"
              }}>
                <div style={{ fontSize: 9, fontWeight: 800 }}>{u.day}</div>
                <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 14, lineHeight: 1 }}>{u.date}</div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 700 }}>{u.subject}</div>
                <div style={{ fontSize: 10, color: "var(--muted)", fontWeight: 600 }}>{u.tutor} · {u.time}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* LINE */}
      <div className="line-strip" style={{ flexDirection: "column", alignItems: "flex-start", gap: 6, padding: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Icon name="line" size={18} color="white" />
          <span style={{ fontSize: 13 }}>เชื่อมต่อ LINE</span>
        </div>
        <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.9 }}>
          แจ้งเตือนคลาส · ส่งการบ้าน · คุยกับครู ทั้งหมดผ่าน LINE
        </div>
        <button className="btn sm" style={{ background: "white", color: "#06C755", marginTop: 4 }}>
          จัดการ →
        </button>
      </div>
    </aside>
  );
};

// =============== Viewport detection ===============
const useIsMobile = (breakpoint = 768) => {
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== "undefined" ? window.innerWidth < breakpoint : false
  );
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < breakpoint);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [breakpoint]);
  return isMobile;
};

// =============== APP ===============
const App = () => {
  const [screen, setScreen] = React.useState("home");
  const [params, setParams] = React.useState({});
  const [booking, setBooking] = React.useState(null);
  const isMobile = useIsMobile();

  const go = (s, p = {}) => {
    setScreen(s);
    setParams(p);
    window.scrollTo(0, 0);
  };

  if (isMobile) {
    return (
      <>
        <MobileApp booking={booking} setBooking={setBooking} />
        {booking && (
          <BookingConfirmModal
            booking={booking}
            onClose={() => setBooking(null)}
            onGo={() => setBooking(null)}
          />
        )}
      </>
    );
  }

  const nav = [
    { id: "home", label: "หน้าหลัก", icon: "home" },
    { id: "tutors", label: "ตลาดติวเตอร์", icon: "search" },
    { id: "schedule", label: "ตารางเรียน", icon: "calendar" },
    { id: "classroom", label: "ห้องเรียน", icon: "video", badge: "LIVE" },
    { id: "homework", label: "การบ้าน", icon: "homework", badge: "2" },
    { id: "chat", label: "แชท / LINE", icon: "chat", badge: "3" },
    { id: "rewards", label: "รางวัล", icon: "trophy" }
  ];

  return (
    <div className="app">
      {/* Sidebar */}
      <aside className="sidebar">
        <div className="logo">
          <div className="mark">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="white">
              <path d="m12 2 2.9 6.6 7.1.7-5.4 4.9 1.6 7L12 17.8 5.8 21.2l1.6-7L2 9.3l7.1-.7Z" />
            </svg>
          </div>
          <div>
            <h1>Tutoro</h1>
            <small>เรียนสนุก เก่งจริง</small>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          {nav.map(n => (
            <div
              key={n.id}
              className={`nav-item ${screen === n.id || (n.id === "tutors" && screen === "tutor") ? "active" : ""}`}
              onClick={() => go(n.id)}
            >
              <div className="ico"><Icon name={n.icon} size={18} /></div>
              <span>{n.label}</span>
              {n.badge && <span className="badge">{n.badge}</span>}
            </div>
          ))}
        </div>
        <div className="profile-card">
          <div className="avi">{ME.emoji}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <b style={{ display: "block" }}>{ME.name}</b>
            <div className="lv">⭐ Lv.{ME.level} · 🔥 {ME.streak}d</div>
          </div>
          <button className="icon-btn" style={{ width: 32, height: 32 }}>
            <Icon name="settings" size={14} />
          </button>
        </div>
      </aside>

      {/* Main */}
      <main className="main">
        {/* Topbar */}
        <div className="topbar">
          <div className="search">
            <Icon name="search" size={18} color="#8b87a8" />
            <input placeholder="ค้นหาครู, วิชา, การบ้าน..." />
            <span className="kbd">⌘ K</span>
          </div>
          <button className="icon-btn">
            <Icon name="bell" size={20} />
            <span className="dot"></span>
          </button>
          <button className="icon-btn" style={{ background: "var(--yellow)" }}>
            🪙
          </button>
        </div>

        {screen === "home" && <HomeScreen go={go} />}
        {screen === "tutors" && <TutorsScreen go={go} />}
        {screen === "tutor" && <TutorProfile tutorId={params.tutorId} go={go} onBook={setBooking} />}
        {screen === "schedule" && <ScheduleScreen go={go} />}
        {screen === "classroom" && <ClassroomScreen go={go} />}
        {screen === "chat" && <ChatScreen go={go} />}
        {screen === "homework" && <HomeworkScreen go={go} />}
        {screen === "rewards" && <RewardsScreen go={go} />}
      </main>

      {/* Right rail */}
      <RightRail screen={screen} go={go} />

      {booking && (
        <BookingConfirmModal
          booking={booking}
          onClose={() => setBooking(null)}
          onGo={go}
        />
      )}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
