// screens-video.jsx — Availability settings, booking calendar, video call

// ===========================================================
//  TIME SELECT — elegant dropdown replacing <input type="time">
// ===========================================================
function TimeSelect({ value, onChange, style }) {
  // 30-minute increments from 06:00 to 23:00
  const options = [];
  for (let h = 6; h <= 23; h++) {
    for (let m = 0; m < 60; m += 30) {
      if (h === 23 && m === 30) break;
      const hh = String(h).padStart(2, '0');
      const mm = String(m).padStart(2, '0');
      options.push(`${hh}:${mm}`);
    }
  }

  return (
    <div style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', ...style }}>
      <select
        value={value}
        onChange={e => onChange(e.target.value)}
        style={{
          appearance: 'none', WebkitAppearance: 'none',
          border: '1.5px solid var(--psy-rule)',
          borderRadius: 10,
          padding: '6px 32px 6px 12px',
          fontSize: 14, fontWeight: 600,
          color: 'var(--psy-ink)',
          background: 'var(--psy-surface)',
          cursor: 'pointer',
          outline: 'none',
          width: 100,
          transition: 'border-color 120ms',
        }}
        onFocus={e => { e.target.style.borderColor = 'var(--psy-accent)'; }}
        onBlur={e => { e.target.style.borderColor = 'var(--psy-rule)'; }}
      >
        {options.map(o => (
          <option key={o} value={o}>{o}</option>
        ))}
      </select>
      {/* Chevron icon */}
      <svg
        viewBox="0 0 10 6" width="10" height="6"
        style={{ position: 'absolute', right: 10, pointerEvents: 'none', color: 'var(--fg3)' }}
        fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="1 1 5 5 9 1" />
      </svg>
    </div>
  );
}

