// Agenda de Atendimentos — com fluxos de cancelamento, falta e reagendamento

const { useState: agState, useEffect: agEffect, useRef: agRef } = React;

const HOURS = [];
for (let h = 7; h <= 20; h++) {
  HOURS.push(`${String(h).padStart(2,'0')}:00`);
  if (h < 20) HOURS.push(`${String(h).padStart(2,'0')}:30`);
}
const SLOT_H = 72;
function timeToSlot(t) { const [h,m]=t.split(':').map(Number); return (h-7)*2+(m>=30?1:0); }

let _nextId = 100;
const uid = () => ++_nextId;

const INIT_APPTS = [
  { id:1,  day:'seg', patient:'Ana Silva',    terapeuta:'Dra. Ana Silva',   time:'09:00', unidade:'Unidade Centro',  sala:'Sala 201', status:'confirmado', dur:1 },
  { id:2,  day:'ter', patient:'Jorge Ribeiro',terapeuta:'Dr. Carlos Mendes',time:'09:00', unidade:'Unidade Centro',  sala:'Sala 202', status:'aguardando', dur:1 },
  { id:3,  day:'ter', patient:'Amanda Viana', terapeuta:'Dra. Ana Silva',   time:'10:00', unidade:'Unidade Jardins', sala:'Sala 201', status:'falta',      dur:1 },
  { id:4,  day:'ter', patient:'Carmem Lúcia', terapeuta:'Dra. Ana Silva',   time:'11:00', unidade:'Unidade Centro',  sala:'Sala 203', status:'reagendado', dur:1 },
  { id:5,  day:'qua', patient:'Carmem Lúcia', terapeuta:'Dra. Ana Silva',   time:'09:00', unidade:'Unidade Jardins', sala:'Sala 201', status:'cancelado',  dur:1 },
  { id:6,  day:'qua', patient:'Ana Silva',    terapeuta:'Dra. Ana Silva',   time:'10:00', unidade:'Unidade Centro',  sala:'Sala 201', status:'confirmado', dur:1 },
  { id:7,  day:'qui', patient:'Amanda Viana', terapeuta:'Dr. Carlos Mendes',time:'09:00', unidade:'Unidade Jardins', sala:'Sala 202', status:'aguardando', dur:1 },
  { id:8,  day:'sex', patient:'Ana Silva',    terapeuta:'Dra. Ana Silva',   time:'09:00', unidade:'Unidade Centro',  sala:'Sala 201', status:'confirmado', dur:1 },
  { id:9,  day:'sex', patient:'Jorge Ribeiro',terapeuta:'Dr. Carlos Mendes',time:'11:00', unidade:'Unidade Centro',  sala:'Sala 203', status:'falta',      dur:1 },
  { id:10, day:'sab', patient:'Carmem Lúcia', terapeuta:'Dra. Ana Silva',   time:'09:00', unidade:'Unidade Jardins', sala:'Sala 201', status:'reagendado', dur:1 },
];

