const { useState: useMsSt, useContext: useMsCtx, useMemo: useMsMemo } = React;

/* ── Helpers de data ──────────────────────────────────────────────── */
const MONTH_NAMES = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
const WEEK_NAMES  = ['D','S','T','Q','Q','S','S'];

const startOfDay = (d) => { const x = new Date(d); x.setHours(0,0,0,0); return x; };
const fmtBR = (iso) => {
  const d = new Date(iso);
  return d.toLocaleString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric',
    hour: '2-digit', minute: '2-digit' });
};

/* ── Calendário de 1 mês ──────────────────────────────────────────── */
const MonthCalendar = ({ year, month, selected, onPick, onPrev, onNext, disabledWeekdays }) => {
  const today = startOfDay(new Date());
  const firstWeekday = new Date(year, month, 1).getDay();
  const totalDays    = new Date(year, month + 1, 0).getDate();
  const cells        = [];
  for (let i = 0; i < firstWeekday; i++) cells.push(null);
  for (let d = 1; d <= totalDays; d++) cells.push(d);

  const disabledList = disabledWeekdays || [];

  return (
    <div>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 14, padding: '0 4px',
      }}>
        <button onClick={onPrev} style={{
          width: 34, height: 34, borderRadius: '50%',
          background: 'var(--card)', border: '1px solid var(--border)',
          color: 'var(--text2)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>‹</button>
        <p style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)', letterSpacing: '-0.01em' }}>
          {MONTH_NAMES[month]} {year}
        </p>
        <button onClick={onNext} style={{
          width: 34, height: 34, borderRadius: '50%',
          background: 'var(--card)', border: '1px solid var(--border)',
          color: 'var(--text2)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>›</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, marginBottom: 6 }}>
        {WEEK_NAMES.map((w, i) => (
          <div key={i} style={{
            textAlign: 'center', fontSize: 10, fontWeight: 600,
            color: 'var(--text3)', letterSpacing: '0.08em', padding: '6px 0',
          }}>{w}</div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
        {cells.map((d, i) => {
          if (d == null) return <div key={i}/>;
          const date = new Date(year, month, d);
          const isPast    = date < today;
          const isToday   = date.getTime() === today.getTime();
          const weekday   = date.getDay();
          const isBlocked = disabledList.includes(weekday);
          const isSelected = selected
            && selected.getFullYear() === year && selected.getMonth() === month && selected.getDate() === d;
          const disabled = isPast || isBlocked;

          return (
            <button
              key={i}
              onClick={() => !disabled && onPick(date)}
              disabled={disabled}
              style={{
                aspectRatio: '1',
                borderRadius: 8,
                background: isSelected ? 'var(--gold)' : isToday ? 'var(--gold-bg)' : 'var(--card)',
                border: `1px solid ${
                  isSelected ? 'var(--gold)' :
                  isToday    ? 'var(--border-h)' :
                  'var(--border)'
                }`,
                color: isSelected ? '#0A0A0A' : disabled ? 'var(--text3)' : 'var(--text)',
                fontSize: 13, fontWeight: isSelected || isToday ? 700 : 500,
                cursor: disabled ? 'not-allowed' : 'pointer',
                opacity: disabled ? 0.35 : 1,
                fontFamily: 'inherit',
              }}
            >
              {d}
            </button>
          );
        })}
      </div>
    </div>
  );
};

/* ── MentoriaScheduling ──────────────────────────────────────────── */
const MentoriaScheduling = ({ mentorias, onScheduled, onDismiss, onAllDone }) => {
  const { user, goToAccount, goToDashboard } = useMsCtx(UserCtx);
  const isMob = typeof useIsMobile === 'function' ? useIsMobile() : false;
  const [view, setView]         = useMsSt('list');   // 'list' | 'calendar'
  const [slot, setSlot]         = useMsSt(null);     // 1 | 2
  const [calRef, setCalRef]     = useMsSt(() => { const d = new Date(); d.setDate(1); return d; });
  const [selDate, setSelDate]   = useMsSt(null);
  const [selTime, setSelTime]   = useMsSt(null);
  const [confirming, setConfirming] = useMsSt(false);

  const mentoriasSafe = mentorias || {};
  const m1 = mentoriasSafe.mentoria_1;
  const m2 = mentoriasSafe.mentoria_2;
  const m1Done = !!m1?.scheduled_at;
  const m2Done = !!m2?.scheduled_at;
  const tudoFeito = m1Done && m2Done;

  /* ── Regra: a Mentoria 2 só pode ser marcada a partir de 1 dia
     APÓS a data da Mentoria 1. Ex.: M1 em 15/jun → M2 libera em 16/jun. */
  const m2UnlockAt = m1Done ? new Date(new Date(m1.scheduled_at).getTime() + 24*60*60*1000) : null;
  const m2Unlocked = m1Done && m2UnlockAt && new Date() >= m2UnlockAt;

  const openCalendar = (n) => {
    if (n === 2 && !m2Unlocked) return;
    setSlot(n);
    setSelDate(null);
    setSelTime(null);
    setView('calendar');
  };

  const backToList = () => {
    setView('list');
    setSlot(null);
    setSelDate(null);
    setSelTime(null);
  };

  const prevMonth = () => { const d = new Date(calRef); d.setMonth(d.getMonth() - 1); setCalRef(d); };
  const nextMonth = () => { const d = new Date(calRef); d.setMonth(d.getMonth() + 1); setCalRef(d); };

  const confirmSchedule = async () => {
    if (!selDate || !selTime || !slot) return;
    setConfirming(true);
    try {
      const [hh, mm] = selTime.split(':').map(Number);
      const dt = new Date(selDate);
      dt.setHours(hh, mm, 0, 0);
      const isoLocal = new Date(dt.getTime() - dt.getTimezoneOffset() * 60000).toISOString().slice(0, 19);

      const { data: sess } = await _supabase.auth.getSession();
      const token = sess?.session?.access_token;
      if (!token) throw new Error('Sessão expirada — faça login novamente');

      /* Timeout cliente de 25s: se a função no Vercel travar, libera a UI */
      const ctrl = new AbortController();
      const timer = setTimeout(() => ctrl.abort(), 25000);

      let resp;
      try {
        resp = await fetch('/api/schedule-mentoria', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
          body: JSON.stringify({ slot, scheduled_at_local: isoLocal }),
          signal: ctrl.signal,
        });
      } catch (e) {
        if (e.name === 'AbortError') {
          throw new Error('A operação demorou mais que o esperado. Tente de novo em alguns segundos.');
        }
        throw e;
      } finally {
        clearTimeout(timer);
      }

      const result = await resp.json().catch(() => ({}));
      if (!resp.ok) throw new Error(result?.error || `Erro HTTP ${resp.status}`);

      const updated = {
        ...mentoriasSafe,
        [`mentoria_${slot}`]: {
          scheduled_at: result.scheduled_at || dt.toISOString(),
          calendar_event_id: result.calendar_event_id || null,
          created_at: new Date().toISOString(),
        },
      };
      onScheduled(updated);
      backToList();
      /* Se as duas já estão marcadas, fecha o overlay */
      if (slot === 1 ? (updated.mentoria_2?.scheduled_at) : (updated.mentoria_1?.scheduled_at)) {
        if (typeof onAllDone === 'function') onAllDone();
      }
    } catch (e) {
      console.error('[mentoria] erro:', e);
      alert(`Não foi possível agendar.\n\n${e.message || e}`);
    } finally {
      setConfirming(false);
    }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 999,
      background: 'var(--bg)',
      /* No view de lista (depois de marcada) não scrolla; só no calendário
         (que tem mais conteúdo) liberamos o scroll. */
      overflow: view === 'calendar' ? 'auto' : 'hidden',
      paddingTop: 'env(safe-area-inset-top, 0px)',
      paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 24px)',
    }}>
      <div style={{ maxWidth: 540, margin: '0 auto', padding: '28px 24px 48px' }}>

        {view === 'list' && (
          <>
            {/* Voltar — só no mobile, leva pra aba Perfil (account) */}
            {isMob && (
              <button
                onClick={() => {
                  onDismiss();
                  if (typeof goToAccount === 'function') goToAccount();
                }}
                style={{
                  background: 'none', color: 'var(--text2)', fontSize: 13,
                  padding: '4px 8px 4px 0',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  marginBottom: 16, fontFamily: 'inherit',
                }}
              >
                ← Voltar
              </button>
            )}

            <p style={{
              fontSize: 11, fontWeight: 700, color: 'var(--gold)',
              letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 8,
            }}>
              {tudoFeito ? 'Mentorias agendadas' : 'Marque suas mentorias'}
            </p>
            <h1 style={{
              fontSize: 26, fontWeight: 700, color: 'var(--text)',
              lineHeight: 1.2, marginBottom: 8, letterSpacing: '-0.4px',
            }}>
              {tudoFeito ? 'Tudo certo!' : 'Agende suas sessões'}
            </h1>
            <p style={{ fontSize: 14, color: 'var(--text2)', lineHeight: 1.55, marginBottom: 24 }}>
              {tudoFeito
                ? 'Você já marcou as duas sessões de mentoria. Veja os detalhes abaixo.'
                : 'Escolha o melhor dia e horário com a Andreza. A Mentoria 2 fica disponível depois que você marcar a Mentoria 1.'}
            </p>

            {/* Cards das mentorias */}
            {MENTORIA_SLOTS.map(slotCfg => {
              const data = mentoriasSafe[`mentoria_${slotCfg.id}`];
              const done = !!data?.scheduled_at;
              /* M2 fica bloqueada se M1 não foi marcada OU se ainda não passou
                 1 dia da data da M1. (Quando já está agendada, mostra normal.) */
              const blocked = slotCfg.id === 2 && !done && !m2Unlocked;
              const blockedReason = slotCfg.id === 2 && !done
                ? (!m1Done
                    ? 'Marque a Mentoria 1 primeiro'
                    : `Disponível a partir de ${m2UnlockAt.toLocaleDateString('pt-BR', { day: '2-digit', month: 'long' })}`)
                : null;
              return (
                <div key={slotCfg.id} style={{
                  background: 'var(--card)',
                  border: `1px solid ${done ? 'var(--gold)' : 'var(--border)'}`,
                  borderRadius: 12, padding: '18px 20px', marginBottom: 14,
                  opacity: blocked ? 0.55 : 1,
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                    <p style={{ fontSize: 10, fontWeight: 700, color: 'var(--gold)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                      {blocked ? '🔒 Bloqueada' : done ? '✓ Agendada' : 'Disponível'}
                    </p>
                    <span style={{ fontSize: 11, color: 'var(--text3)' }}>
                      {MENTORIA_DURATION_MIN} min
                    </span>
                  </div>
                  <h2 style={{ fontSize: 17, fontWeight: 700, color: 'var(--text)', marginBottom: 5 }}>
                    {slotCfg.title}
                  </h2>
                  <p style={{ fontSize: 13, color: 'var(--text2)', lineHeight: 1.5, marginBottom: done || !blocked ? 14 : 8 }}>
                    {slotCfg.desc}
                  </p>

                  {blocked && blockedReason && (
                    <p style={{ fontSize: 12, color: 'var(--gold)', fontWeight: 600,
                      letterSpacing: '0.02em', marginTop: 6 }}>
                      🔒 {blockedReason}
                    </p>
                  )}

                  {done && (
                    <div style={{
                      background: 'var(--gold-bg)', border: '1px solid var(--border-h)',
                      borderRadius: 8, padding: '10px 14px',
                      fontSize: 13, color: 'var(--text)',
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      gap: 12, flexWrap: 'wrap',
                    }}>
                      <span>📅 <strong>{fmtBR(data.scheduled_at)}</strong></span>
                      <button
                        onClick={() => openCalendar(slotCfg.id)}
                        style={{
                          background: 'none', color: 'var(--gold)',
                          padding: '4px 10px', borderRadius: 6,
                          fontSize: 12, fontWeight: 600,
                          textDecoration: 'underline', textUnderlineOffset: 3,
                          fontFamily: 'inherit', cursor: 'pointer',
                          border: 'none',
                        }}
                      >
                        Remarcar
                      </button>
                    </div>
                  )}

                  {!done && !blocked && (
                    <button
                      onClick={() => openCalendar(slotCfg.id)}
                      style={{
                        background: 'var(--gold)', color: '#0A0A0A',
                        padding: '10px 22px', borderRadius: 8,
                        fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
                        fontFamily: 'inherit',
                      }}
                    >
                      Marcar →
                    </button>
                  )}
                </div>
              );
            })}

            {/* Footer — link à esquerda quando nada marcado; botão à direita caso contrário */}
            <div style={{
              display: 'flex', gap: 10, marginTop: 30,
              justifyContent: (m1Done || m2Done) ? 'flex-end' : 'space-between', alignItems: 'center',
            }}>
              {/* 0 marcadas → "Deixar para depois" (link)
                  1 marcada  → "Ir para plataforma" (botão dourado)
                  2 marcadas → "Concluir" (botão dourado) */}
              {!m1Done && !m2Done && (
                <button onClick={onDismiss} style={{
                  background: 'none', color: 'var(--text2)', fontSize: 13,
                  padding: '10px 6px', textDecoration: 'underline', textUnderlineOffset: 3,
                }}>
                  Deixar para depois
                </button>
              )}
              {(m1Done || m2Done) && !tudoFeito && (
                <button
                  onClick={() => {
                    onDismiss();
                    if (typeof goToDashboard === 'function') goToDashboard();
                  }}
                  style={{
                    background: 'var(--gold)', color: '#0A0A0A',
                    padding: '12px 26px', borderRadius: 9,
                    fontSize: 13.5, fontWeight: 700, fontFamily: 'inherit',
                  }}
                >
                  Ir para plataforma →
                </button>
              )}
              {tudoFeito && (
                <button
                  onClick={() => {
                    onDismiss();
                    if (typeof goToDashboard === 'function') goToDashboard();
                  }}
                  style={{
                    background: 'var(--gold)', color: '#0A0A0A',
                    padding: '12px 26px', borderRadius: 9,
                    fontSize: 13.5, fontWeight: 700, fontFamily: 'inherit',
                  }}
                >
                  Concluir
                </button>
              )}
            </div>
          </>
        )}

        {view === 'calendar' && (
          <>
            <button onClick={backToList} style={{
              background: 'none', color: 'var(--text2)', fontSize: 13,
              padding: '4px 8px 4px 0', display: 'inline-flex', alignItems: 'center', gap: 6,
              marginBottom: 16,
            }}>
              ← Voltar
            </button>

            <p style={{
              fontSize: 11, fontWeight: 700, color: 'var(--gold)',
              letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 8,
            }}>
              Mentoria {slot}
            </p>
            <h1 style={{
              fontSize: 22, fontWeight: 700, color: 'var(--text)',
              lineHeight: 1.2, marginBottom: 6, letterSpacing: '-0.3px',
            }}>
              Escolha um dia
            </h1>
            <p style={{ fontSize: 13.5, color: 'var(--text2)', marginBottom: 22 }}>
              Sessão de {MENTORIA_DURATION_MIN} minutos com a Andreza.
            </p>

            {/* Calendário */}
            <div style={{
              background: 'var(--card)', border: '1px solid var(--border)',
              borderRadius: 12, padding: '18px',
              marginBottom: 22,
            }}>
              <MonthCalendar
                year={calRef.getFullYear()}
                month={calRef.getMonth()}
                selected={selDate}
                onPick={(d) => { setSelDate(d); setSelTime(null); }}
                onPrev={prevMonth}
                onNext={nextMonth}
                disabledWeekdays={MENTORIA_DISABLED_WEEKDAYS}
              />
            </div>

            {/* Horários */}
            {selDate && (
              <div style={{ marginBottom: 22 }}>
                <p style={{
                  fontSize: 11, fontWeight: 700, color: 'var(--text2)',
                  letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 10,
                }}>
                  Horário disponível
                </p>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(86px, 1fr))', gap: 8 }}>
                  {MENTORIA_TIME_SLOTS.map(t => {
                    const sel = selTime === t;
                    return (
                      <button
                        key={t}
                        onClick={() => setSelTime(t)}
                        style={{
                          padding: '11px 14px', borderRadius: 8,
                          background: sel ? 'var(--gold)' : 'var(--card)',
                          color: sel ? '#0A0A0A' : 'var(--text)',
                          border: `1px solid ${sel ? 'var(--gold)' : 'var(--border)'}`,
                          fontSize: 13.5, fontWeight: sel ? 700 : 500,
                          fontFamily: 'inherit', cursor: 'pointer',
                          transition: 'all 0.15s',
                        }}
                      >
                        {t}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Resumo + confirmar */}
            {selDate && selTime && (
              <div style={{
                background: 'var(--gold-bg)', border: '1px solid var(--border-h)',
                borderRadius: 10, padding: '14px 16px', marginBottom: 18,
              }}>
                <p style={{ fontSize: 11, color: 'var(--gold)', fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 4 }}>
                  Você vai agendar
                </p>
                <p style={{ fontSize: 14, color: 'var(--text)', fontWeight: 600 }}>
                  Mentoria {slot} · {selDate.toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric' })} às {selTime}
                </p>
              </div>
            )}

            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={onDismiss} disabled={confirming} style={{
                background: 'none', color: 'var(--text2)', fontSize: 13,
                padding: '12px 6px', textDecoration: 'underline', textUnderlineOffset: 3,
              }}>
                Deixar para depois
              </button>
              <div style={{ flex: 1 }}/>
              <button
                onClick={confirmSchedule}
                disabled={!selDate || !selTime || confirming}
                style={{
                  background: 'var(--gold)', color: '#0A0A0A',
                  padding: '12px 26px', borderRadius: 9,
                  fontSize: 13.5, fontWeight: 700,
                  opacity: (!selDate || !selTime || confirming) ? 0.5 : 1,
                  cursor: (!selDate || !selTime || confirming) ? 'not-allowed' : 'pointer',
                  fontFamily: 'inherit',
                  display: 'flex', alignItems: 'center', gap: 7,
                }}
              >
                {confirming ? (
                  <>
                    <span style={{
                      width: 13, height: 13, borderRadius: '50%',
                      border: '2px solid rgba(10,10,10,0.25)', borderTopColor: '#0A0A0A',
                      animation: 'ms-spin 0.7s linear infinite',
                    }}/>
                    Agendando…
                  </>
                ) : 'Confirmar agendamento'}
              </button>
            </div>

            <style>{`@keyframes ms-spin { to { transform: rotate(360deg); } }`}</style>
          </>
        )}
      </div>
    </div>
  );
};

window.MentoriaScheduling = MentoriaScheduling;