// ===========================================================
//  AVAILABILITY SCREEN (psychologist)
// ===========================================================
function AvailabilityScreen({ setRoute }) {
  const { lang } = useLang();
  const el = lang === 'el';

  const DAY_LABELS    = ['Sunday',   'Monday',  'Tuesday', 'Wednesday', 'Thursday', 'Friday',    'Saturday'];
  const DAY_LABELS_EL = ['Κυριακή', 'Δευτέρα', 'Τρίτη',  'Τετάρτη',  'Πέμπτη',   'Παρασκευή', 'Σάββατο'];

  // Each day: { enabled, slots: [{start_time, end_time}, ...] }
  const defaultDay = () => ({ enabled: false, slots: [{ start_time: '09:00', end_time: '17:00' }] });
  const [avail, setAvail] = useState(Array.from({ length: 7 }, defaultDay));
  const [loading,   setLoading]   = useState(true);
  const [saving,    setSaving]    = useState(false);
  const [saved,     setSaved]     = useState(false);
  const [dirty,     setDirty]     = useState(false);
  const [saveError, setSaveError] = useState(null);
  const [myProfileId, setMyProfileId] = useState(null);
  const [dbDays,    setDbDays]    = useState(null); // day_of_week numbers currently in DB

  // Helper: parse availability rows into the 7-day avail array
  function rowsToAvail(rows) {
    const next = Array.from({ length: 7 }, defaultDay);
    rows.forEach(r => {
      const day = next[r.day_of_week];
      if (!day.enabled) {
        day.enabled = true;
        day.slots = [{ start_time: r.start_time, end_time: r.end_time }];
      } else {
        day.slots.push({ start_time: r.start_time, end_time: r.end_time });
      }
    });
    return next;
  }

  useEffect(() => {
    // Load availability + profile id in parallel
    Promise.all([
      API.getMyAvailability().catch(() => null),
      API.getMyProfile().catch(() => null),
    ]).then(([rows, profile]) => {
      if (Array.isArray(rows)) {
        setAvail(rowsToAvail(rows));
        setDbDays([...new Set(rows.map(r => r.day_of_week))].sort((a, b) => a - b));
      } else {
        setDbDays([]);
      }
      if (profile && profile.id) setMyProfileId(profile.id);
    }).finally(() => setLoading(false));
  }, []);

  async function save() {
    setSaving(true);
    setSaveError(null);
    try {
      const slots = avail.flatMap((a, i) =>
        a.enabled ? a.slots.map(s => ({ day_of_week: i, start_time: s.start_time, end_time: s.end_time })) : []
      );
      // Use API helper which throws on non-2xx responses
      await API.saveMyAvailability(slots);
      // Reload from DB to confirm what was actually stored
      const rows = await API.getMyAvailability();
      if (Array.isArray(rows)) {
        setAvail(rowsToAvail(rows));
        setDbDays([...new Set(rows.map(r => r.day_of_week))].sort((a, b) => a - b));
      }
      setSaved(true);
      setDirty(false);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      setSaveError(err.message || 'Save failed — please try again.');
    } finally {
      setSaving(false);
    }
  }

  function toggleDay(i) {
    setAvail(prev => prev.map((a, idx) => idx !== i ? a : { ...a, enabled: !a.enabled }));
    setDirty(true);
  }
  function setSlotTime(dayIdx, slotIdx, field, val) {
    setAvail(prev => prev.map((a, idx) => {
      if (idx !== dayIdx) return a;
      const slots = a.slots.map((s, si) => si === slotIdx ? { ...s, [field]: val } : s);
      return { ...a, slots };
    }));
    setDirty(true);
  }
  function addSlot(dayIdx) {
    setAvail(prev => prev.map((a, idx) => {
      if (idx !== dayIdx) return a;
      // default new slot starts where last one ends, +1h
      const last = a.slots[a.slots.length - 1];
      const [h] = last.end_time.split(':').map(Number);
      const start = String(Math.min(h, 22)).padStart(2, '0') + ':00';
      const end   = String(Math.min(h + 1, 23)).padStart(2, '0') + ':00';
      return { ...a, slots: [...a.slots, { start_time: start, end_time: end }] };
    }));
    setDirty(true);
  }
  function removeSlot(dayIdx, slotIdx) {
    setAvail(prev => prev.map((a, idx) => {
      if (idx !== dayIdx) return a;
      const slots = a.slots.filter((_, si) => si !== slotIdx);
      return { ...a, slots: slots.length ? slots : [{ start_time: '09:00', end_time: '17:00' }], enabled: slots.length > 0 };
    }));
    setDirty(true);
  }
  function totalSlots(day) {
    return day.slots.reduce((sum, s) => {
      const [sh, sm] = s.start_time.split(':').map(Number);
      const [eh, em] = s.end_time.split(':').map(Number);
      return sum + Math.max(0, Math.floor(((eh * 60 + em) - (sh * 60 + sm)) / 50));
    }, 0);
  }

  if (loading) return (
    <div className="page narrow" style={{ paddingTop: 80, textAlign: 'center' }}>
      <Icon name="pending" style={{ fontSize: 40, color: 'var(--fg3)' }} />
    </div>
  );

  return (
    <div className="page narrow" style={{ maxWidth: 660 }}>

      {/* Header row: back button left, title right-of-center */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 28 }}>
        <button className="btn link" style={{ fontSize: 13 }} onClick={() => setRoute('provider')}>
          <Icon name="arrow_back" className="sm" /> {el ? 'Πίσω στο dashboard' : 'Back to dashboard'}
        </button>
        <span className="eyebrow muted">{el ? 'Ρυθμίσεις' : 'Settings'}</span>
      </div>

      <div style={{ marginBottom: 32 }}>
        <h1 className="display" style={{ fontSize: 36, marginTop: 0 }}>
          {el ? 'Ώρες & Διαθεσιμότητα' : 'Availability & Hours'}
        </h1>
        <p style={{ color: 'var(--fg2)', marginTop: 8, fontSize: 15 }}>
          {el
            ? 'Ορίστε ποιες μέρες και ώρες είστε διαθέσιμοι. Μπορείτε να προσθέσετε πολλαπλά διαστήματα ανά μέρα (π.χ. πρωί + απόγευμα). Κάθε συνεδρία διαρκεί 50 λεπτά.'
            : 'Set your weekly availability. Add multiple time ranges per day (e.g. morning + afternoon). Each session is 50 minutes.'}
        </p>
      </div>


      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        {avail.map((a, i) => (
          <div key={i} style={{
            padding: '16px 20px',
            borderBottom: i < 6 ? '1px solid var(--psy-rule)' : 'none',
            background: a.enabled ? 'var(--psy-surface-2)' : 'transparent',
          }}>
            {/* Day header row: toggle + name + slot count */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              {/* Toggle */}
              <div onClick={() => toggleDay(i)} style={{
                width: 44, height: 24, borderRadius: 12, flexShrink: 0, cursor: 'pointer',
                background: a.enabled ? 'var(--psy-accent)' : 'var(--psy-rule)',
                position: 'relative', transition: 'background 150ms',
              }}>
                <div style={{
                  position: 'absolute', top: 3,
                  left: a.enabled ? 23 : 3,
                  width: 18, height: 18, borderRadius: '50%', background: 'white',
                  boxShadow: '0 1px 3px rgba(0,0,0,0.25)', transition: 'left 150ms',
                }} />
              </div>
              <span style={{ width: 100, fontWeight: 600, fontSize: 14, color: a.enabled ? 'var(--psy-ink)' : 'var(--fg3)', flexShrink: 0 }}>
                {el ? DAY_LABELS_EL[i] : DAY_LABELS[i]}
              </span>
              {a.enabled ? (
                <span style={{ fontSize: 12, color: 'var(--psy-accent)', fontWeight: 600 }}>
                  {totalSlots(a) > 0 ? `${totalSlots(a)} slots` : ''}
                </span>
              ) : (
                <span style={{ color: 'var(--fg3)', fontSize: 13 }}>
                  {el ? 'Μη διαθέσιμος/η' : 'Not available'}
                </span>
              )}
            </div>

            {/* Time slot rows (only when enabled) */}
            {a.enabled && (
              <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {a.slots.map((s, si) => (
                  <div key={si} style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 58 }}>
                    <TimeSelect
                      value={s.start_time}
                      onChange={val => setSlotTime(i, si, 'start_time', val)} />
                    <span style={{ color: 'var(--fg3)', fontSize: 13, fontWeight: 500, flexShrink: 0 }}>→</span>
                    <TimeSelect
                      value={s.end_time}
                      onChange={val => setSlotTime(i, si, 'end_time', val)} />
                    {/* Remove button (only if >1 slot) */}
                    {a.slots.length > 1 && (
                      <button
                        onClick={() => removeSlot(i, si)}
                        title={el ? 'Αφαίρεση' : 'Remove'}
                        style={{
                          background: 'none', border: 'none', cursor: 'pointer',
                          color: 'var(--fg3)', padding: '2px 4px', borderRadius: 6,
                          display: 'flex', alignItems: 'center', lineHeight: 1,
                          fontSize: 18, fontWeight: 700,
                        }}>
                        ×
                      </button>
                    )}
                  </div>
                ))}

                {/* + Add time slot */}
                <button
                  onClick={() => addSlot(i)}
                  style={{
                    marginLeft: 58, alignSelf: 'flex-start',
                    background: 'none', border: '1.5px dashed var(--psy-rule)',
                    borderRadius: 8, padding: '5px 12px', cursor: 'pointer',
                    fontSize: 12, fontWeight: 600, color: 'var(--psy-accent)',
                    display: 'flex', alignItems: 'center', gap: 4,
                    marginTop: 2,
                  }}>
                  <Icon name="add" style={{ fontSize: 14 }} />
                  {el ? 'Προσθήκη ωραρίου' : 'Add time range'}
                </button>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Error banner */}
      {saveError && (
        <div style={{
          marginTop: 16, padding: '12px 16px', borderRadius: 12,
          background: '#FEF2F2', border: '1.5px solid #FCA5A5',
          display: 'flex', alignItems: 'flex-start', gap: 10,
        }}>
          <Icon name="error" style={{ color: '#EF4444', fontSize: 20, flexShrink: 0 }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 14, color: '#991B1B', marginBottom: 2 }}>
              {el ? 'Αποτυχία αποθήκευσης' : 'Save failed'}
            </div>
            <div style={{ fontSize: 13, color: '#7F1D1D' }}>{saveError}</div>
            <div style={{ fontSize: 12, color: '#9CA3AF', marginTop: 6 }}>
              {el
                ? 'Βεβαιωθείτε ότι είστε συνδεδεμένοι και δοκιμάστε ξανά.'
                : 'Make sure you are signed in and try again. If the problem persists, sign out and sign back in.'}
            </div>
          </div>
          <button onClick={() => setSaveError(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#9CA3AF', padding: 2, fontSize: 18, lineHeight: 1 }}>×</button>
        </div>
      )}

      {/* Sticky save bar — always visible, pulses dark when dirty */}
      <div style={{
        position: 'sticky', bottom: 16, zIndex: 10,
        background: dirty ? 'var(--psy-ink)' : saveError ? '#FEF2F2' : 'var(--psy-surface)',
        border: dirty ? 'none' : saveError ? '1.5px solid #FCA5A5' : '1px solid var(--psy-rule)',
        borderRadius: 14, padding: '12px 18px',
        display: 'flex', alignItems: 'center', gap: 12,
        marginTop: 24,
        boxShadow: dirty ? '0 4px 20px rgba(15,21,37,0.3)' : '0 2px 8px rgba(15,21,37,0.06)',
        transition: 'all 0.2s',
      }}>
        {saveError && !dirty && (
          <span style={{ fontSize: 13, color: '#991B1B', flex: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="error" style={{ fontSize: 16 }} />
            {el ? 'Αποτυχία — δοκιμάστε ξανά' : 'Save failed — try again'}
          </span>
        )}
        {dirty && (
          <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.8)', flex: 1 }}>
            <Icon name="edit" style={{ fontSize: 15, verticalAlign: -2, marginRight: 5 }} />
            {el ? 'Έχετε αποθηκεύσει τις αλλαγές σας;' : 'You have unsaved changes — click Save'}
          </span>
        )}
        {saved && !dirty && !saveError && (
          <span style={{ fontSize: 13, color: 'var(--psy-leaf)', flex: 1, display: 'flex', alignItems: 'center', gap: 5 }}>
            <Icon name="check_circle" className="sm" />
            {el ? 'Αποθηκεύτηκε επιτυχώς!' : 'Saved & confirmed from database!'}
          </span>
        )}
        {!dirty && !saved && !saveError && (
          <span style={{ fontSize: 13, color: 'var(--fg3)', flex: 1 }}>
            {el ? 'Η διαθεσιμότητά σας είναι ενημερωμένη.' : 'Your availability is up to date.'}
          </span>
        )}
        <button
          onClick={save}
          disabled={saving}
          style={{
            background: dirty ? 'white' : saveError ? '#EF4444' : 'var(--psy-accent)',
            color: dirty ? 'var(--psy-ink)' : 'white',
            border: 0, borderRadius: 10,
            padding: '9px 20px', fontSize: 14, fontWeight: 600,
            cursor: saving ? 'default' : 'pointer',
            opacity: saving ? 0.6 : 1,
            whiteSpace: 'nowrap',
          }}>
          {saving
            ? (el ? 'Αποθήκευση...' : 'Saving...')
            : saveError
            ? (el ? 'Δοκιμή ξανά' : 'Retry')
            : (el ? 'Αποθήκευση' : 'Save changes')}
        </button>
      </div>

    </div>
  );
}

// ===========================================================
//  BOOKING CALENDAR SCREEN (client)
// ===========================================================
function BookingCalendarScreen({ psyId, setRoute, authUser, requireAuth, setToast }) {
  const { lang } = useLang();
  const el = lang === 'el';

  const [psy, setPsy]               = useState(null);
  const [mode, setMode]             = useState('online');   // 'online' | 'in-person'
  const [selectedDate, setSelectedDate] = useState(null);
  const [slots, setSlots]           = useState([]);
  const [loadingSlots, setLoadingSlots] = useState(false);
  const [booking, setBooking]       = useState(false);
  const [bookedResult, setBookedResult] = useState(null);
  const [availDays, setAvailDays]   = useState(null); // null=loading, number[]=day_of_week values

  useEffect(() => {
    if (!psyId) return;
    API.getPsychologist(psyId).then(d => setPsy(d)).catch(() => {});
    API.getAvailableDays(psyId)
      .then(d => {
        if (Array.isArray(d)) {
          console.log('[BookingCalendar] psyId:', psyId, '| availDays (day_of_week values):', d);
          setAvailDays(d);
        }
      })
      .catch(() => setAvailDays([]));
  }, [psyId]);

  useEffect(() => {
    if (!selectedDate || !psyId) return;
    setLoadingSlots(true);
    setSlots([]);
    API.getSlots(psyId, selectedDate)
      .then(d => { if (Array.isArray(d)) setSlots(d); })
      .catch(() => {})
      .finally(() => setLoadingSlots(false));
  }, [selectedDate, psyId]);

  // Next 14 days (skip today, start tomorrow)
  const dates = Array.from({ length: 14 }, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() + i + 1);
    const yyyy = d.getFullYear();
    const mm   = String(d.getMonth() + 1).padStart(2, '0');
    const dd   = String(d.getDate()).padStart(2, '0');
    const label = d.toLocaleDateString(el ? 'el-GR' : 'en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
    return { value: `${yyyy}-${mm}-${dd}`, label, dayOfWeek: d.getDay() };
  });

  // Auto-select first available day once we know which days have slots
  useEffect(() => {
    if (!availDays || availDays.length === 0 || selectedDate) return;
    const first = dates.find(d => availDays.includes(d.dayOfWeek));
    if (first) setSelectedDate(first.value);
  }, [availDays]);

  async function bookSlot(time) {
    if (!requireAuth(() => {})) return;
    if (booking) return;
    setBooking(true);
    try {
      const data = await API.postBooking({
        psyId, date: selectedDate, time, mode,
        psyName: psy?.name, from_calendar: true,
      });
      setBookedResult(data);
    } catch (e) {
      setToast && setToast(e.message || 'Booking failed');
    }
    setBooking(false);
  }

  // ── Success state ──────────────────────────────────────────
  if (bookedResult) {
    const isOnline = mode === 'online';
    return (
      <div className="page narrow" style={{ paddingTop: 60, textAlign: 'center', maxWidth: 520 }}>
        <div style={{ width: 72, height: 72, borderRadius: 20, background: 'var(--psy-leaf-soft)', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}>
          <Icon name="check_circle" style={{ color: 'var(--psy-leaf)', fontSize: 36 }} />
        </div>
        <h2 className="display" style={{ fontSize: 30, fontWeight: 600 }}>
          {el ? 'Κράτηση επιβεβαιώθηκε!' : 'Session booked!'}
        </h2>
        <p style={{ color: 'var(--fg2)', marginTop: 10, fontSize: 15, lineHeight: 1.55 }}>
          {el
            ? `Η συνεδρία σας με ${psy?.name} την ${selectedDate} είναι επιβεβαιωμένη.${isOnline ? ' Έχει δημιουργηθεί ασφαλής βιντεοκλήση.' : ''}`
            : `Your session with ${psy?.name} on ${selectedDate} is confirmed.${isOnline ? ' A secure video room has been created.' : ''}`}
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 28, maxWidth: 280, margin: '28px auto 0' }}>
          {isOnline && (
            <button className="btn accent" onClick={() => setRoute('video-call', { id: String(bookedResult.id) })}>
              <Icon name="videocam" className="sm" /> {el ? 'Είσοδος στο video call' : 'Join video call'}
            </button>
          )}
          <button className="btn ghost" onClick={() => setRoute('my-sessions')}>
            {el ? 'Δείτε τις συνεδρίες μου' : 'View my sessions'}
          </button>
          <button className="btn link" style={{ fontSize: 13 }} onClick={() => setRoute('home')}>
            {el ? 'Πίσω στην αρχική' : 'Back to home'}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="page narrow" style={{ maxWidth: 700 }}>
      <button className="btn link" style={{ fontSize: 13, marginBottom: 24 }}
        onClick={() => setRoute('detail', psyId)}>
        <Icon name="arrow_back" className="sm" /> {el ? 'Πίσω στο προφίλ' : 'Back to profile'}
      </button>

      {/* Psy header */}
      {psy && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20, padding: '16px 20px', background: 'var(--psy-surface)', borderRadius: 16, border: '1px solid var(--psy-rule)' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 18, flexShrink: 0,
            background: avatarBg(psy.avatarVariant),
            display: 'grid', placeItems: 'center',
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
            color: 'white', letterSpacing: '-0.02em',
            boxShadow: '0 2px 8px rgba(0,0,0,0.12)',
          }}>
            {psy.initials || '?'}
          </div>
          <div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, margin: 0 }}>{psy.name}</h2>
            <p style={{ color: 'var(--fg2)', fontSize: 13, margin: '3px 0 0' }}>
              {el ? 'Κράτηση συνεδρίας 50 λεπτών' : 'Book a 50-minute session'}
            </p>
          </div>
          <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
            <div style={{ fontWeight: 700, fontSize: 18, color: 'var(--psy-ink)' }}>
              {psy.pricePerSession ? `€${psy.pricePerSession}` : '—'}
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg3)' }}>{el ? 'ανά συνεδρία' : 'per session'}</div>
          </div>
        </div>
      )}

      {/* Mode picker — only if psychologist supports both */}
      {psy && psy.modes && psy.modes.length > 1 && (
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg2)', marginBottom: 10 }}>
            {el ? 'Μορφή συνεδρίας' : 'Session format'}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { id: 'online',     icon: 'videocam',     label: el ? 'Online' : 'Online' },
              { id: 'in-person',  icon: 'meeting_room', label: el ? 'Δια ζώσης' : 'In-person' },
            ].filter(opt => psy.modes.includes(opt.id)).map(opt => (
              <button key={opt.id}
                onClick={() => setMode(opt.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 7,
                  padding: '10px 18px', borderRadius: 12, cursor: 'pointer',
                  border: mode === opt.id ? '2px solid var(--psy-accent)' : '1.5px solid var(--psy-rule)',
                  background: mode === opt.id ? 'var(--psy-accent-soft)' : 'white',
                  color: mode === opt.id ? 'var(--psy-accent)' : 'var(--fg2)',
                  fontWeight: 600, fontSize: 14,
                }}>
                <Icon name={opt.icon} style={{ fontSize: 18 }} />
                {opt.label}
              </button>
            ))}
          </div>
          {mode === 'in-person' && (
            <p style={{ fontSize: 12, color: 'var(--fg3)', marginTop: 8, display: 'flex', gap: 5, alignItems: 'flex-start' }}>
              <Icon name="info" style={{ fontSize: 14, flexShrink: 0, marginTop: 1 }} />
              {el ? 'Η συνεδρία είναι δια ζώσης. Δεν δημιουργείται video room.' : 'In-person session. No video room will be created.'}
            </p>
          )}
        </div>
      )}

      {/* Step 1 — Date */}
      <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, marginBottom: 14 }}>
        {el ? '1. Επιλέξτε ημερομηνία' : '1. Pick a date'}
      </h3>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 32 }}>
        {dates.map(d => {
          const parts = d.label.split(' ');
          const active = selectedDate === d.value;
          const hasAvail = !availDays || availDays.includes(d.dayOfWeek);
          return (
            <button
              key={d.value}
              onClick={() => hasAvail && setSelectedDate(d.value)}
              style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center',
                gap: 2, padding: '10px 14px', borderRadius: 14,
                cursor: hasAvail ? 'pointer' : 'default',
                opacity: hasAvail ? 1 : 0.35,
                border: active ? '2px solid var(--psy-accent)' : '1.5px solid var(--psy-rule)',
                background: active ? 'var(--psy-accent-soft)' : 'white',
                minWidth: 58,
              }}>
              <span style={{ fontSize: 10, color: active ? 'var(--psy-accent)' : 'var(--fg3)', fontWeight: 600, textTransform: 'uppercase' }}>
                {parts[0]}
              </span>
              <span style={{ fontSize: 17, fontWeight: 700, color: active ? 'var(--psy-accent)' : 'var(--psy-ink)' }}>
                {parts[1]}
              </span>
              <span style={{ fontSize: 10, color: active ? 'var(--psy-accent)' : 'var(--fg3)' }}>
                {parts[2]}
              </span>
            </button>
          );
        })}
      </div>

      {/* Step 2 — Time */}
      {selectedDate && (
        <>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, marginBottom: 14 }}>
            {el ? '2. Επιλέξτε ώρα' : '2. Pick a time'}
          </h3>
          {loadingSlots ? (
            <div style={{ color: 'var(--fg3)', fontSize: 14, padding: '20px 0' }}>
              <Icon name="pending" style={{ verticalAlign: -3, marginRight: 6 }} />
              {el ? 'Φόρτωση...' : 'Loading...'}
            </div>
          ) : slots.length === 0 ? (
            <div className="card" style={{ padding: '28px 24px', textAlign: 'center' }}>
              <Icon name="event_busy" style={{ fontSize: 32, color: 'var(--fg3)', display: 'block', margin: '0 auto 10px' }} />
              <p style={{ color: 'var(--fg2)', fontSize: 14, margin: 0 }}>
                {el ? 'Δεν υπάρχουν διαθέσιμες ώρες αυτήν την ημέρα.' : 'No available slots on this day.'}
              </p>
            </div>
          ) : (
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {slots.map(s => (
                <button
                  key={s.time}
                  disabled={!s.available || booking}
                  onClick={() => bookSlot(s.time)}
                  style={{
                    padding: '10px 20px', borderRadius: 12, fontWeight: 600, fontSize: 15, cursor: s.available ? 'pointer' : 'not-allowed',
                    border: s.available ? '1.5px solid var(--psy-accent)' : '1.5px solid var(--psy-rule)',
                    background: s.available ? 'var(--psy-accent)' : 'transparent',
                    color: s.available ? 'white' : 'var(--fg3)',
                    opacity: booking ? 0.6 : 1,
                    position: 'relative',
                  }}>
                  {s.time}
                  {!s.available && (
                    <span style={{ display: 'block', fontSize: 9, fontWeight: 400, marginTop: 2, color: 'var(--fg3)' }}>
                      {el ? 'Κλειστό' : 'Taken'}
                    </span>
                  )}
                </button>
              ))}
            </div>
          )}

          {booking && (
            <p style={{ color: 'var(--fg2)', fontSize: 14, marginTop: 16 }}>
              <Icon name="pending" style={{ verticalAlign: -3, marginRight: 6 }} />
              {el ? 'Δημιουργία κράτησης & video room...' : 'Creating booking & video room...'}
            </p>
          )}
        </>
      )}
    </div>
  );
}

