// instructor-profile.jsx — Single-instructor page with bio, reviews, calendar booking.

const InstructorProfilePage = ({ instructorId, setPage, openAuth }) => {
  const auth = window.useAuth();
  const isMobile = window.useIsMobile();
  const [instructor, setInstructor] = React.useState(null);
  const [reviews, setReviews] = React.useState([]);
  const [reviewers, setReviewers] = React.useState({});
  const [loading, setLoading] = React.useState(true);
  const [showBook, setShowBook] = React.useState(false);
  const [refreshKey, setRefreshKey] = React.useState(0);

  React.useEffect(() => {
    if (!instructorId) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      const { data: ins } = await window.supa
        .from('instructors').select('*').eq('id', instructorId).maybeSingle();
      if (cancelled) return;
      setInstructor(ins);
      const { data: revs } = await window.supa
        .from('reviews').select('*').eq('instructor_id', instructorId).order('created_at', { ascending: false });
      if (cancelled) return;
      const reviewerIds = [...new Set((revs || []).map(r => r.student_id))];
      let profilesById = {};
      if (reviewerIds.length) {
        const { data: profs } = await window.supa
          .from('profiles').select('id,full_name,avatar_initials,hue').in('id', reviewerIds);
        profilesById = Object.fromEntries((profs || []).map(p => [p.id, p]));
      }
      setReviews(revs || []);
      setReviewers(profilesById);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [instructorId, refreshKey]);

  if (loading) return <CenterMsg>Loading instructor…</CenterMsg>;
  if (!instructor) return <CenterMsg>Instructor not found. <button onClick={() => setPage('instructors')} style={linkBtnP}>Back to browse</button></CenterMsg>;

  const handleBookClick = () => {
    if (!auth.user) { openAuth && openAuth('signup'); return; }
    if (auth.profile?.role === 'instructor') { alert('Instructors cannot book their own trials.'); return; }
    setShowBook(true);
  };

  const canReview = auth.profile?.role === 'student';

  return (
    <div style={{ background: 'oklch(98% 0.008 60)', minHeight: '100vh', paddingTop: isMobile ? 70 : 100, paddingBottom: isMobile && instructor.available ? 96 : 0 }}>
      {/* Header band */}
      <section style={{ background: '#fff', borderBottom: '1px solid oklch(92% 0.01 265)', padding: isMobile ? '24px 18px' : '40px 80px' }}>
        <div style={{
          maxWidth: 1200, margin: '0 auto',
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          gap: isMobile ? 16 : 32,
          alignItems: isMobile ? 'center' : 'flex-start',
          textAlign: isMobile ? 'center' : 'left',
        }}>
          <window.Avatar initials={instructor.avatar_initials} hue={instructor.hue} size={isMobile ? 88 : 120} src={instructor.avatar_url} />
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: isMobile ? 'center' : 'flex-start', gap: 12, flexWrap: 'wrap', marginBottom: 4 }}>
              <h1 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: isMobile ? 28 : 40, fontWeight: 600, color: 'oklch(18% 0.03 265)' }}>{window.MASTERY.maskTeacherName(instructor.full_name)}</h1>
              {!instructor.available && (
                <span style={{ fontSize: 12, color: 'oklch(55% 0.03 265)', background: 'oklch(94% 0.01 265)', padding: '4px 10px', borderRadius: 20 }}>Waitlist</span>
              )}
            </div>
            <div style={{ color: 'oklch(38% 0.06 265)', fontWeight: 600, fontSize: isMobile ? 14 : 16, marginBottom: 8 }}>
              {instructor.subject} · {instructor.city}, {instructor.state}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: isMobile ? 'center' : 'flex-start', gap: 14, marginBottom: 14, flexWrap: 'wrap' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <window.Stars rating={Number(instructor.rating) || 0} size={14} />
                <span style={{ fontWeight: 700, fontSize: 14, color: 'oklch(22% 0.06 265)' }}>{Number(instructor.rating || 0).toFixed(1)}</span>
                <span style={{ fontSize: 13, color: 'oklch(55% 0.03 265)' }}>({instructor.review_count} reviews)</span>
              </span>
              <span style={{ fontSize: 13, color: 'oklch(55% 0.03 265)' }}>{(instructor.student_count || 0).toLocaleString()} students taught</span>
              <span style={{ fontSize: 13, color: 'oklch(55% 0.03 265)' }}>{instructor.experience} years of experience</span>
            </div>
            <div style={{ display: 'flex', justifyContent: isMobile ? 'center' : 'flex-start', gap: 6, flexWrap: 'wrap' }}>
              {(instructor.badges || []).map(b => <window.Badge key={b} label={b} />)}
              {(instructor.specialties || []).map(s => (
                <span key={s} style={{ fontSize: 12, color: 'oklch(42% 0.04 265)', background: 'oklch(96% 0.01 265)', padding: '3px 10px', borderRadius: 20 }}>{s}</span>
              ))}
            </div>
          </div>
          <div style={{ textAlign: isMobile ? 'center' : 'right', flexShrink: 0, width: isMobile ? '100%' : 'auto' }}>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: isMobile ? 32 : 40, fontWeight: 700, color: 'oklch(22% 0.06 265)' }}>${instructor.rate}<span style={{ fontSize: 16, fontWeight: 400 }}>/hr</span></div>
            <button onClick={handleBookClick} disabled={!instructor.available} style={{
              marginTop: 14, background: instructor.available ? 'oklch(22% 0.06 265)' : 'oklch(85% 0.01 265)',
              color: '#fff', border: 'none', borderRadius: 12,
              padding: isMobile ? '14px 0' : '14px 32px', fontWeight: 700, fontSize: 15,
              cursor: instructor.available ? 'pointer' : 'not-allowed',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
              width: isMobile ? '100%' : 'auto',
            }}>{instructor.available ? 'Book a trial lesson' : 'Currently on waitlist'}</button>
          </div>
        </div>
      </section>

      {/* Body */}
      <section style={{
        maxWidth: 1200, margin: isMobile ? '20px auto' : '40px auto',
        padding: isMobile ? '0 16px' : '0 80px',
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.5fr 1fr',
        gap: isMobile ? 16 : 36, alignItems: 'flex-start',
      }}>
        <div>
          <Card title="About">
            <p style={{ fontSize: 15, lineHeight: 1.75, color: 'oklch(32% 0.04 265)' }}>{instructor.bio || 'This instructor has not added a bio yet.'}</p>
          </Card>

          <Card title={`Reviews (${reviews.length})`}>
            {reviews.length === 0 ? (
              <p style={{ fontSize: 14, color: 'oklch(55% 0.03 265)' }}>No reviews yet. Be the first after your trial lesson.</p>
            ) : (
              reviews.map(r => {
                const rev = reviewers[r.student_id];
                return (
                  <div key={r.id} style={{ borderTop: '1px solid oklch(94% 0.01 265)', padding: '18px 0', display: 'flex', gap: 14 }}>
                    <window.Avatar initials={rev?.avatar_initials || '??'} hue={rev?.hue || 220} size={44} />
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                        <span style={{ fontWeight: 700, fontSize: 14, color: 'oklch(22% 0.06 265)' }}>{rev?.full_name || 'Anonymous'}</span>
                        <window.Stars rating={r.rating} size={12} />
                        <span style={{ fontSize: 12, color: 'oklch(55% 0.03 265)' }}>{new Date(r.created_at).toLocaleDateString()}</span>
                      </div>
                      {r.text && <p style={{ fontSize: 14, lineHeight: 1.6, color: 'oklch(35% 0.04 265)' }}>{r.text}</p>}
                    </div>
                  </div>
                );
              })
            )}
          </Card>
        </div>

        {/* Sidebar */}
        <div>
          <Card title="Weekly availability">
            <AvailabilityPreview instructorId={instructor.id} />
            <button onClick={handleBookClick} disabled={!instructor.available} style={{
              marginTop: 16, width: '100%',
              background: instructor.available ? 'oklch(22% 0.06 265)' : 'oklch(88% 0.01 265)',
              color: '#fff', border: 'none', borderRadius: 10,
              padding: '12px 0', fontWeight: 600, fontSize: 14,
              cursor: instructor.available ? 'pointer' : 'not-allowed',
              fontFamily: "'Plus Jakarta Sans', sans-serif",
            }}>Pick a time</button>
          </Card>
        </div>
      </section>

      {showBook && (
        <window.BookTrialModal
          instructor={instructor}
          onClose={() => setShowBook(false)}
          onBooked={() => { setShowBook(false); setPage('dashboard'); }}
        />
      )}

      {/* Sticky Book CTA on mobile — Airbnb pattern. Sits at the bottom and
          is always visible while the user scrolls through bio + reviews. */}
      {isMobile && instructor.available && (
        <div style={{
          position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 50,
          background: '#fff',
          borderTop: '1px solid oklch(92% 0.01 265)',
          boxShadow: '0 -6px 24px rgba(0,0,0,0.08)',
          padding: '12px 16px max(12px, env(safe-area-inset-bottom))',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 700, color: 'oklch(22% 0.06 265)', lineHeight: 1 }}>${instructor.rate}<span style={{ fontSize: 13, fontWeight: 400 }}>/hr</span></div>
            <div style={{ fontSize: 12, color: 'oklch(58% 0.03 265)', marginTop: 2 }}>Free first lesson</div>
          </div>
          <button onClick={handleBookClick} style={{
            background: 'oklch(22% 0.06 265)', color: '#fff',
            border: 'none', borderRadius: 12,
            padding: '14px 26px', fontWeight: 700, fontSize: 15,
            cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif",
            minHeight: 48,
          }}>Book trial</button>
        </div>
      )}
    </div>
  );
};