/* ── Toast ── */
function AgendaToast({ msg, onDone }) {
  agEffect(() => { const t = setTimeout(onDone, 3000); return () => clearTimeout(t); }, []);
  return (
    <div style={{
      position:'fixed', bottom:80, left:'50%', transform:'translateX(-50%)',
      background:'#1e293b', color:'white', borderRadius:8, padding:'11px 20px',
      fontSize:13, fontWeight:500, zIndex:9999,
      boxShadow:'0 4px 20px rgba(0,0,0,0.3)', display:'flex', alignItems:'center', gap:10,
      animation:'fadeInUp .2s ease',
    }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#22c55e" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
      {msg}
    </div>
  );
}

/* ── Bloco clicável ── */
function AgendaApptBlock({ appt, onClick }) {
  const c = APPT_COLORS[appt.status] || APPT_COLORS.aguardando;
  const top = timeToSlot(appt.time) * SLOT_H;
  const height = appt.dur * SLOT_H - 3;
  const Mini = ({ icon, text }) => (
    <div style={{ display:'flex', alignItems:'center', gap:3, marginTop:2 }}>
      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke={c.text} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ opacity:.7, flexShrink:0 }}>
        <path d={icon}/>
      </svg>
      <span style={{ fontSize:10, color:c.text, opacity:.8, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{text}</span>
    </div>
  );
  return (
    <div onClick={() => onClick(appt)}
      style={{
        position:'absolute', left:2, right:2, top, height,
        background: c.bg, borderLeft:`3px solid ${c.border}`,
        borderRadius:5, padding:'5px 8px', overflow:'hidden',
        boxShadow:'0 1px 3px rgba(0,0,0,0.06)', zIndex:1,
        cursor:'pointer', transition:'filter .1s',
      }}
      onMouseEnter={e => e.currentTarget.style.filter='brightness(0.95)'}
      onMouseLeave={e => e.currentTarget.style.filter='none'}>
      <div style={{ fontSize:12, fontWeight:700, color:c.text, lineHeight:1.2 }}>{appt.patient}</div>
      <Mini icon="M12 6v6l4 2 M12 2a10 10 0 100 20A10 10 0 0012 2z" text={appt.time} />
      {appt.unidade && <Mini icon="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z" text={appt.unidade} />}
      {appt.sala    && <Mini icon="M3 3h18v18H3z M9 3v18 M3 9h6 M3 15h6" text={appt.sala} />}
      <div style={{ marginTop:3, display:'inline-block', fontSize:9, fontWeight:700, color:c.text, background:c.border+'28', padding:'1px 6px', borderRadius:8 }}>{c.label}</div>
    </div>
  );
}

/* ── Modal Detalhe ── */
function ModalDetalhe({ appt, perfil, onClose, onCancelar, onReagendar, onConfirmar, onIniciar }) {
  const c = APPT_COLORS[appt.status] || APPT_COLORS.aguardando;
  const isTerapeuta   = perfil === 'terapeuta';
  const isSecretaria  = perfil === 'secretaria';
  const isAdmin       = perfil === 'admin';
  const podeAgir      = !isTerapeuta; // admin + secretaria
  const podeConfirmar = ['aguardando','reagendado'].includes(appt.status);
  const podeReagendar = ['confirmado','aguardando','falta','reagendado'].includes(appt.status);
  const podeCancelar  = ['confirmado','aguardando','reagendado'].includes(appt.status);
  const podeIniciar   = isAdmin && appt.status === 'confirmado';

  const Row = ({ label, value }) => (
    <div style={{ display:'flex', justifyContent:'space-between', padding:'7px 0', borderBottom:'1px solid #f3f4f6' }}>
      <span style={{ fontSize:13, color:'#6b7280' }}>{label}</span>
      <span style={{ fontSize:13, fontWeight:500, color:'#111' }}>{value}</span>
    </div>
  );

  return (
    <Modal title="Detalhes da consulta" onClose={onClose} width={420}>
      <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
        <Row label="Paciente"  value={appt.patient} />
        <Row label="Terapeuta" value={appt.terapeuta} />
        <Row label="Data"      value={WEEK_DAYS.find(d=>d.key===appt.day)?.label+', '+WEEK_DAYS.find(d=>d.key===appt.day)?.num} />
        <Row label="Horário"   value={appt.time} />
        <Row label="Unidade"   value={appt.unidade} />
        <Row label="Sala"      value={appt.sala} />
        <div style={{ display:'flex', justifyContent:'space-between', padding:'10px 0', alignItems:'center' }}>
          <span style={{ fontSize:13, color:'#6b7280' }}>Status</span>
          <span style={{ fontSize:12, fontWeight:700, color:c.text, background:c.bg, border:`1px solid ${c.border}`, padding:'3px 10px', borderRadius:12 }}>
            {c.label}
          </span>
        </div>
      </div>

      {isTerapeuta ? (
        <div style={{ marginTop:16 }}>
          <div style={{ padding:'10px 14px', background:'#f8fafc', border:'1px solid #e5e7eb', borderRadius:8, fontSize:13, color:'#6b7280', textAlign:'center' }}>
            Você está visualizando esta consulta em modo leitura.
          </div>
          <button onClick={onClose}
            style={{ width:'100%', marginTop:12, padding:'9px', background:'white', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, fontWeight:500, cursor:'pointer', color:'#374151' }}>
            Fechar
          </button>
        </div>
      ) : (
        <div style={{ display:'flex', gap:8, marginTop:16, flexWrap:'wrap' }}>
          {podeCancelar && (
            <button onClick={onCancelar}
              style={{ flex:1, padding:'9px', background:'#fee2e2', color:'#991b1b', border:'1px solid #fca5a5', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              Cancelar / Falta
            </button>
          )}
          {podeConfirmar && (
            <button onClick={onConfirmar}
              style={{ flex:1, padding:'9px', background:'#dcfce7', color:'#15803d', border:'1px solid #86efac', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              ✓ Confirmar
            </button>
          )}
          {podeReagendar && (
            <button onClick={onReagendar}
              style={{ flex:1, padding:'9px', background:'#fef9c3', color:'#854d0e', border:'1px solid #fde047', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
              Reagendar
            </button>
          )}
          {podeIniciar && (
            <button onClick={onIniciar}
              style={{ width:'100%', marginTop:4, padding:'10px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:700, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
              Iniciar consulta
            </button>
          )}
        </div>
      )}
    </Modal>
  );
}

/* ── Modal Cancelar / Falta (unificado) ── */
function ModalCancelar({ appt, onClose, onConfirm }) {
  const [tipo,      setTipo]    = agState('');        // 'cancelamento' | 'falta'
  const [step,      setStep]    = agState('tipo');    // 'tipo' | 'cancelamento' | 'quem' | 'paciente' | 'terapeuta'
  const [motivo,    setMotivo]  = agState('');
  const [responsavel, setResp]  = agState('');
  const [docFile,   setDocFile] = agState(null);
  const [docErro,   setDocErro] = agState('');
  const [obs,       setObs]     = agState('');
  const [novaData,  setNData]   = agState('');
  const [novaHora,  setNHora]   = agState('');
  const [erro,      setErro]    = agState('');

  const antecedencia24h = true; // mock demo
  const FORMATOS = ['application/pdf','image/jpeg','image/png'];

  const inputS = { padding:'8px 10px', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, background:'white', outline:'none', color:'#111', width:'100%', boxSizing:'border-box' };

  const Nota = ({ tipo: t, children }) => (
    <div style={{ padding:'10px 14px', borderRadius:8, fontSize:12, lineHeight:1.5,
      background: t==='info' ? '#eff6ff' : t==='warn' ? '#fffbeb' : t==='green' ? '#f0fdf4' : '#fff7ed',
      border: `1px solid ${t==='info' ? '#bfdbfe' : t==='warn' ? '#fde68a' : t==='green' ? '#86efac' : '#fed7aa'}`,
      color: t==='info' ? '#1d4ed8' : t==='warn' ? '#92400e' : t==='green' ? '#15803d' : '#9a3412' }}>
      {children}
    </div>
  );

  const handleDoc = e => {
    const f = e.target.files[0];
    if (!f) return;
    if (!FORMATOS.includes(f.type)) { setDocErro('Formato inválido. Envie PDF, JPG ou PNG.'); setDocFile(null); return; }
    setDocErro(''); setDocFile(f);
  };

  const handleAvancar = () => {
    if (!tipo) { setErro('Selecione o tipo de ocorrência para continuar.'); return; }
    setErro('');
    if (tipo === 'cancelamento') setStep('cancelamento');
    else setStep('quem');
  };

  const handleConfirmarCancelamento = () => {
    if (!motivo.trim()) { setErro('Informe o motivo do cancelamento.'); return; }
    onConfirm({ tipo:'cancelamento', motivo });
  };

  const handleAvancarFalta = () => {
    if (!responsavel) { setErro('Selecione de quem é a falta para continuar.'); return; }
    setErro(''); setStep(responsavel);
  };

  const handleConfirmarFalta = () => {
    if (step === 'paciente' && !docFile) { onConfirm({ tipo:'falta', responsavel:'paciente', reagendar:false }); return; }
    if (step === 'paciente' && docFile)  { onConfirm({ tipo:'falta', responsavel:'paciente', reagendar:!!(novaData&&novaHora), novaData, novaHora, obs }); return; }
    if (step === 'terapeuta')            { onConfirm({ tipo:'falta', responsavel:'terapeuta', reagendar:!!(novaData&&novaHora), novaData, novaHora, obs }); return; }
  };

  const btnBack = (onClick) => (
    <button onClick={onClick} style={{ flex:1, padding:'9px', background:'white', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, cursor:'pointer', color:'#374151' }}>← Voltar</button>
  );

  return (
    <Modal title="Cancelar / Registrar falta" onClose={onClose} width={440}>

      {/* STEP 1 — Tipo de ocorrência */}
      {step === 'tipo' && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <p style={{ margin:0, fontSize:14, color:'#374151' }}>Qual o tipo de ocorrência para a consulta de <strong>{appt.patient}</strong> às {appt.time}?</p>
          {[
            { id:'cancelamento', label:'Cancelamento', sub:'A consulta não ocorrerá e não será reagendada por este motivo.', bg:'#fee2e2', border:'#fca5a5', color:'#991b1b' },
            { id:'falta',        label:'Falta',        sub:'O paciente ou terapeuta não compareceu ao atendimento.',         bg:'#ffedd5', border:'#fed7aa', color:'#9a3412' },
          ].map(op => (
            <label key={op.id} onClick={() => { setTipo(op.id); setErro(''); }}
              style={{ display:'flex', alignItems:'flex-start', gap:12, padding:'12px 14px', border:`1.5px solid ${tipo===op.id ? op.border : '#e5e7eb'}`, borderRadius:8, cursor:'pointer', background: tipo===op.id ? op.bg : 'white', transition:'all .15s' }}>
              <div style={{ marginTop:2, width:16, height:16, borderRadius:'50%', border:`2px solid ${tipo===op.id ? op.color : '#d1d5db'}`, background: tipo===op.id ? op.color : 'white', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                {tipo===op.id && <div style={{ width:6, height:6, borderRadius:'50%', background:'white' }}/>}
              </div>
              <div>
                <div style={{ fontSize:14, fontWeight:600, color: tipo===op.id ? op.color : '#374151' }}>{op.label}</div>
                <div style={{ fontSize:12, color:'#6b7280', marginTop:2 }}>{op.sub}</div>
              </div>
            </label>
          ))}
          {erro && <p style={{ margin:0, fontSize:12, color:'#ef4444' }}>{erro}</p>}
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={onClose} style={{ flex:1, padding:'9px', background:'white', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, cursor:'pointer', color:'#374151' }}>Fechar</button>
            <button onClick={handleAvancar} style={{ flex:1, padding:'9px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>Avançar →</button>
          </div>
        </div>
      )}

      {/* STEP — Cancelamento */}
      {step === 'cancelamento' && (
        <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
          <Nota tipo={antecedencia24h ? 'green' : 'orange'}>
            {antecedencia24h ? '💰 O valor pago será devolvido ao paciente. Nenhuma comissão será gerada.' : '⚠️ O valor não será devolvido. Comissão do terapeuta gerada normalmente.'}
          </Nota>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:6 }}>Motivo do cancelamento <span style={{ color:'#ef4444' }}>*</span></label>
            <textarea value={motivo} onChange={e=>{ setMotivo(e.target.value); setErro(''); }}
              placeholder="Descreva o motivo do cancelamento…" rows={3}
              style={{ width:'100%', padding:'9px 12px', border:`1px solid ${erro ? '#fca5a5' : '#d1d5db'}`, borderRadius:6, fontSize:13, resize:'vertical', outline:'none', color:'#111', boxSizing:'border-box', fontFamily:'inherit' }}/>
            {erro && <p style={{ margin:'4px 0 0', fontSize:12, color:'#ef4444' }}>{erro}</p>}
          </div>
          <div style={{ display:'flex', gap:10 }}>
            {btnBack(() => setStep('tipo'))}
            <button onClick={handleConfirmarCancelamento} style={{ flex:1, padding:'9px', background:'#dc2626', color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>Confirmar cancelamento</button>
          </div>
        </div>
      )}

      {/* STEP — Quem faltou */}
      {step === 'quem' && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <p style={{ margin:0, fontSize:14, color:'#374151' }}>De quem é a falta?</p>
          {['paciente','terapeuta'].map(op => (
            <label key={op} onClick={() => { setResp(op); setErro(''); }}
              style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', border:`1.5px solid ${responsavel===op ? C.primary : '#e5e7eb'}`, borderRadius:8, cursor:'pointer', background: responsavel===op ? '#eff6ff' : 'white', transition:'all .15s' }}>
              <div style={{ width:16, height:16, borderRadius:'50%', border:`2px solid ${responsavel===op ? C.primary : '#d1d5db'}`, background: responsavel===op ? C.primary : 'white', display:'flex', alignItems:'center', justifyContent:'center' }}>
                {responsavel===op && <div style={{ width:6, height:6, borderRadius:'50%', background:'white' }}/>}
              </div>
              <span style={{ fontSize:14, fontWeight: responsavel===op ? 600 : 400, color: responsavel===op ? C.primary : '#374151', textTransform:'capitalize' }}>{op}</span>
            </label>
          ))}
          {erro && <p style={{ margin:0, fontSize:12, color:'#ef4444' }}>{erro}</p>}
          <div style={{ display:'flex', gap:10 }}>
            {btnBack(() => setStep('tipo'))}
            <button onClick={handleAvancarFalta} style={{ flex:1, padding:'9px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>Avançar →</button>
          </div>
        </div>
      )}

      {/* STEP — Falta do paciente */}
      {step === 'paciente' && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Nota tipo="warn">Falta do <strong>Paciente</strong>. Reagendamento bloqueado sem justificativa.</Nota>
          <Nota tipo="green">💰 Nenhuma alteração no lançamento financeiro.</Nota>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:6 }}>Justificativa — comprovante (opcional)</label>
            <label style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:6, padding:'14px', border:`2px dashed ${docFile ? '#22c55e' : '#d1d5db'}`, borderRadius:8, cursor:'pointer', background: docFile ? '#f0fdf4' : '#fafafa' }}>
              <input type="file" accept=".pdf,.jpg,.jpeg,.png" onChange={handleDoc} style={{ display:'none' }}/>
              {docFile ? <><span>✅</span><span style={{ fontSize:13, color:'#16a34a', fontWeight:500 }}>{docFile.name}</span></> : <><Icon name="upload" size={18} color="#9ca3af"/><span style={{ fontSize:13, color:'#6b7280' }}>Clique para anexar PDF, JPG ou PNG</span></>}
            </label>
            {docErro && <p style={{ margin:'4px 0 0', fontSize:12, color:'#ef4444' }}>{docErro}</p>}
          </div>
          {!docFile && (
            <div title="Para reagendar, anexe um documento de justificativa." style={{ opacity:.45, cursor:'not-allowed' }}>
              <div style={{ padding:'9px', background:'#f3f4f6', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, color:'#9ca3af', textAlign:'center', pointerEvents:'none' }}>
                Reagendar — anexe justificativa para habilitar
              </div>
            </div>
          )}
          {docFile && (
            <>
              <div>
                <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:8 }}>Reagendar para (opcional)</label>
                <div style={{ display:'flex', gap:10 }}>
                  <input type="date" value={novaData} onChange={e=>setNData(e.target.value)} style={{ ...inputS, flex:1 }}/>
                  <input type="time" value={novaHora} onChange={e=>setNHora(e.target.value)} style={{ ...inputS, flex:'0 0 110px' }}/>
                </div>
              </div>
            </>
          )}
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:6 }}>Observação (opcional)</label>
            <textarea value={obs} onChange={e=>setObs(e.target.value)} rows={2} placeholder="Observações sobre a falta do paciente…"
              style={{ ...inputS, resize:'vertical', fontFamily:'inherit' }}/>
          </div>
          <div style={{ display:'flex', gap:10 }}>
            {btnBack(() => setStep('quem'))}
            <button onClick={handleConfirmarFalta} style={{ flex:1, padding:'9px', background:'#f97316', color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>Registrar falta</button>
          </div>
        </div>
      )}

      {/* STEP — Falta do terapeuta */}
      {step === 'terapeuta' && (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Nota tipo="info">Falta do <strong>Terapeuta</strong>. Reagendamento liberado automaticamente.</Nota>
          <Nota tipo="warn">💰 Nenhuma comissão será gerada para este atendimento.</Nota>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:8 }}>Observação (opcional)</label>
            <textarea value={obs} onChange={e=>setObs(e.target.value)} rows={2} placeholder="Observações sobre a falta do terapeuta…"
              style={{ ...inputS, resize:'vertical', fontFamily:'inherit' }}/>
          </div>
          <div>
            <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:8 }}>Reagendar para (recomendado)</label>
            <div style={{ display:'flex', gap:10 }}>
              <input type="date" value={novaData} onChange={e=>setNData(e.target.value)} style={{ ...inputS, flex:1 }}/>
              <input type="time" value={novaHora} onChange={e=>setNHora(e.target.value)} style={{ ...inputS, flex:'0 0 110px' }}/>
            </div>
          </div>
          <div style={{ display:'flex', gap:10 }}>
            {btnBack(() => setStep('quem'))}
            <button onClick={handleConfirmarFalta} style={{ flex:2, padding:'9px', background:'#f97316', color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>Registrar falta</button>
          </div>
        </div>
      )}

    </Modal>
  );
}

/* ── Modal Reagendar ── */
function ModalReagendar({ appt, onClose, onConfirm }) {
  const [novaData, setNData] = agState('');
  const [novaHora, setNHora] = agState('');
  const [pago,     setPago]  = agState(false);
  const [erro,     setErro]  = agState('');
  const inputS = { padding:'8px 10px', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, background:'white', outline:'none', color:'#111', width:'100%', boxSizing:'border-box' };

  const handleConfirm = () => {
    if (!novaData || !novaHora) { setErro('Preencha a nova data e horário.'); return; }
    onConfirm({ novaData, novaHora, pago });
  };

  return (
    <Modal title="Reagendar consulta" onClose={onClose} width={400}>
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <p style={{ margin:0, fontSize:13, color:'#6b7280' }}>
          Reagendando consulta de <strong style={{ color:'#111' }}>{appt.patient}</strong> (atualmente {appt.time})
        </p>
        <div>
          <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:6 }}>Nova data <span style={{ color:'#ef4444' }}>*</span></label>
          <input type="date" value={novaData} onChange={e=>{setNData(e.target.value);setErro('');}} style={inputS}/>
        </div>
        <div>
          <label style={{ fontSize:13, fontWeight:500, color:'#374151', display:'block', marginBottom:6 }}>Novo horário <span style={{ color:'#ef4444' }}>*</span></label>
          <input type="time" value={novaHora} onChange={e=>{setNHora(e.target.value);setErro('');}} style={inputS}/>
        </div>
        <label onClick={()=>setPago(p=>!p)} style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer', padding:'10px 12px', background:'#f9fafb', borderRadius:6, userSelect:'none' }}>
          <div style={{ width:16, height:16, borderRadius:4, border:`2px solid ${pago ? C.primary : '#d1d5db'}`, background: pago ? C.primary : 'white', display:'flex', alignItems:'center', justifyContent:'center', transition:'all .15s' }}>
            {pago && <svg width="9" height="7" viewBox="0 0 9 7" fill="none"><path d="M1 3.5l2.5 2.5 4.5-5" stroke="white" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
          </div>
          <span style={{ fontSize:13, color:'#374151' }}>Sessão já quitada <span style={{ fontSize:12, color:'#9ca3af' }}>(indica que o pagamento já foi realizado)</span></span>
        </label>
        {erro && <p style={{ margin:0, fontSize:12, color:'#ef4444' }}>{erro}</p>}
      </div>
      <div style={{ display:'flex', gap:10, marginTop:18 }}>
        <button onClick={onClose} style={{ flex:1, padding:'9px', background:'white', border:'1px solid #d1d5db', borderRadius:6, fontSize:13, cursor:'pointer', color:'#374151' }}>Cancelar</button>
        <button onClick={handleConfirm} style={{ flex:2, padding:'9px', background:'#eab308', color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>Confirmar reagendamento</button>
      </div>
    </Modal>
  );
}

/* ── Visão Mensal ── */
const MONTH_DAYS_MAP = {
  Janeiro:31, Fevereiro:28, Março:31, Abril:30, Maio:31, Junho:30,
  Julho:31, Agosto:31, Setembro:30, Outubro:31, Novembro:30, Dezembro:31,
};
const MONTH_START_DOW = { Janeiro:3, Fevereiro:6, Março:6, Abril:2, Maio:4, Junho:0, Julho:2, Agosto:5, Setembro:1, Outubro:3, Novembro:6, Dezembro:1 };
const DOW_LABELS = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];

// Map week day keys to day-of-month numbers — aligned with WEEK_DAYS data
const WEEK_KEY_TO_DOM = { seg:11, ter:12, qua:13, qui:14, sex:15, sab:16, dom:10 };

function MonthView({ appts, month, onApptClick }) {
  const totalDays = MONTH_DAYS_MAP[month] || 30;
  const startDow  = MONTH_START_DOW[month] || 0;

  // Map appointments to day-of-month
  const apptsByDay = {};
  appts.forEach(a => {
    const dom = WEEK_KEY_TO_DOM[a.day] || 1;
    if (!apptsByDay[dom]) apptsByDay[dom] = [];
    apptsByDay[dom].push(a);
  });

  // Build calendar grid cells
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= totalDays; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const today = 6; // mock today

  return (
    <div style={{ display:'flex', flexDirection:'column', flex:1 }}>
      {/* Day-of-week header */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', borderBottom:'1px solid #e5e7eb', flexShrink:0 }}>
        {DOW_LABELS.map(d => (
          <div key={d} style={{ padding:'8px 0', textAlign:'center', fontSize:11, fontWeight:700, color:'#9ca3af', textTransform:'uppercase', letterSpacing:'.06em' }}>{d}</div>
        ))}
      </div>
      {/* Weeks — each row gets equal flex share */}
      <div style={{ flex:1, display:'flex', flexDirection:'column' }}>
      {Array.from({ length: cells.length / 7 }, (_, wi) => (
        <div key={wi} style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', borderBottom: wi < cells.length/7-1 ? '1px solid #f0f0f0' : 'none', flex:1 }}>
          {cells.slice(wi*7, wi*7+7).map((day, di) => {
            const dayAppts = day ? (apptsByDay[day] || []) : [];
            const isToday  = day === today;
            return (
              <div key={di} style={{ minHeight:100, padding:'6px 8px', borderRight: di<6 ? '1px solid #f0f0f0' : 'none', background: day ? 'white' : '#fafafa', verticalAlign:'top' }}>
                {day && (
                  <>
                    <div style={{ marginBottom:4 }}>
                      <span style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', width:22, height:22, borderRadius:'50%', fontSize:12, fontWeight:600, background: isToday ? C.primary : 'transparent', color: isToday ? 'white' : '#374151' }}>{day}</span>
                    </div>
                    {dayAppts.slice(0,3).map((a,i) => {
                      const c = APPT_COLORS[a.status] || APPT_COLORS.aguardando;
                      return (
                        <div key={a.id} onClick={() => onApptClick(a)}
                          style={{ marginBottom:2, padding:'2px 6px', background:c.bg, borderLeft:`2px solid ${c.border}`, borderRadius:3, fontSize:10, fontWeight:600, color:c.text, cursor:'pointer', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', lineHeight:1.5 }}
                          onMouseEnter={e=>e.currentTarget.style.filter='brightness(0.95)'}
                          onMouseLeave={e=>e.currentTarget.style.filter='none'}>
                          {a.time} {a.patient}
                        </div>
                      );
                    })}
                    {dayAppts.length > 3 && (
                      <div style={{ fontSize:10, color:'#6b7280', padding:'1px 4px' }}>+{dayAppts.length-3} mais</div>
                    )}
                  </>
                )}
              </div>
            );
          })}
        </div>
      ))}
      </div>
    </div>
  );
}

/* ── Agenda principal ── */
function Agenda({ setModal, perfil='admin' }) {
  const [appts,    setAppts]   = agState(INIT_APPTS);
  const [month,    setMonth]   = agState('Junho');
  const [viewMode, setViewMode]= agState('Semana');
  const [selected, setSelected]= agState(null);   // appt sendo operado
  const [modalT,   setModalT]  = agState(null);   // 'detalhe'|'cancelar'|'falta'|'reagendar'
  const [toast,    setToast]   = agState(null);
  const [prontuTela,   setProntuTela]   = agState(null);
  const [prontuarios,  setProntuarios]  = agState([]);

  const months = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
  const mi = months.indexOf(month);
  const totalH = HOURS.length * SLOT_H;

  const showToast = msg => setToast(msg);

  const openModal = (appt, tipo) => { setSelected(appt); setModalT(tipo); };
  const closeModal = () => { setSelected(null); setModalT(null); };

  const updateStatus = (id, status) =>
    setAppts(as => as.map(a => a.id===id ? {...a, status} : a));

  const addAppt = (base, novaData, novaHora) => {
    const day = WEEK_DAYS[new Date(novaData).getDay()-1]?.key || base.day;
    setAppts(as => [...as, { ...base, id:uid(), day, time:novaHora, status:'aguardando' }]);
  };

  /* Handlers */
  const handleConfirmar = () => {
    updateStatus(selected.id, 'confirmado');
    closeModal();
    showToast('Consulta confirmada com sucesso.');
  };

  const handleIniciar = () => {
    setProntuTela({...selected, day: selected.day});
    closeModal();
  };

  const handleSaveProntuario = (dados) => {
    setProntuarios(prev => {
      const exists = prev.findIndex(p => p.apptId === dados.apptId);
      if (exists >= 0) { const n=[...prev]; n[exists]=dados; return n; }
      return [...prev, dados];
    });
    setProntuTela(null);
  };

  const handleCancelar = ({ tipo, motivo, responsavel, reagendar, novaData, novaHora }) => {
    if (tipo === 'cancelamento') {
      updateStatus(selected.id, 'cancelado');
      closeModal();
      showToast('Consulta cancelada com sucesso.');
    } else {
      // falta
      updateStatus(selected.id, 'falta');
      if (reagendar && novaData && novaHora) addAppt(selected, novaData, novaHora);
      closeModal();
      if (responsavel==='terapeuta')
        showToast(reagendar ? 'Falta registrada. Consulta disponível para reagendamento.' : 'Falta do terapeuta registrada.');
      else if (reagendar)
        showToast('Falta registrada e consulta reagendada com sucesso.');
      else
        showToast('Falta registrada com sucesso.');
    }
  };

  const handleReagendar = ({ novaData, novaHora, pago }) => {
    updateStatus(selected.id, 'reagendado');
    if (novaData && novaHora) addAppt(selected, novaData, novaHora);
    closeModal();
    showToast('Consulta reagendada com sucesso.');
  };

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, background:C.pageBg }}>
      <Topbar title="Agenda de Atendimentos" />

      {/* Toolbar */}
      <div style={{ background:'white', borderBottom:'1px solid #e5e7eb', padding:'10px 24px', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
        <button onClick={() => setMonth(months[Math.max(0,mi-1)])} style={{ background:'none', border:'none', cursor:'pointer', color:'#6b7280', fontSize:18 }}>‹</button>
        <span style={{ fontSize:14, fontWeight:600, color:'#111', minWidth:80 }}>{month}</span>
        <button onClick={() => setMonth(months[Math.min(11,mi+1)])} style={{ background:'none', border:'none', cursor:'pointer', color:'#6b7280', fontSize:18 }}>›</button>
        <select value={viewMode} onChange={e=>setViewMode(e.target.value)}
          style={{ fontSize:13, border:'1px solid #e5e7eb', borderRadius:6, padding:'5px 10px', color:'#374151', background:'white', cursor:'pointer' }}>
          <option>Semana</option><option>Mês</option>
        </select>
        <div style={{ flex:1 }}/>
        {[
          { label:'Todas as unidades', opts:['Todas as unidades','Unidade Centro','Unidade Jardins'] },
          { label:'Todas as salas',    opts:['Todas as salas','Sala 201','Sala 202','Sala 203'] },
          { label:'Todos os profissionais', opts:['Todos os profissionais','Dra. Ana Silva','Dr. Carlos Mendes'] },
        ].map(s => (
          <select key={s.label} style={{ fontSize:13, border:'1px solid #e5e7eb', borderRadius:6, padding:'5px 10px', color:'#374151', background:'white', cursor:'pointer' }}>
            {s.opts.map(o => <option key={o}>{o}</option>)}
          </select>
        ))}
        <button onClick={() => setModal('agendarConsulta')}
          style={{ display:'flex', alignItems:'center', gap:6, padding:'8px 16px', background:C.primary, color:'white', border:'none', borderRadius:6, fontSize:13, fontWeight:600, cursor:'pointer' }}>
          <span style={{ fontSize:16, lineHeight:1 }}>+</span> Nova Consulta
        </button>
      </div>

      {/* Calendário */}
      <div style={{ flex:1, overflowY:'auto', padding:'16px 24px', display:'flex', flexDirection:'column' }}>
        <Card style={{ overflow:'hidden', flex:1, display:'flex', flexDirection:'column' }}>
          <div style={{ padding:'14px 18px', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:'1px solid #f0f0f0' }}>
            <h2 style={{ margin:0, fontSize:15, fontWeight:600, color:'#111' }}>{viewMode === 'Semana' ? 'Agenda da semana' : `Agenda de ${month}`}</h2>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <select style={{ fontSize:13, border:'1px solid #e5e7eb', borderRadius:6, padding:'5px 10px', background:'white', cursor:'pointer' }}>
                <option>Todos os profissionais</option><option>Dra. Ana Silva</option><option>Dr. Carlos Mendes</option>
              </select>
              <button style={{ background:'none', border:'none', cursor:'pointer', color:'#6b7280', fontSize:18 }}>‹</button>
              <span style={{ fontSize:13, fontWeight:500, color:'#374151' }}>{viewMode === 'Semana' ? 'Semana atual' : month}</span>
              <button style={{ background:'none', border:'none', cursor:'pointer', color:'#6b7280', fontSize:18 }}>›</button>
            </div>
          </div>

          {/* Vista Mensal */}
          {viewMode === 'Mês' && (
            <div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden' }}>
              <MonthView appts={appts} month={month} onApptClick={ap => openModal(ap,'detalhe')} />
            </div>
          )}

          {/* Vista Semanal */}
          {viewMode === 'Semana' && (<div style={{ display:'flex' }}>
            <div style={{ width:60, flexShrink:0 }}>
              <div style={{ height:40 }}/>
              {HOURS.map(h => (
                <div key={h} style={{ height:SLOT_H, display:'flex', alignItems:'center', justifyContent:'flex-end', paddingRight:10 }}>
                  <span style={{ fontSize:11, color:'#9ca3af', whiteSpace:'nowrap' }}>{h}</span>
                </div>
              ))}
            </div>
            {WEEK_DAYS.map(d => {
              const dayAppts = appts.filter(a => a.day===d.key);
              return (
                <div key={d.key} style={{ flex:1, borderLeft:'1px solid #f0f0f0' }}>
                  <div style={{ height:40, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', borderBottom:'1px solid #f0f0f0' }}>
                    <span style={{ fontSize:11, color:'#9ca3af', fontWeight:500 }}>{d.label}</span>
                    <span style={{ fontSize:15, fontWeight:600, color:'#111' }}>{d.num}</span>
                  </div>
                  <div style={{ position:'relative', height:totalH }}>
                    {HOURS.map((h,i) => (
                      <div key={h} style={{ position:'absolute', left:0, right:0, top:i*SLOT_H, height:SLOT_H, borderBottom:'1px solid #f5f5f5' }}/>
                    ))}
                    {dayAppts.map(a => (
                      <AgendaApptBlock key={a.id} appt={a} onClick={ap => openModal(ap,'detalhe')} />
                    ))}
                  </div>
                </div>
              );
            })}
          </div>)}
        </Card>
      </div>

      {/* Legenda */}
      <div style={{ background:'white', borderTop:'1px solid #e5e7eb', padding:'8px 24px', display:'flex', gap:20, flexShrink:0, flexWrap:'wrap' }}>
        {STATUS_LEGEND_ITEMS.map(s => (
          <div key={s.key} style={{ display:'flex', alignItems:'center', gap:6 }}>
            <div style={{ width:10, height:10, borderRadius:3, background:s.border, flexShrink:0 }}/>
            <span style={{ fontSize:12, color:'#374151' }}>{s.label}</span>
          </div>
        ))}
      </div>

      {/* Ações Rápidas */}
      <div style={{ flexShrink:0, background:'white', borderTop:'1px solid #e5e7eb', padding:'12px 24px', display:'flex', alignItems:'center', gap:12 }}>
        <span style={{ fontSize:13, fontWeight:600, color:'#374151', marginRight:4 }}>Ações rápidas</span>
        {[
          { label:'Novo Paciente',         icon:'pacientes', action:() => setModal('novoPaciente') },
          { label:'Agendar Consulta',      icon:'agenda',    action:() => setModal('agendarConsulta') },
          { label:'Lançamento Financeiro', icon:'financeiro',action:() => setModal('lancamento') },
        ].map(a => (
          <button key={a.label} onClick={a.action}
            style={{ display:'flex', alignItems:'center', gap:7, padding:'8px 16px', background:'white', border:'1px solid #e5e7eb', borderRadius:6, cursor:'pointer', fontSize:13, color:'#374151', fontWeight:500 }}
            onMouseEnter={e=>e.currentTarget.style.background='#f9fafb'}
            onMouseLeave={e=>e.currentTarget.style.background='white'}>
            <Icon name={a.icon} size={15} color={C.primary}/>{a.label}
          </button>
        ))}
      </div>

      {/* Modais */}
      {modalT==='detalhe'  && selected && <ModalDetalhe  appt={selected} perfil={perfil} onClose={closeModal} onCancelar={()=>setModalT('cancelar')} onReagendar={()=>setModalT('reagendar')} onConfirmar={handleConfirmar} onIniciar={handleIniciar} />}
      {modalT==='cancelar' && selected && <ModalCancelar appt={selected} onClose={closeModal} onConfirm={handleCancelar} />}
      {modalT==='reagendar'&& selected && <ModalReagendar appt={selected} onClose={closeModal} onConfirm={handleReagendar} />}

      {/* Tela Prontuário */}
      {prontuTela && (
        <div style={{ position:'fixed', inset:0, zIndex:1000, display:'flex' }}>
          <TelaProntuario
            appt={prontuTela}
            existente={prontuarios.find(p => p.apptId === prontuTela.id)}
            prontuarios={prontuarios}
            onSave={handleSaveProntuario}
            onVoltar={() => setProntuTela(null)}
          />
        </div>
      )}

      {/* Toast */}
      {toast && <AgendaToast msg={toast} onDone={() => setToast(null)} />}

      <style>{`@keyframes fadeInUp{from{opacity:0;transform:translateX(-50%) translateY(10px)}to{opacity:1;transform:translateX(-50%) translateY(0)}}`}</style>
    </div>
  );
}

Object.assign(window, { Agenda });