// ===========================================================
//  VIDEO CALL SCREEN
// ===========================================================
function VideoCallScreen({ bookingId, setRoute }) {
  const { lang } = useLang();
  const el = lang === 'el';

  const [callUrl, setCallUrl] = useState(null);
  const [error,   setError]   = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!bookingId) return;
    API.joinBooking(bookingId)
      .then(d => { if (d.url) setCallUrl(d.url); else setError(d.error || 'No video URL'); })
      .catch(e => setError(e.message || 'Network error'))
      .finally(() => setLoading(false));
  }, [bookingId]);

  return (
    <div style={{ height: 'calc(100vh - 56px)', display: 'flex', flexDirection: 'column', background: '#0C1118' }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '10px 20px', background: 'rgba(255,255,255,0.04)',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        flexShrink: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="videocam" style={{ color: 'rgba(255,255,255,0.8)', fontSize: 20 }} />
          <span style={{ color: 'rgba(255,255,255,0.9)', fontWeight: 600, fontSize: 15 }}>
            {el ? 'Ασφαλής Συνεδρία' : 'Secure Session'}
          </span>
          <span style={{
            background: 'rgba(14,159,110,0.2)', color: '#34D399',
            borderRadius: 99, padding: '2px 8px', fontSize: 11, fontWeight: 700,
          }}>
            GDPR
          </span>
        </div>
        <button
          className="btn ghost sm"
          style={{ color: 'rgba(255,255,255,0.6)', borderColor: 'rgba(255,255,255,0.15)', fontSize: 13 }}
          onClick={() => setRoute('home')}>
          <Icon name="close" className="sm" /> {el ? 'Έξοδος' : 'Leave'}
        </button>
      </div>

      {/* Content */}
      {loading && (
        <div style={{ flex: 1, display: 'grid', placeItems: 'center' }}>
          <div style={{ textAlign: 'center', color: 'rgba(255,255,255,0.5)' }}>
            <Icon name="videocam" style={{ fontSize: 40, display: 'block', margin: '0 auto 14px', color: 'rgba(255,255,255,0.3)' }} />
            <p style={{ margin: 0, fontSize: 15 }}>{el ? 'Σύνδεση...' : 'Connecting...'}</p>
          </div>
        </div>
      )}

      {error && (
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', padding: 32 }}>
          <div style={{ textAlign: 'center', maxWidth: 360 }}>
            <Icon name="error_outline" style={{ fontSize: 40, display: 'block', margin: '0 auto 14px', color: '#EF4444' }} />
            <p style={{ color: 'rgba(255,255,255,0.7)', fontSize: 15, marginBottom: 20, lineHeight: 1.5 }}>{error}</p>
            <button
              className="btn ghost sm"
              style={{ color: 'rgba(255,255,255,0.7)', borderColor: 'rgba(255,255,255,0.2)' }}
              onClick={() => setRoute('home')}>
              {el ? 'Πίσω στην αρχική' : 'Back to home'}
            </button>
          </div>
        </div>
      )}

      {callUrl && (
        <iframe
          src={callUrl}
          allow="camera; microphone; fullscreen; display-capture; autoplay"
          style={{ flex: 1, border: 'none', width: '100%', display: 'block' }}
          title={el ? 'Συνεδρία ψυχολογίας' : 'Psychology session'}
        />
      )}
    </div>
  );
}

