// All screens

// ============== HOME ==============
const HomeScreen = ({ go }) => {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {/* Hero greeting */}
      <div className="card tint-purple" style={{ display: "flex", alignItems: "center", gap: 24, overflow: "hidden", paddingRight: 0 }}>
        <div style={{ flex: 1 }}>
          <span className="pill" style={{ background: "white", marginBottom: 12 }}>
            <Icon name="fire" size={14} color="#F26666" />
            สวัสดีตอนบ่าย ☀️
          </span>
          <h1 style={{ fontSize: 38, marginTop: 10, lineHeight: 1.05 }}>
            ไปเรียนกันต่อเลย<br />
            <span style={{ color: "var(--coral-deep)" }}>{ME.name}</span>!
          </h1>
          <p style={{ fontSize: 15, fontWeight: 600, color: "var(--ink-soft)", marginTop: 10, maxWidth: 460 }}>
            วันนี้มีคลาสกับ <b>ครูพีช</b> ตอน 16:00 น. — เตรียมตัวให้พร้อมแล้วเจอกันในห้องเรียนนะ 📚✨
          </p>
          <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
            <button className="btn primary lg" onClick={() => go("classroom")}>
              <Icon name="video" size={18} color="white" />
              เข้าห้องเรียน
            </button>
            <button className="btn lg" onClick={() => go("tutors")}>
              จองคลาสใหม่
            </button>
          </div>
        </div>
        <div style={{ width: 240, position: "relative", alignSelf: "stretch" }}>
          <FloatyShapes />
          <div style={{ position: "absolute", right: 20, top: "50%", transform: "translateY(-50%)" }}>
            <Stella size={180} hat />
          </div>
        </div>
      </div>

      {/* Stats row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        <StatTile icon="🔥" value={`${ME.streak} วัน`} label="Learning Streak" color="coral" />
        <StatTile icon="⚡" value={ME.xp.toLocaleString()} label={`XP · Level ${ME.level}`} color="yellow" />
        <StatTile icon="🪙" value={ME.coins} label="Tutoro Coins" color="mint" />
        <StatTile icon="📚" value={`${ME.hoursTotal} ชม.`} label="เรียนทั้งหมด" color="purple" />
      </div>

      {/* Today's class + Subjects */}
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 18 }}>
        <div className="card tint-dark" style={{ position: "relative", overflow: "hidden" }}>
          <span className="sticker" style={{ position: "absolute", top: -10, right: 16, background: "var(--coral)", color: "white" }}>
            🔴 LIVE เร็วๆ นี้
          </span>
          <div style={{ fontSize: 13, fontWeight: 700, color: "rgba(255,255,255,0.7)", marginBottom: 6 }}>
            คลาสถัดไป · {TODAY_CLASS.startsIn}
          </div>
          <h2 style={{ fontSize: 24, color: "white" }}>{TODAY_CLASS.subject}</h2>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 14 }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: "var(--yellow)", border: "2px solid white", display: "grid", placeItems: "center", fontSize: 22 }}>
              👩‍🏫
            </div>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14, color: "white" }}>{TODAY_CLASS.tutorName}</div>
              <div style={{ fontSize: 12, color: "rgba(255,255,255,0.7)" }}>{TODAY_CLASS.time}</div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 18 }}>
            <button className="btn primary" onClick={() => go("classroom")}>
              <Icon name="play" size={14} color="white" />
              เข้าห้อง
            </button>
            <button className="btn ghost" style={{ color: "white", borderColor: "rgba(255,255,255,0.3)" }}>
              <Icon name="chat" size={14} color="white" />
              ทักครู
            </button>
          </div>
        </div>

        <div className="card">
          <SectionHeader
            title="หมวดวิชา"
            action={<button className="btn sm ghost" onClick={() => go("tutors")}>ทั้งหมด →</button>}
          />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            {SUBJECTS.slice(0, 8).map(s => (
              <button
                key={s.id}
                onClick={() => go("tutors")}
                style={{
                  background: `var(--${s.color})`,
                  border: "2px solid var(--ink)",
                  borderRadius: 16,
                  padding: "14px 8px",
                  cursor: "pointer",
                  boxShadow: "0 2px 0 var(--ink)",
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
                  fontFamily: "Baloo 2", fontWeight: 700
                }}
              >
                <span style={{ fontSize: 26 }}>{s.icon}</span>
                <span style={{ fontSize: 12 }}>{s.name}</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Featured tutors */}
      <div>
        <SectionHeader
          title="ครูแนะนำสำหรับเธอ"
          sub="คัดมาแล้วโดยพี่ Stella จากความสนใจของน้อง"
          action={<button className="btn sm ghost" onClick={() => go("tutors")}>ดูทั้งหมด →</button>}
        />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
          {TUTORS.slice(0, 3).map(t => (
            <TutorCard key={t.id} tutor={t} onClick={() => go("tutor", { tutorId: t.id })} />
          ))}
        </div>
      </div>

      {/* Homework strip */}
      <div className="card">
        <SectionHeader
          title="การบ้านสัปดาห์นี้"
          action={<button className="btn sm ghost" onClick={() => go("homework")}>จัดการ →</button>}
        />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
          {HOMEWORK.slice(0, 4).map(h => (
            <div key={h.id} className="card flat" style={{ padding: 14, display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{
                width: 48, height: 48, borderRadius: 14,
                background: `var(--${h.color})`,
                border: "2px solid var(--ink)",
                display: "grid", placeItems: "center", fontSize: 24, flexShrink: 0
              }}>{h.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>{h.title}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11, color: "var(--muted)", fontWeight: 600 }}>
                  <span>{h.tutor}</span>
                  <span>·</span>
                  <span>ส่ง {h.due}</span>
                </div>
                <div style={{ marginTop: 6 }}>
                  <ProgressBar value={h.progress} max={100} color={h.color === "mint" ? "mint" : h.color === "sky" ? "sky" : "coral"} />
                </div>
              </div>
              {h.status === "done"
                ? <span style={{ fontSize: 22 }}>✅</span>
                : <button className="btn sm">เปิด</button>}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ============== TUTORS MARKETPLACE ==============
const TutorsScreen = ({ go }) => {
  const [filter, setFilter] = React.useState("all");
  const [sort, setSort] = React.useState("rating");
  const filtered = filter === "all"
    ? TUTORS
    : TUTORS.filter(t => t.subjectEn.toLowerCase() === filter);
  const sorted = [...filtered].sort((a, b) => {
    if (sort === "rating") return b.rating - a.rating;
    if (sort === "price-low") return a.rate - b.rate;
    if (sort === "price-high") return b.rate - a.rate;
    return b.reviews - a.reviews;
  });
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <div className="card tint-coral" style={{ position: "relative", overflow: "hidden" }}>
        <div style={{ maxWidth: 540 }}>
          <span className="pill yellow" style={{ marginBottom: 10 }}>🎯 ตลาดติวเตอร์</span>
          <h1 style={{ fontSize: 34, marginTop: 6 }}>เจอครูที่ใช่ ในไม่กี่คลิก ✨</h1>
          <p style={{ fontSize: 14, color: "var(--ink-soft)", marginTop: 8, lineHeight: 1.5 }}>
            ครูทุกคน <b>ผ่านการตรวจสอบ</b> · มีรีวิวจริง · จองเป็นชั่วโมงได้เลย ยกเลิกฟรีก่อน 6 ชม.
          </p>
        </div>
        <div style={{ position: "absolute", right: 24, top: 16, opacity: 0.8 }}>
          <Stella size={120} mood="wink" />
        </div>
      </div>

      {/* Subject chips */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
        <button
          className={`pill ${filter === "all" ? "coral" : "ghost"}`}
          style={{ cursor: "pointer", fontSize: 13, padding: "8px 14px" }}
          onClick={() => setFilter("all")}
        >
          ทั้งหมด · {TUTORS.length}
        </button>
        {SUBJECTS.slice(0, 6).map(s => (
          <SubjectChip
            key={s.id}
            subject={s}
            active={filter === s.id}
            onClick={() => setFilter(s.id === "math" ? "math" : s.id === "english" ? "english" : s.id === "science" ? "science" : s.id === "code" ? "coding" : s.id === "art" ? "art" : s.id === "social" ? "social" : s.id)}
          />
        ))}
      </div>

      {/* Sort bar */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontWeight: 700, color: "var(--ink-soft)" }}>
          พบ <span style={{ fontFamily: "Baloo 2", fontSize: 18, color: "var(--ink)" }}>{sorted.length}</span> ครู
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <span style={{ fontSize: 12, fontWeight: 700, color: "var(--muted)" }}>เรียงตาม</span>
          {[
            { id: "rating", label: "⭐ คะแนน" },
            { id: "price-low", label: "💰 ราคาต่ำ" },
            { id: "reviews", label: "💬 รีวิวเยอะ" }
          ].map(o => (
            <button
              key={o.id}
              className={`pill ${sort === o.id ? "sky" : "ghost"}`}
              style={{ cursor: "pointer", fontSize: 12, padding: "6px 12px" }}
              onClick={() => setSort(o.id)}
            >
              {o.label}
            </button>
          ))}
        </div>
      </div>

      {/* Grid */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(310px, 1fr))", gap: 18 }}>
        {sorted.map(t => (
          <TutorCard key={t.id} tutor={t} onClick={() => go("tutor", { tutorId: t.id })} />
        ))}
      </div>
    </div>
  );
};

// ============== TUTOR PROFILE + BOOKING ==============
const TutorProfile = ({ tutorId, go, onBook }) => {
  const tutor = TUTORS.find(t => t.id === tutorId) || TUTORS[0];
  const [dayIdx, setDayIdx] = React.useState(2);
  const [selectedSlot, setSelectedSlot] = React.useState(null);
  const [duration, setDuration] = React.useState(1);

  const days = ["จ.","อ.","พ.","พฤ.","ศ.","ส.","อา."];
  const dates = [14, 15, 16, 17, 18, 19, 20];

  const handleBook = () => {
    if (!selectedSlot) return;
    onBook({ tutor, dayIdx, slot: selectedSlot, duration, date: dates[dayIdx], day: days[dayIdx] });
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 22, alignItems: "start" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* Header */}
        <div className="card" style={{ padding: 24 }}>
          <button className="btn sm ghost" onClick={() => go("tutors")} style={{ marginBottom: 14 }}>
            ← กลับไปที่ตลาดติวเตอร์
          </button>
          <div style={{ display: "flex", gap: 20, alignItems: "flex-start" }}>
            <div style={{
              width: 120, height: 120, borderRadius: 32,
              background: tutor.avatarBg,
              border: "2px solid var(--ink)",
              display: "grid", placeItems: "center",
              fontSize: 64, flexShrink: 0,
              boxShadow: "var(--shadow)"
            }}>{tutor.emoji}</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                <h1 style={{ fontSize: 32 }}>{tutor.name}</h1>
                <span className="pill mint" style={{ fontSize: 12 }}>✓ ยืนยันแล้ว</span>
              </div>
              <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 10 }}>
                {tutor.subjectIcon} {tutor.subject} · ระดับชั้น {tutor.grades}
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
                <Stars value={tutor.rating} size={16} />
                <span style={{ fontSize: 13, color: "var(--muted)" }}>({tutor.reviews} รีวิว)</span>
                <span className="pill ghost">👥 {tutor.students} นักเรียน</span>
                <span className="pill ghost">⏱️ {tutor.hours} ชม.</span>
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 12 }}>
                {tutor.badges.map((b, i) => (
                  <span key={i} className="sticker" style={{ background: i === 0 ? "var(--yellow)" : "var(--mint)" }}>{b}</span>
                ))}
              </div>
            </div>
          </div>
          <p style={{ fontSize: 14, marginTop: 18, lineHeight: 1.6, color: "var(--ink-soft)" }}>
            {tutor.bio}
          </p>
        </div>

        {/* Intro video placeholder */}
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{
            aspectRatio: "16/8",
            background: `linear-gradient(135deg, ${tutor.avatarBg} 0%, #FFD668 100%)`,
            position: "relative",
            display: "grid", placeItems: "center"
          }}>
            <div style={{
              width: 80, height: 80, borderRadius: "50%",
              background: "white", border: "3px solid var(--ink)",
              display: "grid", placeItems: "center",
              boxShadow: "0 6px 0 var(--ink)",
              cursor: "pointer"
            }}>
              <Icon name="play" size={32} color="#1b1740" />
            </div>
            <span className="sticker" style={{ position: "absolute", top: 16, left: 16 }}>
              🎬 แนะนำตัว · 1:24
            </span>
          </div>
        </div>

        {/* Reviews */}
        <div className="card">
          <SectionHeader title="รีวิวจากนักเรียน" />
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {[
              { name: "น้องเมษา", grade: "ม.5", text: "ครูสอนเข้าใจง่ายมากค่ะ! ทำให้คะแนนเลขที่โรงเรียนดีขึ้นเยอะ ❤️", rating: 5, emoji: "🐰" },
              { name: "ผู้ปกครอง น้องโบ้", grade: "ม.6", text: "ครูเตรียมเอกสารดีมาก ติดตามผลลูกตลอด ใช้ LINE คุยสะดวก สบายใจ", rating: 5, emoji: "👨" },
              { name: "น้องไอซ์", grade: "ม.4", text: "สนุกมาก ไม่กลัวเลขแล้วฮะ", rating: 5, emoji: "🧊" }
            ].map((r, i) => (
              <div key={i} style={{
                padding: 14,
                borderRadius: 18,
                background: "var(--paper-2)",
                border: "2px solid var(--border)"
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                  <span style={{
                    width: 32, height: 32, borderRadius: "50%",
                    background: "white", border: "2px solid var(--ink)",
                    display: "grid", placeItems: "center", fontSize: 16
                  }}>{r.emoji}</span>
                  <div>
                    <div style={{ fontWeight: 800, fontSize: 14 }}>{r.name}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", fontWeight: 600 }}>{r.grade}</div>
                  </div>
                  <div style={{ marginLeft: "auto" }}><Stars value={r.rating} size={12} /></div>
                </div>
                <p style={{ margin: 0, fontSize: 14, color: "var(--ink-soft)" }}>{r.text}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Booking panel (sticky right) */}
      <div style={{ position: "sticky", top: 22, display: "flex", flexDirection: "column", gap: 14 }}>
        <div className="card tint-yellow">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
            <h2 style={{ fontSize: 22 }}>📅 จองคลาส</h2>
            <div style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 26 }}>
              ฿{tutor.rate}<span style={{ fontSize: 13, color: "var(--ink-soft)", fontWeight: 600 }}>/ชม.</span>
            </div>
          </div>

          {/* Days */}
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8 }}>เลือกวัน</div>
          <div style={{ display: "flex", gap: 6, marginBottom: 18 }}>
            {days.map((d, i) => (
              <div
                key={i}
                className={`day-pill ${dayIdx === i ? "active" : ""}`}
                onClick={() => { setDayIdx(i); setSelectedSlot(null); }}
              >
                <span className="d">{d}</span>
                <span className="n">{dates[i]}</span>
              </div>
            ))}
          </div>

          {/* Time slots */}
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8 }}>เลือกเวลา</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 18 }}>
            {TIMES_OF_DAY.map(period => (
              <div key={period.label}>
                <div style={{ fontSize: 11, fontWeight: 700, color: "var(--muted)", marginBottom: 6, letterSpacing: "0.06em" }}>
                  {period.label.toUpperCase()}
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                  {period.hours.map(h => {
                    const available = tutor.available.includes(h);
                    const isSelected = selectedSlot === h;
                    return (
                      <button
                        key={h}
                        className={`time-slot ${!available ? "booked" : ""} ${isSelected ? "selected" : ""}`}
                        disabled={!available}
                        onClick={() => available && setSelectedSlot(h)}
                      >
                        {String(h).padStart(2, "0")}:00
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>

          {/* Duration */}
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8 }}>จำนวนชั่วโมง</div>
          <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>
            {[1, 1.5, 2, 3].map(d => (
              <button
                key={d}
                className={`btn sm ${duration === d ? "primary" : ""}`}
                onClick={() => setDuration(d)}
                style={{ flex: 1 }}
              >
                {d} ชม.
              </button>
            ))}
          </div>

          {/* Total */}
          <div style={{
            padding: 14, borderRadius: 16,
            background: "white", border: "2px solid var(--ink)",
            marginBottom: 14
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 14, color: "var(--ink-soft)" }}>
              <span>{tutor.rate} × {duration} ชม.</span>
              <span>฿{(tutor.rate * duration).toLocaleString()}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 14, color: "var(--ink-soft)" }}>
              <span>ค่าธรรมเนียม</span>
              <span>฿0</span>
            </div>
            <div style={{ height: 2, background: "var(--border)", margin: "8px 0" }} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontFamily: "Baloo 2", fontWeight: 700, fontSize: 16 }}>รวมทั้งหมด</span>
              <span style={{ fontFamily: "Baloo 2", fontWeight: 800, fontSize: 24, color: "var(--coral-deep)" }}>
                ฿{(tutor.rate * duration).toLocaleString()}
              </span>
            </div>
          </div>

          <button
            className="btn primary lg"
            style={{ width: "100%" }}
            disabled={!selectedSlot}
            onClick={handleBook}
          >
            {selectedSlot
              ? `จอง ${String(selectedSlot).padStart(2, "0")}:00 · ${duration} ชม.`
              : "เลือกเวลาเรียน"}
            <Icon name="arrow" size={16} color="white" />
          </button>
          <div className="line-strip" style={{ marginTop: 10, justifyContent: "center" }}>
            <Icon name="line" size={16} color="white" />
            แจ้งเตือนผ่าน LINE อัตโนมัติ
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { HomeScreen, TutorsScreen, TutorProfile });
