
// Events / Calendar Module

function Events({ onNavigate }) {
  const [view, setView] = React.useState('month');
  const [events, setEvents] = React.useState([]);
  const [appUsers, setAppUsers] = React.useState([]);
  const [reportModal, setReportModal] = React.useState(null); // { event, type }
  const [loading, setLoading] = React.useState(true);
  const [selectedEvent, setSelectedEvent] = React.useState(null);
  const [addModal, setAddModal] = React.useState(false);
  const [editEventModal, setEditEventModal] = React.useState(false);
  const [editEventForm, setEditEventForm] = React.useState({ name: '', client: '', type: 'Inauguração', location: '', date: '', date_end: '', time: '09:00', vendedor_id: '', responsavel_producao_id: '' });
  const [savingEvent, setSavingEvent] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', client: '', type: 'Inauguração', date: '2026-04-22', date_end: '', time: '09:00', location: '', vendedor_id: '', responsavel_producao_id: '' });
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };

  const mapRow = (row) => {
    const d = row.event_date ? new Date(row.event_date + 'T00:00:00') : null;
    return {
      id: row.id,
      name: row.name,
      client: row.client_name,
      type: row.type,
      day: d ? d.getDate() : 1,
      month: d ? d.getMonth() + 1 : 1,
      year: d ? d.getFullYear() : new Date().getFullYear(),
      date_iso: row.event_date || '',
      date_end_iso: row.event_end_date || '',
      time: row.event_time || '',
      duration: row.duration || '',
      color: row.color || '#3B82F6',
      status: row.status || 'Planejamento',
      team: row.team || [],
      budget: row.budget || 0,
      location: row.location || '',
      vendedor_id: row.vendedor_id || '',
      responsavel_producao_id: row.responsavel_producao_id || '',
    };
  };

  React.useEffect(() => {
    sb.from('events').select('*').order('event_date').then(({ data, error }) => {
      if (data) setEvents(data.map(mapRow));
      setLoading(false);
    });
    Promise.all([
      sb.from('app_users').select('id, name, email, role').order('name'),
      sb.auth.getUser(),
    ]).then(([listRes, authRes]) => {
      const list = listRes.data || [];
      const cu = authRes.data?.user;
      if (cu && !list.some(u => u.id === cu.id)) {
        list.unshift({
          id: cu.id,
          name: cu.user_metadata?.name || (cu.email ? cu.email.split('@')[0] : 'Eu'),
          email: cu.email || '',
          role: 'admin',
        });
      }
      setAppUsers(list);
    });
  }, []);

  const userName = (id) => {
    const u = appUsers.find(x => x.id === id);
    return u ? (u.name || u.email) : '—';
  };
  const userOptions = [{ value: '', label: '— Selecionar —' }, ...appUsers.map(u => ({ value: u.id, label: u.name || u.email }))];

  const addEvent = async () => {
    if (!form.name.trim()) return;
    const { data, error } = await sb.from('events').insert({
      name: form.name,
      client_name: form.client,
      type: form.type,
      event_date: form.date,
      event_end_date: form.date_end || null,
      event_time: form.time,
      duration: '1 dia',
      color: '#3B82F6',
      status: 'Planejamento',
      team: [],
      location: form.location,
      vendedor_id: form.vendedor_id || null,
      responsavel_producao_id: form.responsavel_producao_id || null,
    }).select().single();
    if (data) {
      setEvents(prev => [...prev, mapRow(data)]);
      showToast('Evento criado com sucesso!');
    } else {
      showToast('Erro ao criar evento', 'danger');
    }
    setAddModal(false);
    setForm({ name: '', client: '', type: 'Inauguração', date: '2026-04-22', date_end: '', time: '09:00', location: '', vendedor_id: '', responsavel_producao_id: '' });
  };

  const openEditEvent = () => {
    if (!selectedEvent) return;
    setEditEventForm({
      name: selectedEvent.name || '',
      client: selectedEvent.client || '',
      type: selectedEvent.type || 'Inauguração',
      location: selectedEvent.location || '',
      date: selectedEvent.date_iso || '',
      date_end: selectedEvent.date_end_iso || '',
      time: selectedEvent.time || '09:00',
      vendedor_id: selectedEvent.vendedor_id || '',
      responsavel_producao_id: selectedEvent.responsavel_producao_id || '',
    });
    setEditEventModal(true);
  };

  const handleEditEvent = async () => {
    if (!editEventForm.name.trim()) { showToast('Preencha o nome do evento.', 'danger'); return; }
    setSavingEvent(true);
    const { data, error } = await sb.from('events').update({
      name: editEventForm.name,
      client_name: editEventForm.client,
      type: editEventForm.type,
      location: editEventForm.location,
      event_date: editEventForm.date || selectedEvent.date_iso,
      event_end_date: editEventForm.date_end || null,
      event_time: editEventForm.time || selectedEvent.time,
      vendedor_id: editEventForm.vendedor_id || null,
      responsavel_producao_id: editEventForm.responsavel_producao_id || null,
    }).eq('id', selectedEvent.id).select().single();
    setSavingEvent(false);
    if (error) { showToast('Erro ao salvar evento.', 'danger'); return; }
    const updated = mapRow(data);
    setEvents(prev => prev.map(e => e.id === updated.id ? updated : e));
    setSelectedEvent(updated);
    setEditEventModal(false);
    showToast('Evento atualizado!');
  };

  const handleCancelEvent = async () => {
    if (!selectedEvent) return;
    const isCancelled = selectedEvent.status === 'Cancelado';
    const newStatus = isCancelled ? 'Planejamento' : 'Cancelado';
    const msg = isCancelled
      ? 'Reativar este evento? Ele voltará para o status "Planejamento".'
      : 'Cancelar este evento? O registro será mantido no histórico.';
    if (!window.confirm(msg)) return;
    setSavingEvent(true);
    const { data, error } = await sb.from('events').update({ status: newStatus }).eq('id', selectedEvent.id).select().single();
    setSavingEvent(false);
    if (error) { showToast('Erro ao atualizar evento.', 'danger'); return; }
    const updated = mapRow(data);
    setEvents(prev => prev.map(e => e.id === updated.id ? updated : e));
    setSelectedEvent(updated);
    showToast(isCancelled ? 'Evento reativado!' : 'Evento cancelado.');
  };

  const checklist = [
    { label: 'Aprovação de Orçamento',          done: false },
    { label: 'Conferir Produção',               done: false },
    { label: 'Ação Definida',                   done: false },
    { label: 'Equipe Contratada',               done: false },
    { label: 'Equip. Separados e Revisados',    done: false },
    { label: 'Montagem Agendada',               done: false },
  ];
  const [checks, setChecks] = React.useState(checklist);

  const EVENT_TYPES = [
    { value: 'Inauguração', label: 'Inauguração' },
    { value: 'Ativação de Marca', label: 'Ativação de Marca' },
    { value: 'Ação Promocional', label: 'Ação Promocional' },
    { value: 'Panfletagem', label: 'Panfletagem' },
    { value: 'Sampling', label: 'Sampling' },
    { value: 'Confraternização', label: 'Confraternização' },
    { value: 'Corporativo', label: 'Corporativo' },
    { value: 'Outro', label: 'Outro' },
  ];
  const typeColor = { 'Inauguração': '#3B82F6', 'Ativação de Marca': '#8B5CF6', 'Ação Promocional': '#10B981', 'Panfletagem': '#F59E0B', 'Sampling': '#EF4444', 'Confraternização': '#EC4899', 'Corporativo': '#3B82F6', 'Outro': '#64748B' };
  const statusVariant = { 'Confirmado': 'success', 'Planejamento': 'warning', 'Orçamento': 'default', 'Em andamento': 'primary', 'Cancelado': 'danger' };

  const MONTH_NAMES = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
  const MONTH_SHORT = ['JAN', 'FEV', 'MAR', 'ABR', 'MAI', 'JUN', 'JUL', 'AGO', 'SET', 'OUT', 'NOV', 'DEZ'];

  const [currentDate, setCurrentDate] = React.useState(() => { const d = new Date(); d.setDate(1); return d; });
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth(); // 0-indexed
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const startDay = new Date(year, month, 1).getDay();
  const realToday = new Date();
  const isCurrentMonth = realToday.getFullYear() === year && realToday.getMonth() === month;
  const today = isCurrentMonth ? realToday.getDate() : -1;

  const goToPrevMonth = () => setCurrentDate(new Date(year, month - 1, 1));
  const goToNextMonth = () => setCurrentDate(new Date(year, month + 1, 1));
  const goToToday = () => { const d = new Date(); d.setDate(1); setCurrentDate(d); };

  const eventsThisMonth = events.filter(e => e.month === month + 1 && e.year === year);
  const getEventsForDay = (day) => eventsThisMonth.filter(e => e.day === day);

  const MonthView = () => (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 0 }}>
        {['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'].map(d => (
          <div key={d} style={{ padding: '10px 12px', fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', borderBottom: `1px solid ${DS.colors.border}` }}>{d}</div>
        ))}
        {Array.from({ length: startDay }).map((_, i) => (
          <div key={`empty-${i}`} style={{ minHeight: 100, background: '#FAFAFA', borderRight: `1px solid ${DS.colors.border}`, borderBottom: `1px solid ${DS.colors.border}` }} />
        ))}
        {Array.from({ length: daysInMonth }).map((_, i) => {
          const day = i + 1;
          const dayEvents = getEventsForDay(day);
          const isToday = day === today;
          return (
            <div key={day} style={{ minHeight: 100, borderRight: `1px solid ${DS.colors.border}`, borderBottom: `1px solid ${DS.colors.border}`, padding: 8, background: isToday ? '#EFF6FF' : '#fff' }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12, fontWeight: isToday ? 800 : 500,
                background: isToday ? DS.colors.primary : 'transparent',
                color: isToday ? '#fff' : DS.colors.text, marginBottom: 4,
              }}>{day}</div>
              {dayEvents.map(ev => {
                const isCancelled = ev.status === 'Cancelado';
                return (
                  <div key={ev.id} onClick={() => setSelectedEvent(ev)}
                    style={{ background: isCancelled ? '#94A3B8' : ev.color, color: '#fff', borderRadius: 4, padding: '2px 6px', fontSize: 10, fontWeight: 600, marginBottom: 2, cursor: 'pointer', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', opacity: isCancelled ? 0.7 : 1, textDecoration: isCancelled ? 'line-through' : 'none' }}>
                    {ev.time} {ev.name}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );

  const ListView = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {[...eventsThisMonth].sort((a, b) => a.day - b.day).map(ev => {
        const isCancelled = ev.status === 'Cancelado';
        const accent = isCancelled ? '#94A3B8' : ev.color;
        return (
          <Card key={ev.id} hover onClick={() => setSelectedEvent(ev)} style={{ padding: '16px 20px', opacity: isCancelled ? 0.65 : 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <div style={{ width: 4, borderRadius: 2, alignSelf: 'stretch', background: accent, flexShrink: 0 }} />
              <div style={{ width: 52, height: 52, borderRadius: DS.radius.sm, background: accent + '15', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: accent, lineHeight: 1 }}>{ev.day}</div>
                <div style={{ fontSize: 10, color: accent, fontWeight: 600 }}>{MONTH_SHORT[ev.month - 1]}</div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text, textDecoration: isCancelled ? 'line-through' : 'none' }}>{ev.name}</div>
                <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 2 }}>{ev.client} · {ev.location}</div>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <Badge variant="default">{ev.type}</Badge>
                <Badge variant={statusVariant[ev.status] || 'default'}>{ev.status}</Badge>
              </div>
            </div>
          </Card>
        );
      })}
    </div>
  );

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Agenda de Eventos</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>{MONTH_NAMES[month]} {year} · {eventsThisMonth.length} eventos programados</p>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <button onClick={goToPrevMonth} aria-label="Mês anterior" style={{ width: 32, height: 32, borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}`, background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: DS.colors.text }}>
              <Icon name="chevronLeft" size={16} />
            </button>
            <button onClick={goToToday} style={{ padding: '6px 12px', borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}`, background: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: DS.colors.text }}>Hoje</button>
            <button onClick={goToNextMonth} aria-label="Próximo mês" style={{ width: 32, height: 32, borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}`, background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: DS.colors.text }}>
              <Icon name="chevronRight" size={16} />
            </button>
          </div>
          <div style={{ display: 'flex', gap: 2, background: '#F1F5F9', padding: 3, borderRadius: DS.radius.sm }}>
            {[['month', 'Mensal'], ['week', 'Semanal'], ['list', 'Lista']].map(([v, l]) => (
              <button key={v} onClick={() => setView(v)} style={{
                padding: '5px 12px', borderRadius: 6, border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                background: view === v ? '#fff' : 'transparent', color: view === v ? DS.colors.text : DS.colors.textSec,
                boxShadow: view === v ? DS.shadow.sm : 'none', transition: 'all 0.15s',
              }}>{l}</button>
            ))}
          </div>
          <Btn icon="plus" onClick={() => setAddModal(true)}>Novo evento</Btn>
        </div>
      </div>

      <Card>
        {loading ? <Spinner /> : (
          <>
            {(view === 'month' || view === 'week') && <MonthView />}
            {view === 'list' && <div style={{ padding: 20 }}><ListView /></div>}
          </>
        )}
      </Card>

      {/* Event detail modal */}
      <Modal open={!!selectedEvent} onClose={() => setSelectedEvent(null)} title={selectedEvent?.name || ''} width={600}>
        {selectedEvent && (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}>
              {[
                { label: 'Cliente', value: selectedEvent.client },
                (() => {
                  const startStr = `${selectedEvent.day} ${MONTH_SHORT[(selectedEvent.month || 1) - 1]}`;
                  if (selectedEvent.date_end_iso && selectedEvent.date_end_iso !== selectedEvent.date_iso) {
                    const e = new Date(selectedEvent.date_end_iso + 'T00:00:00');
                    const endStr = `${e.getDate()} ${MONTH_SHORT[e.getMonth()]}`;
                    return { label: 'Período', value: `${startStr} → ${endStr} · ${selectedEvent.time}` };
                  }
                  return { label: 'Data e hora', value: `${startStr} · ${selectedEvent.time}` };
                })(),
                { label: 'Tipo', value: selectedEvent.type },
                { label: 'Local', value: selectedEvent.location },
                { label: 'Duração', value: selectedEvent.duration },
                { label: 'Status', value: selectedEvent.status },
                { label: 'Resp. Comercial', value: userName(selectedEvent.vendedor_id) },
                { label: 'Resp. Produção', value: userName(selectedEvent.responsavel_producao_id) },
              ].map(({ label, value }) => (
                <div key={label} style={{ padding: '12px 16px', background: '#F8FAFC', borderRadius: DS.radius.sm }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>{label}</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{value}</div>
                </div>
              ))}
            </div>
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 12 }}>Equipe vinculada</div>
              {selectedEvent.team.length > 0 ? (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {selectedEvent.team.map(name => (
                    <div key={name} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px', background: '#F1F5F9', borderRadius: DS.radius.full }}>
                      <Avatar name={name} size={22} />
                      <span style={{ fontSize: 12, fontWeight: 600, color: DS.colors.text }}>{name}</span>
                    </div>
                  ))}
                </div>
              ) : <span style={{ fontSize: 12, color: DS.colors.textMuted }}>Nenhuma equipe vinculada ainda</span>}
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 12 }}>Checklist</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {checks.map((c, i) => (
                  <div key={i} onClick={() => setChecks(ch => ch.map((item, idx) => idx === i ? { ...item, done: !item.done } : item))}
                    style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: DS.radius.sm, cursor: 'pointer', background: c.done ? DS.colors.successLight : '#F8FAFC', transition: 'background 0.15s' }}>
                    <div style={{ width: 18, height: 18, borderRadius: 4, border: `2px solid ${c.done ? DS.colors.success : DS.colors.border}`, background: c.done ? DS.colors.success : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'all 0.15s' }}>
                      {c.done && <Icon name="check" size={11} color="#fff" />}
                    </div>
                    <span style={{ fontSize: 13, color: c.done ? DS.colors.success : DS.colors.text, textDecoration: c.done ? 'line-through' : 'none', fontWeight: c.done ? 400 : 500 }}>{c.label}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <Btn icon="tasks" onClick={() => {
                  localStorage.setItem('ef_tasks_filter_event', selectedEvent.name);
                  if (onNavigate) onNavigate('tasks');
                }}>Ver tarefas</Btn>
                <Btn variant="secondary" icon="edit" onClick={openEditEvent}>Editar evento</Btn>
                <Btn variant="secondary" icon="briefcase" onClick={() => setReportModal({ event: selectedEvent, type: 'PP' })}>Pedido de Produção</Btn>
                <Btn variant="secondary" icon="photo" onClick={() => setReportModal({ event: selectedEvent, type: 'RF' })}>Relatório Fotográfico</Btn>
                <Btn
                  variant={selectedEvent.status === 'Cancelado' ? 'success' : 'danger'}
                  icon={selectedEvent.status === 'Cancelado' ? 'check' : 'x'}
                  onClick={handleCancelEvent}
                  disabled={savingEvent}
                  style={{ marginLeft: 'auto' }}
                >
                  {selectedEvent.status === 'Cancelado' ? 'Reativar evento' : 'Cancelar evento'}
                </Btn>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* Add event modal */}
      <Modal open={addModal} onClose={() => setAddModal(false)} title="Novo Evento">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Input label="Nome do evento" value={form.name} onChange={v => setForm(f => ({ ...f, name: v }))} placeholder="Ex: Congresso Tech 2027" />
          <Input label="Cliente" value={form.client} onChange={v => setForm(f => ({ ...f, client: v }))} placeholder="Ex: TechCorp Brasil" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Tipo" value={form.type} onChange={v => setForm(f => ({ ...f, type: v }))} options={EVENT_TYPES} />
            <Input label="Horário" value={form.time} onChange={v => setForm(f => ({ ...f, time: v }))} placeholder="09:00" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Data início" value={form.date} onChange={v => setForm(f => ({ ...f, date: v }))} type="date" />
            <Input label="Data fim (opcional)" value={form.date_end} onChange={v => setForm(f => ({ ...f, date_end: v }))} type="date" />
          </div>
          <Input label="Local" value={form.location} onChange={v => setForm(f => ({ ...f, location: v }))} placeholder="Ex: Centro de Convenções SP" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Responsável Comercial" value={form.vendedor_id} onChange={v => setForm(f => ({ ...f, vendedor_id: v }))} options={userOptions} />
            <Select label="Responsável Produção" value={form.responsavel_producao_id} onChange={v => setForm(f => ({ ...f, responsavel_producao_id: v }))} options={userOptions} />
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => setAddModal(false)}>Cancelar</Btn>
            <Btn onClick={addEvent}>Criar evento</Btn>
          </div>
        </div>
      </Modal>

      {/* Modal editar evento */}
      <Modal open={editEventModal} onClose={() => setEditEventModal(false)} title="Editar Evento" width={520}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Input label="Nome do evento *" value={editEventForm.name} onChange={v => setEditEventForm(f => ({ ...f, name: v }))} />
          <Input label="Cliente" value={editEventForm.client} onChange={v => setEditEventForm(f => ({ ...f, client: v }))} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Tipo de evento" value={editEventForm.type} onChange={v => setEditEventForm(f => ({ ...f, type: v }))} options={EVENT_TYPES} />
            <Input label="Horário" value={editEventForm.time} onChange={v => setEditEventForm(f => ({ ...f, time: v }))} placeholder="09:00" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Data início" type="date" value={editEventForm.date} onChange={v => setEditEventForm(f => ({ ...f, date: v }))} />
            <Input label="Data fim (opcional)" type="date" value={editEventForm.date_end} onChange={v => setEditEventForm(f => ({ ...f, date_end: v }))} />
          </div>
          <Input label="Local" value={editEventForm.location} onChange={v => setEditEventForm(f => ({ ...f, location: v }))} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Responsável Comercial" value={editEventForm.vendedor_id} onChange={v => setEditEventForm(f => ({ ...f, vendedor_id: v }))} options={userOptions} />
            <Select label="Responsável Produção" value={editEventForm.responsavel_producao_id} onChange={v => setEditEventForm(f => ({ ...f, responsavel_producao_id: v }))} options={userOptions} />
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => setEditEventModal(false)}>Cancelar</Btn>
            <Btn onClick={handleEditEvent} disabled={savingEvent} icon="check">{savingEvent ? 'Salvando…' : 'Salvar alterações'}</Btn>
          </div>
        </div>
      </Modal>

      {/* Modal de Relatórios (PP / RF / Contrato) */}
      {reportModal && window.EventReport && (
        <window.EventReport
          event={reportModal.event}
          type={reportModal.type}
          appUsers={appUsers}
          onClose={() => setReportModal(null)}
          onSaved={() => showToast('Documento salvo!')}
        />
      )}

      {toast && <Toast message={toast.msg} type={toast.type} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { Events });