const AvailabilityPreview = ({ instructorId }) => {
  const [slots, setSlots] = React.useState([]);
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      const { data } = await window.supa
        .from('availability_slots').select('*').eq('instructor_id', instructorId)
        .order('day_of_week').order('start_time');
      if (!cancelled) setSlots(data || []);
    })();
    return () => { cancelled = true; };
  }, [instructorId]);
  if (!slots.length) return <p style={{ fontSize: 13, color: 'oklch(55% 0.03 265)' }}>This instructor hasn't set availability yet.</p>;
  const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  const grouped = {};
  slots.forEach(s => { (grouped[s.day_of_week] = grouped[s.day_of_week] || []).push(s); });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {Object.keys(grouped).map(d => (
        <div key={d} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
          <span style={{ fontWeight: 600, color: 'oklch(22% 0.06 265)' }}>{days[Number(d)]}</span>
          <span style={{ color: 'oklch(45% 0.04 265)' }}>
            {grouped[d].map(s => `${formatTime(s.start_time)}–${formatTime(s.end_time)}`).join(', ')}
          </span>
        </div>
      ))}
    </div>
  );
};

function formatTime(t) {
  const [h, m] = String(t).split(':');
  const hr = Number(h);
  const ampm = hr >= 12 ? 'pm' : 'am';
  const h12 = hr % 12 || 12;
  return `${h12}${m === '00' ? '' : ':' + m}${ampm}`;
}

const Card = ({ title, children }) => {
  const isMobile = window.useIsMobile();
  return (
    <div style={{ background: '#fff', borderRadius: 16, padding: isMobile ? 18 : 28, marginBottom: 16, border: '1px solid oklch(92% 0.01 265)' }}>
      <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: isMobile ? 19 : 22, fontWeight: 600, color: 'oklch(22% 0.06 265)', marginBottom: 14 }}>{title}</h3>
      {children}
    </div>
  );
};

const CenterMsg = ({ children }) => (
  <div style={{ paddingTop: 200, textAlign: 'center', minHeight: '60vh', fontSize: 15, color: 'oklch(40% 0.04 265)' }}>{children}</div>
);

const linkBtnP = {
  background: 'none', border: 'none', cursor: 'pointer',
  color: 'oklch(22% 0.06 265)', fontWeight: 600, textDecoration: 'underline',
  fontFamily: "'Plus Jakarta Sans', sans-serif",
};

window.InstructorProfilePage = InstructorProfilePage;
window.formatTime = formatTime;
