// src/features/student/ui/student-home.jsx
//
// The main logged-in view for a student: upcoming + past lessons, my
// instructors, profile editor. Extracted from student-dashboard.jsx
// for size (was lines 875-1319 there).
//
// Depends on (via window): AvailabilityStep.
// Public: window.StudentHome.

const { AvailabilityStep } = window;

const StudentLessonRow = ({ b, onReschedule }) => (
  <div style={{ padding:'14px clamp(14px, 4vw, 20px)', borderTop:'1px solid oklch(95% 0.004 60)', background:'#fff', opacity:(new Date(b.scheduledAt) < new Date()) ? 0.7 : 1 }}>
    <div style={{ display:'flex', alignItems:'center', gap:10, justifyContent:'space-between', flexWrap:'wrap' }}>
      <div style={{ minWidth:0, flex:'1 1 auto' }}>
        <div style={{ fontSize:'clamp(15px, 4vw, 17px)', fontWeight:700, color:'oklch(18% 0.03 265)', lineHeight:1.2 }}>
          {stdFmtDate(b.scheduledAt)}
        </div>
        <div style={{ fontSize:13.5, color:'oklch(58% 0.03 265)', marginTop:3 }}>
          {stdHFromIso(b.scheduledAt)} · {b.durationMinutes} min
        </div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:6, flexWrap:'wrap', justifyContent:'flex-end' }}>
        {(new Date(b.scheduledAt) < new Date()) ? (
          <span style={{ fontSize:11.5, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.05em', color:'oklch(58% 0.03 265)' }}>Done</span>
        ) : (b.status !== 'cancelled' && !b.rescheduleRequestedAt && onReschedule && (
          <button onClick={() => onReschedule(b)}
            style={{ background:'none', border:'none', padding:'6px 4px', fontSize:12, fontWeight:500, color:'oklch(48% 0.04 265)', cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", textDecoration:'underline', textUnderlineOffset:3 }}
            title="Reschedule">Reschedule</button>
        ))}
      </div>
    </div>
    {b.rescheduleRequestedAt && (
      <div style={{ marginTop:10, fontSize:13, color:'oklch(36% 0.1 75)', background:'oklch(96.5% 0.07 80)', borderRadius:10, padding:'9px 14px', lineHeight:1.55, borderLeft:'3px solid oklch(72% 0.13 80)' }}>
        Reschedule requested for <strong>{stdFmtDate(b.rescheduleRequestedAt)} at {stdHFromIso(b.rescheduleRequestedAt)}</strong>. Waiting for instructor.
      </div>
    )}
    {b.message && (
      <div style={{ marginTop:10, fontSize:14, color:'oklch(40% 0.04 265)', background:'oklch(97.5% 0.007 60)', borderRadius:10, padding:'10px 14px', lineHeight:1.6, borderLeft:'3px solid oklch(72% 0.12 265)' }}>
        <span style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(52% 0.04 265)', display:'block', marginBottom:4 }}>Note</span>
        {b.message}
      </div>
    )}
  </div>
);

const StudentHome = ({ onBack }) => {
  const data = window.useDashboardData();
  const auth = window.useAuth();
  const [showBooking,     setShowBooking]     = React.useState(false);
  const [rescheduleTarget, setRescheduleTarget] = React.useState(null);
  const [showBlock,       setShowBlock]       = React.useState(false);
  const [showAvail,       setShowAvail]       = React.useState(false);
  // Viewer TZ = student's current browser zone, used for projecting the
  // displayed availability hours. Calendly-style: detected on mount, the
  // TimezoneBadge dropdown can override for this session, override is
  // session-only (not written to profile, since profile.timezone is the
  // anchor for the saved hours — not a viewing preference).
  const [viewerTz, setViewerTz] = React.useState(() => window.Calendar.time.detect());
  // The availability panel (view + edit) and all its draft state lives in
  // student-home-availability.jsx as <window.StudentAvailabilityPanel>.

  // Live-refresh: 8s polling that matches the instructor dashboard
  // (see instructor-schedule-list.jsx). logic.js already wires realtime
  // postgres_changes for bookings + availability_slots, but those events
  // are RLS-aware and don't always fire — polling is the bulletproof
  // backstop. Cheap because the student's row set is tiny.
  React.useEffect(() => {
    if (!auth.user?.id && !data.impersonating) return;
    const tick = () => { if (data?.refresh) data.refresh(); };
    tick();
    const id = setInterval(tick, 8000);
    return () => clearInterval(id);
  }, [auth.user?.id, data.impersonating]);

  // When the admin is in View-As mode the auth.profile is the admin's
  // row (or null); use the impersonated student's name instead so the
  // greeting + every other "{name}" reference shows the student we're
  // viewing, not the admin who's viewing them.
  const name = (data.impersonating && data.subjectProfile?.full_name)
    || auth.profile?.full_name
    || data.studentInfo?.phone
    || 'You';
  const topic = data.studentInfo?.topicsOfInterest?.[0] || '';
  const assignment = data.studentAssignments[0];
  const instructor = assignment?.instructor || null;

  const now = new Date();
  const today = new Date(); today.setHours(0,0,0,0);
  // Students see THIS week + NEXT week (Monday→Sunday each). "This week"
  // includes the classes they've already had this week (shown as "Done"),
  // not just the ones still to come. Anything before this Monday, or beyond
  // next week, is hidden. (Joe, 2026-06-04.)
  const monday = new Date(today);
  monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7));
  const nextMonday = new Date(+monday + 7  * 86400000);
  const weekAfter  = new Date(+monday + 14 * 86400000);
  const allBookings = (data.studentBookings || [])
    .filter(b => b.status !== 'cancelled')
    .slice()
    .sort((a, b) => new Date(a.scheduledAt) - new Date(b.scheduledAt));
  const inWindow = allBookings.filter(b => { const d = new Date(b.scheduledAt); return d >= monday && d < weekAfter; });
  const lessonGroups = [
    { key:'this-week', label:'This week', items: inWindow.filter(b => new Date(b.scheduledAt) <  nextMonday) },
    { key:'next-week', label:'Next week', items: inWindow.filter(b => new Date(b.scheduledAt) >= nextMonday) },
  ].filter(g => g.items.length);
  // Hero highlights the soonest lesson still to come within the window.
  const nextLesson = inWindow.find(b => new Date(b.scheduledAt) >= now);
  const canBook = (() => {
    const everBooked = (data.studentBookings || []).some(b => b.usesCredit);
    const balance    = data.studentInfo?.classesBalance ?? 0;
    return !everBooked || balance > 0;
  })();
  const daysUntil  = nextLesson ? Math.max(0, Math.round((new Date(new Date(nextLesson.scheduledAt).setHours(0,0,0,0)) - today) / 86400000)) : null;

  const requestReschedule = async (newIso) => {
    try {
      await data.requestReschedule(rescheduleTarget.id, newIso);
      setRescheduleTarget(null);
    } catch (e) { throw e; }
  };

  const hr = new Date().getHours();
  const greeting = hr < 12 ? 'Good morning' : hr < 17 ? 'Good afternoon' : 'Good evening';

  if (showBooking && instructor) {
    return <window.InstructorBookingPage
      instructor={instructor}
      assignment={assignment}
      asStudent={true}
      onBack={() => { setShowBooking(false); data.refresh(); }}
    />;
  }
  // Reschedule reuses the same Calendly month-view page — full takeover, not
  // the old week-of-chips modal.
  if (rescheduleTarget && instructor) {
    return <window.InstructorBookingPage
      instructor={instructor}
      assignment={assignment}
      asStudent={true}
      reschedule={{
        bookingId: rescheduleTarget.id,
        originalIso: rescheduleTarget.scheduledAt,
        onSubmit: async (newIso) => {
          await data.requestReschedule(rescheduleTarget.id, newIso);
        },
      }}
      onBack={() => { setRescheduleTarget(null); data.refresh(); }}
    />;
  }

  const card = (children, mb=20) => (
    <div style={{ background:'#fff', borderRadius:18, padding:'22px clamp(16px, 5vw, 24px)', marginBottom:mb, border:'1px solid oklch(91% 0.01 265)', boxShadow:'0 2px 12px oklch(18% 0.06 265 / 0.05)' }}>{children}</div>
  );
  const sectionLabel = (txt) => (
    <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.1em', color:'oklch(62% 0.03 265)', marginBottom:14 }}>{txt}</div>
  );

  const studio = instructor?.studio || null;
  // Online flag (admin sets it on the student row): when true we surface
  // the meeting link prominently and skip the physical-studio block since
  // those students don't have a studio location.
  const isOnline    = data.studentInfo?.isOnline === true;
  const meetingLink = data.studentInfo?.meetingLink || '';
  const studioPhone = studio?.phone || null;

  return (
    <div style={{ minHeight:'100vh', background:'oklch(98.5% 0.007 60)', fontFamily:"'Plus Jakarta Sans', sans-serif", paddingBottom:60 }}>

      {/* Header — two rows on mobile, single row on desktop. flexWrap
          allows graceful collapse without horizontal scroll at 375px. */}
      <div style={{ background:'#fff', borderBottom:'1px solid oklch(92% 0.01 265)', padding:'10px clamp(14px, 4vw, 20px)', minHeight:60, display:'flex', alignItems:'center', justifyContent:'space-between', gap:10, flexWrap:'wrap', rowGap:6 }}>
        <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:20, fontWeight:700, letterSpacing:'0.12em', color:'oklch(22% 0.06 265)', whiteSpace:'nowrap', flexShrink:0 }}>COACHING</div>
        <window.StudentAccountMenu
          name={name}
          onOpenAvailability={() => setShowAvail(true)}
          onSignOut={onBack}
        />
      </div>

      <div style={{ maxWidth:560, margin:'0 auto', padding:'24px clamp(14px, 4vw, 20px) 40px' }}>

        <div style={{ marginBottom:24 }}>
          <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:'clamp(24px, 7vw, 30px)', fontWeight:600, color:'oklch(18% 0.03 265)', lineHeight:1.15, wordBreak:'break-word' }}>
            {greeting}, {name.split(' ')[0]}
          </div>
        </div>

        {/* Layout order (post-booking matters most): the focus is the
            upcoming lesson IF one exists. Only when there's nothing on the
            calendar do we lead with the book button. Previously the book
            button was always first, which after booking pushed the new
            lesson down the page and made it feel like nothing happened —
            and the disabled "Out of classes" copy was scary. */}

        {/* 1) Hero: next lesson if any. Reschedule is the only action —
            Joe sends the meeting link himself, so there's no Join button,
            and students can't self-cancel (they reschedule instead). */}
        {nextLesson && (
          <div style={{ background:'oklch(22% 0.06 265)', borderRadius:18, padding:'22px clamp(18px, 5vw, 24px)', marginBottom:18 }}>
            {sectionLabel('Next lesson')}
            <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:'clamp(24px, 6.5vw, 30px)', fontWeight:700, color:'#fff', marginBottom:3, lineHeight:1.15 }}>
              {stdFmtDate(nextLesson.scheduledAt)}
            </div>
            <div style={{ fontSize:'clamp(14px, 4vw, 17px)', color:'rgba(255,255,255,0.72)', marginBottom:14, lineHeight:1.4 }}>
              {stdHFromIso(nextLesson.scheduledAt)} · {window.MASTERY.maskTeacherName(nextLesson.instructor?.name) || topic}
              {daysUntil === 0 && <span style={{ marginLeft:10, fontWeight:700, color:'oklch(72% 0.17 80)' }}>Today</span>}
              {daysUntil === 1 && <span style={{ marginLeft:10, fontWeight:700, color:'oklch(72% 0.17 80)' }}>Tomorrow</span>}
              {daysUntil > 1  && <span style={{ marginLeft:10, color:'rgba(255,255,255,0.5)' }}>In {daysUntil} days</span>}
            </div>
            {nextLesson.rescheduleRequestedAt && (
              <div style={{ background:'rgba(255,255,255,0.12)', borderRadius:10, padding:'10px 14px', marginBottom:18, fontSize:13, color:'rgba(255,255,255,0.92)', lineHeight:1.55 }}>
                Reschedule pending — you asked to move this to <strong>{stdFmtDate(nextLesson.rescheduleRequestedAt)} at {stdHFromIso(nextLesson.rescheduleRequestedAt)}</strong>. Waiting for your instructor to confirm.
              </div>
            )}
            {instructor && !nextLesson.rescheduleRequestedAt && (
              <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
                <button onClick={() => setRescheduleTarget(nextLesson)}
                  style={{ background:'none', color:'rgba(255,255,255,0.78)', border:'none', padding:'10px 4px', fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", textDecoration:'underline', textUnderlineOffset:3 }}>
                  Reschedule
                </button>
              </div>
            )}
          </div>
        )}

        {/* 3) Friendly empty-state only when there really is no upcoming
            lesson AND no instructor yet. With an instructor the book button
            above is enough — we don't also need a "No upcoming lessons"
            card because we already showed one of the two more useful cards. */}
        {!nextLesson && !instructor && card(
          <>
            <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:22, fontWeight:600, color:'oklch(28% 0.05 265)', marginBottom:14 }}>No upcoming lessons yet</div>
            <div style={{ fontSize:15, color:'oklch(52% 0.03 265)', lineHeight:1.7 }}>You'll see your upcoming lessons here once your tutor is assigned.</div>
          </>
        )}

        {/* Instructor card */}
        {instructor ? card(
          <>
            {sectionLabel('Your instructor')}
            <div style={{ display:'flex', gap:16, alignItems:'center', marginBottom:16 }}>
              <div style={{ width:64, height:64, borderRadius:'50%', background:`oklch(72% 0.12 ${instructor.hue||258})`, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:"'Cormorant Garamond', serif", fontSize:24, fontWeight:700, color:'#fff', flexShrink:0 }}>
                {instructor.initials}
              </div>
              <div>
                <div style={{ fontWeight:700, fontSize:20, color:'oklch(18% 0.03 265)' }}>{window.MASTERY.maskTeacherName(instructor.name)}</div>
                <div style={{ fontSize:15, color:'oklch(44% 0.04 265)', marginTop:2 }}>{instructor.subject}</div>
              </div>
            </div>
            {isOnline && meetingLink && (
              <div style={{ fontSize:14, color:'oklch(28% 0.13 265)', marginBottom:14, lineHeight:1.5, background:'oklch(96% 0.04 265)', borderRadius:12, padding:'14px 16px', borderLeft:'4px solid oklch(60% 0.18 265)' }}>
                <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.08em', color:'oklch(40% 0.12 265)', marginBottom:6 }}>Online lesson link</div>
                <a href={meetingLink} target="_blank" rel="noopener noreferrer" style={{ color:'oklch(28% 0.13 265)', fontWeight:700, wordBreak:'break-all', textDecoration:'underline' }}>{meetingLink}</a>
              </div>
            )}
            <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
              {!isOnline && studioPhone && (
                <a href={`tel:${studioPhone.replace(/\D/g,'')}`} style={{ flex:'1 1 100px', minWidth:100, padding:'13px 6px', borderRadius:12, border:'2px solid oklch(88% 0.02 265)', background:'#fff', color:'oklch(28% 0.05 265)', fontSize:14.5, fontWeight:700, textAlign:'center', cursor:'pointer', textDecoration:'none', display:'block', minHeight:44, lineHeight:'18px' }}>
                  Call
                </a>
              )}
              {canBook && (
                <button onClick={() => setShowBooking(true)} style={{ flex:'1 1 100px', minWidth:100, padding:'13px 6px', borderRadius:12, border:'none', background:'oklch(22% 0.06 265)', color:'#fff', fontSize:14.5, fontWeight:700, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", minHeight:44, lineHeight:'18px' }}>
                  Book a class
                </button>
              )}
            </div>
          </>,
          20
        ) : card(
          <>
            {sectionLabel('Your instructor')}
            <div style={{ fontSize:16, color:'oklch(52% 0.03 265)', lineHeight:1.7 }}>
              You'll soon see your instructor here.
            </div>
          </>,
          20
        )}

        {/* Lesson list */}
        <div style={{ background:'#fff', borderRadius:18, overflow:'hidden', border:'1px solid oklch(91% 0.01 265)', boxShadow:'0 2px 12px oklch(18% 0.06 265 / 0.05)', marginBottom:20 }}>
          <div style={{ padding:'18px clamp(14px, 4vw, 20px) 12px', borderBottom:'1px solid oklch(94% 0.005 60)' }}>
            <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.1em', color:'oklch(62% 0.03 265)' }}>Your lessons</div>
          </div>
          {lessonGroups.length === 0 ? (
            <div style={{ padding:'28px 24px', fontSize:16, color:'oklch(60% 0.03 265)', textAlign:'center' }}>No classes this week or next week.</div>
          ) : (
            <div style={{ display:'flex', flexDirection:'column' }}>
              {lessonGroups.map((group, gi) => (
                <div key={group.key}>
                  <div style={{
                    padding: gi === 0 ? '14px clamp(14px, 4vw, 20px) 8px' : '20px clamp(14px, 4vw, 20px) 8px',
                    fontSize:11, fontWeight:700, textTransform:'uppercase',
                    letterSpacing:'0.1em', color:'oklch(62% 0.03 265)',
                    borderTop: gi === 0 ? 'none' : '1px solid oklch(94% 0.005 60)',
                  }}>{group.label}</div>
                  {group.items.map(b => <StudentLessonRow key={b.id} b={b} onReschedule={setRescheduleTarget} />)}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Availability moved into the "My account" menu (top-right) → opens
            in the modal below. See setShowAvail + StudentAccountMenu. */}

        {/* No student-facing phone UI: the student's call number is managed
            entirely from the admin dashboard (Edit student → Phone). The
            student never sees or edits it. */}

      </div>

      {showBlock && auth.user && (
        <window.BlockTimeModal
          studentId={auth.user.id}
          ownerName={name}
          ownerTimezone={auth.profile?.timezone || 'America/New_York'}
          onClose={() => setShowBlock(false)}
        />
      )}

      {/* My availability — opened from the "My account" menu. Same panel that
          used to sit in the dashboard body; now in a modal so the body stays
          focused on this week's classes. */}
      {showAvail && (
        <div onClick={() => setShowAvail(false)}
          style={{ position:'fixed', inset:0, zIndex:50, background:'oklch(18% 0.06 265 / 0.45)', display:'flex', alignItems:'flex-start', justifyContent:'center', padding:'clamp(12px, 5vh, 56px) 14px', overflowY:'auto' }}>
          <div onClick={e => e.stopPropagation()} style={{ width:'100%', maxWidth:560 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12 }}>
              <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:'clamp(22px, 6vw, 28px)', fontWeight:700, color:'#fff' }}>My availability</div>
              <button onClick={() => setShowAvail(false)} aria-label="Close"
                style={{ background:'rgba(255,255,255,0.16)', border:'none', color:'#fff', borderRadius:999, width:38, height:38, fontSize:22, cursor:'pointer', lineHeight:1, flexShrink:0 }}>×</button>
            </div>
            <window.StudentAvailabilityPanel
              data={data} viewerTz={viewerTz} setViewerTz={setViewerTz}
              setShowBlock={(v) => { if (v) setShowAvail(false); setShowBlock(v); }}
            />
          </div>
        </div>
      )}
      {/* RescheduleModal removed — page-takeover render of InstructorBookingPage
          above (with reschedule prop) is the new Calendly-style flow. */}
    </div>
  );
};

// ── Portal (top-level entry, wired to Supabase auth) ────────────────

window.StudentHome = StudentHome;