// ===========================================================
//  MY SESSIONS SCREEN (client view)
// ===========================================================
function MySessionsScreen({ setRoute, authUser, requireAuth }) {
  const { t, lang } = useLang();
  const el = lang === 'el';

  const [bookings, setBookings] = useState([]);
  const [loading,  setLoading]  = useState(true);

  useEffect(() => {
    API.getMyBookings()
      .then(d => { if (Array.isArray(d)) setBookings(d); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const todayStr = new Date().toISOString().slice(0, 10);

  const upcoming = bookings.filter(b => b.status === 'confirmed' && b.date >= todayStr)
                           .sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time));
  const pending  = bookings.filter(b => b.status === 'pending')
                           .sort((a, b) => a.date.localeCompare(b.date));
  const past     = bookings.filter(b => b.status === 'confirmed' && b.date < todayStr)
                           .sort((a, b) => b.date.localeCompare(a.date));

  function fmtDate(dateStr) {
    const d = new Date(dateStr + 'T12:00:00');
    return d.toLocaleDateString(el ? 'el-GR' : 'en-GB', { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' });
  }

  function BookingRow({ b, showJoin }) {
    const isOnline = b.mode === 'online';
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 16,
        padding: '16px 20px',
        borderBottom: '1px solid var(--psy-rule)',
      }}>
        {/* Avatar */}
        <div style={{
          width: 44, height: 44, fontSize: 16, flexShrink: 0, borderRadius: '50%',
          background: avatarBg(b.psy_avatar_variant != null ? b.psy_avatar_variant : b.psy_id),
          display: 'grid', placeItems: 'center',
          fontWeight: 700, color: 'white', letterSpacing: '-0.01em',
        }}>
          {b.psy_initials || (b.psy_name || '?').split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase()}
        </div>

        {/* Info */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--psy-ink)', marginBottom: 3 }}>
            {b.psy_name || '—'}
          </div>
          <div style={{ fontSize: 13, color: 'var(--fg2)', display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <span><Icon name="calendar_today" style={{ fontSize: 13, verticalAlign: -2, marginRight: 3 }} />{fmtDate(b.date)}</span>
            <span><Icon name="schedule" style={{ fontSize: 13, verticalAlign: -2, marginRight: 3 }} />{b.time}</span>
            <span style={{
              fontSize: 11, fontWeight: 700, letterSpacing: '0.05em',
              color: isOnline ? 'var(--psy-accent)' : 'var(--psy-ink)',
              background: isOnline ? 'var(--psy-accent-soft)' : 'var(--psy-surface)',
              borderRadius: 99, padding: '2px 8px',
            }}>
              {isOnline ? t('sess_online') : t('sess_in_person')}
            </span>
          </div>
        </div>

        {/* Actions */}
        <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
          {showJoin && isOnline && (
            <button
              className="btn accent sm"
              onClick={() => setRoute('video-call', { id: String(b.id) })}>
              <Icon name="videocam" className="sm" /> {t('sess_join')}
            </button>
          )}
          <button
            className="btn ghost sm"
            onClick={() => setRoute('detail', b.psy_id)}>
            {t('sess_view_psy')}
          </button>
        </div>
      </div>
    );
  }

  function Section({ title, items, emptyMsg, showJoin }) {
    return (
      <div style={{ marginBottom: 36 }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700, marginBottom: 12, color: 'var(--psy-ink)' }}>
          {title}
          <span style={{ marginLeft: 8, fontSize: 13, fontWeight: 500, color: 'var(--fg3)' }}>({items.length})</span>
        </h2>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          {items.length === 0 ? (
            <p style={{ padding: '20px 20px', color: 'var(--fg3)', fontSize: 14, margin: 0 }}>{emptyMsg}</p>
          ) : (
            items.map((b, idx) => (
              <div key={b.id} style={{ borderBottom: idx < items.length - 1 ? undefined : 'none' }}>
                <BookingRow b={b} showJoin={showJoin} />
              </div>
            ))
          )}
        </div>
      </div>
    );
  }

  if (loading) return (
    <div className="page narrow" style={{ paddingTop: 80, textAlign: 'center' }}>
      <Icon name="pending" style={{ fontSize: 40, color: 'var(--fg3)' }} />
    </div>
  );

  return (
    <div className="page narrow" style={{ maxWidth: 760 }}>
      {/* Header */}
      <div style={{ marginBottom: 32 }}>
        <span className="eyebrow muted">{t('sess_eyebrow')}</span>
        <h1 className="display" style={{ fontSize: 36, marginTop: 8 }}>{t('sess_h1')}</h1>
        <p style={{ color: 'var(--fg2)', marginTop: 8, fontSize: 15 }}>{t('sess_sub')}</p>
      </div>

      {/* Upcoming confirmed */}
      <Section
        title={t('sess_upcoming')}
        items={upcoming}
        emptyMsg={t('sess_empty_upcoming')}
        showJoin={true}
      />

      {/* Pending */}
      {pending.length > 0 && (
        <Section
          title={t('sess_pending')}
          items={pending}
          emptyMsg={t('sess_empty_pending')}
          showJoin={false}
        />
      )}

      {/* Past */}
      <Section
        title={t('sess_past')}
        items={past}
        emptyMsg={t('sess_empty_past')}
        showJoin={false}
      />

      {/* CTA when all empty */}
      {bookings.length === 0 && (
        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <button className="btn primary" onClick={() => setRoute('directory')}>
            <Icon name="search" className="sm" /> {t('sess_book_new')}
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AvailabilityScreen, BookingCalendarScreen, VideoCallScreen, MySessionsScreen });
