
// Admin Client Area — módulo da EQUIPE pra alimentar o Portal do Cliente
// (timeline de operação, arquivos, aprovações). Não é o portal em si —
// é a tela onde a equipe registra o que o cliente vai ver.

function AdminClientArea() {
  const [events, setEvents] = React.useState([]);
  const [selectedEventId, setSelectedEventId] = React.useState(() => localStorage.getItem('admin_client_area_event') || '');
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState('');

  React.useEffect(() => {
    sb.from('events').select('id, name, client_name, event_date, status').order('event_date', { ascending: false }).then(({ data }) => {
      setEvents(data || []);
      setLoading(false);
    });
  }, []);

  const q = search.trim().toLowerCase();
  const filtered = q
    ? events.filter(e => (e.name || '').toLowerCase().includes(q) || (e.client_name || '').toLowerCase().includes(q))
    : events;

  const selectedEvent = events.find(e => String(e.id) === String(selectedEventId));

  const selectEvent = (id) => {
    setSelectedEventId(id);
    localStorage.setItem('admin_client_area_event', id);
  };

  if (loading) return <div><h1 style={{ fontSize: 24, fontWeight: 700 }}>Portal Cliente (Admin)</h1><Spinner /></div>;

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Portal do Cliente — Administração</h1>
        <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Alimente a timeline da operação, envie arquivos e crie aprovações — tudo aparece no portal do cliente.</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '340px 1fr', gap: 16 }}>
        {/* Lista de eventos */}
        <Card style={{ padding: 0, height: 'calc(100vh - 160px)', overflowY: 'auto' }}>
          <div style={{ padding: 12, borderBottom: `1px solid ${DS.colors.border}`, position: 'sticky', top: 0, background: '#fff', zIndex: 2 }}>
            <div style={{ position: 'relative' }}>
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar por evento ou cliente..."
                style={{ width: '100%', boxSizing: 'border-box', border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, padding: '8px 12px 8px 34px', fontSize: 13, outline: 'none', background: '#fff', fontFamily: 'inherit' }} />
              <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)' }}>
                <Icon name="search" size={13} color={DS.colors.textMuted} />
              </div>
            </div>
          </div>
          {filtered.length === 0 ? (
            <div style={{ padding: 40, textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Nenhum evento encontrado.</div>
          ) : (
            filtered.map((ev, i) => {
              const active = String(ev.id) === String(selectedEventId);
              return (
                <div key={ev.id} onClick={() => selectEvent(String(ev.id))}
                  style={{ padding: '12px 14px', borderBottom: i < filtered.length - 1 ? `1px solid ${DS.colors.border}` : 'none', cursor: 'pointer', background: active ? DS.colors.primaryLight : '#fff', borderLeft: active ? `3px solid ${DS.colors.primary}` : '3px solid transparent', transition: 'all 0.15s' }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{ev.name}</div>
                  <div style={{ fontSize: 11, color: DS.colors.textSec, marginTop: 2 }}>{ev.client_name || '— sem cliente —'}</div>
                  <div style={{ fontSize: 10, color: DS.colors.textMuted, marginTop: 2 }}>{ev.event_date ? new Date(ev.event_date + 'T00:00:00').toLocaleDateString('pt-BR') : '—'} · {ev.status || ''}</div>
                </div>
              );
            })
          )}
        </Card>

        {/* Área do evento selecionado */}
        <div>
          {!selectedEvent ? (
            <Card style={{ padding: 80, textAlign: 'center' }}>
              <Icon name="portal" size={40} color={DS.colors.border} />
              <div style={{ fontSize: 15, fontWeight: 700, color: DS.colors.textSec, marginTop: 14 }}>Selecione um evento à esquerda</div>
              <div style={{ fontSize: 13, color: DS.colors.textMuted, marginTop: 4 }}>Você poderá adicionar atualizações, arquivos e aprovações que o cliente verá no portal.</div>
            </Card>
          ) : (
            <AdminEventPanel event={selectedEvent} />
          )}
        </div>
      </div>
    </div>
  );
}

function AdminEventPanel({ event }) {
  const [tab, setTab] = React.useState('timeline');
  const tabs = [
    { id: 'timeline',   label: 'Timeline da Operação', icon: 'zap'      },
    { id: 'arquivos',   label: 'Arquivos',             icon: 'download' },
    { id: 'aprovacoes', label: 'Aprovações',           icon: 'check'    },
  ];
  return (
    <div>
      <Card style={{ padding: '18px 22px', marginBottom: 14, background: `linear-gradient(135deg, ${DS.colors.primary} 0%, #C45508 100%)`, border: 'none' }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Evento selecionado</div>
        <div style={{ fontSize: 20, fontWeight: 800, color: '#fff', marginTop: 4 }}>{event.name}</div>
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.85)', marginTop: 4 }}>{event.client_name} · {event.event_date ? new Date(event.event_date + 'T00:00:00').toLocaleDateString('pt-BR') : '—'}</div>
      </Card>

      <div style={{ display: 'flex', gap: 4, marginBottom: 16, background: '#F1F5F9', padding: 4, borderRadius: DS.radius.sm, width: 'fit-content' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', borderRadius: 6, border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            background: tab === t.id ? '#fff' : 'transparent',
            color: tab === t.id ? DS.colors.text : DS.colors.textSec,
            boxShadow: tab === t.id ? DS.shadow.sm : 'none',
            display: 'flex', alignItems: 'center', gap: 8,
            fontFamily: 'inherit',
          }}>
            <Icon name={t.icon} size={13} color={tab === t.id ? DS.colors.primary : DS.colors.textSec} />
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'timeline'   && <AdminTimelinePanel event={event} />}
      {tab === 'arquivos'   && <AdminArquivosPanel event={event} />}
      {tab === 'aprovacoes' && <AdminAprovacoesPanel event={event} />}
    </div>
  );
}

// ─────────────────────────────────────────────────────
// Timeline — adicionar update, listar, deletar
// ─────────────────────────────────────────────────────
function AdminTimelinePanel({ event }) {
  const [updates, setUpdates] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showForm, setShowForm] = React.useState(false);
  const [form, setForm] = React.useState({ type: 'chegada', text: '', image_url: '' });
  const [saving, setSaving] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };
  const photoInputRef = React.useRef(null);

  const fetchUpdates = () => {
    sb.from('operation_updates').select('*').eq('event_id', event.id).order('created_at', { ascending: false }).then(({ data }) => {
      setUpdates(data || []);
      setLoading(false);
    });
  };

  React.useEffect(() => { fetchUpdates(); }, [event.id]);

  const handlePhotoUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) { showToast('Só imagens (JPG/PNG/WEBP).', 'error'); return; }
    setUploading(true);
    try {
      const uid = crypto.randomUUID();
      const ext = (file.name.split('.').pop() || 'jpg').toLowerCase();
      const path = `timeline/event_${event.id}/${uid}.${ext}`;
      const { error: upErr } = await sb.storage.from('event-photos').upload(path, file, { contentType: file.type });
      if (upErr) { showToast('Erro no upload: ' + upErr.message, 'error'); return; }
      const { data: pub } = sb.storage.from('event-photos').getPublicUrl(path);
      setForm(f => ({ ...f, image_url: pub.publicUrl, type: f.type === 'chegada' ? 'foto' : f.type }));
      showToast('Foto pronta! Clique em Publicar.');
    } finally {
      setUploading(false);
      if (photoInputRef.current) photoInputRef.current.value = '';
    }
  };

  const handleSave = async () => {
    if (!form.text.trim() && !form.image_url.trim()) {
      showToast('Escreva um texto ou envie uma foto.', 'error'); return;
    }
    setSaving(true);
    const cu = window.currentUser || {};
    const { error } = await sb.from('operation_updates').insert({
      event_id: event.id,
      type: form.type,
      text: form.text.trim() || null,
      image_url: form.image_url.trim() || null,
      created_by: cu.id || null,
      created_by_name: cu.name || null,
    });
    if (error) { showToast('Erro: ' + error.message, 'error'); setSaving(false); return; }

    // Notifica equipe
    if (window.createNotification) {
      const label = { chegada: 'Chegada da equipe', inicio: 'Início da ação', foto: 'Foto da ativação', ocorrencia: 'Ocorrência', encerramento: 'Ação encerrada', nota: 'Atualização' }[form.type];
      await window.createNotification({
        type: 'operation_update', title: `${label} em ${event.name}`, message: form.text.slice(0, 120), link: 'events', icon: 'zap',
      });
    }

    setForm({ type: 'chegada', text: '', image_url: '' });
    setShowForm(false);
    setSaving(false);
    fetchUpdates();
    showToast('Atualização publicada!');
  };

  const handleDelete = async (u) => {
    if (!window.confirm('Remover essa atualização?')) return;
    await sb.from('operation_updates').delete().eq('id', u.id);
    showToast('Removida.');
    fetchUpdates();
  };

  const label = { chegada: 'Chegada da equipe', inicio: 'Início da ação', foto: 'Foto da ativação', ocorrencia: 'Ocorrência', encerramento: 'Ação encerrada', nota: 'Nota livre' };
  const color = { chegada: '#3B82F6', inicio: '#8B5CF6', foto: '#10B981', ocorrencia: '#F59E0B', encerramento: '#059669', nota: '#64748B' };

  if (loading) return <Spinner />;

  return (
    <Card style={{ padding: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>Atualizações publicadas ({updates.length})</div>
        <Btn icon="plus" onClick={() => setShowForm(true)}>Nova atualização</Btn>
      </div>

      {showForm && (
        <Card style={{ padding: 18, marginBottom: 16, background: '#F8FAFC', border: `2px dashed ${DS.colors.border}` }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Select label="Tipo" value={form.type} onChange={v => setForm(f => ({ ...f, type: v }))}
              options={Object.entries(label).map(([k, v]) => ({ value: k, label: v }))} />
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: DS.colors.textSec, marginBottom: 6 }}>Mensagem</label>
              <textarea value={form.text} onChange={e => setForm(f => ({ ...f, text: e.target.value }))}
                placeholder="Ex: Equipe chegou ao local, montagem iniciada às 08h30"
                rows={3}
                style={{ width: '100%', padding: '10px 12px', border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, fontSize: 13, fontFamily: 'inherit', color: DS.colors.text, resize: 'vertical', boxSizing: 'border-box', background: '#fff' }} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: DS.colors.textSec, marginBottom: 6 }}>Foto (opcional)</label>
              {form.image_url ? (
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <img src={form.image_url} alt="preview" style={{ maxWidth: 180, maxHeight: 140, borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}` }} />
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    <button onClick={() => setForm(f => ({ ...f, image_url: '' }))}
                      style={{ padding: '6px 12px', border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, background: '#fff', fontSize: 12, cursor: 'pointer', color: DS.colors.danger, fontFamily: 'inherit' }}>
                      Remover foto
                    </button>
                    <div style={{ fontSize: 11, color: DS.colors.textMuted }}>Publicada no bucket event-photos</div>
                  </div>
                </div>
              ) : (
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  <input ref={photoInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePhotoUpload} />
                  <Btn variant="secondary" icon="photo" onClick={() => photoInputRef.current?.click()} disabled={uploading}>
                    {uploading ? 'Enviando...' : 'Enviar foto do dispositivo'}
                  </Btn>
                  <span style={{ fontSize: 11, color: DS.colors.textMuted }}>ou cole uma URL:</span>
                  <input value={form.image_url} onChange={e => setForm(f => ({ ...f, image_url: e.target.value }))} placeholder="https://..."
                    style={{ flex: 1, minWidth: 200, boxSizing: 'border-box', padding: '8px 12px', border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, fontSize: 12, outline: 'none', fontFamily: 'inherit', color: DS.colors.text, background: '#fff' }} />
                </div>
              )}
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <Btn variant="secondary" onClick={() => setShowForm(false)}>Cancelar</Btn>
              <Btn onClick={handleSave} disabled={saving}>{saving ? 'Publicando...' : 'Publicar'}</Btn>
            </div>
          </div>
        </Card>
      )}

      {updates.length === 0 ? (
        <div style={{ padding: 32, textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Sem atualizações ainda. Clique em "Nova atualização" pra publicar a primeira.</div>
      ) : (
        <div>
          {updates.map((u, i) => (
            <div key={u.id} style={{ display: 'flex', gap: 12, paddingBottom: i < updates.length - 1 ? 16 : 0 }}>
              <div style={{ width: 32, height: 32, borderRadius: '50%', background: (color[u.type] || '#64748B') + '20', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={u.type === 'foto' ? 'photo' : u.type === 'ocorrencia' ? 'alert' : u.type === 'encerramento' ? 'check' : 'zap'} size={13} color={color[u.type] || '#64748B'} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{label[u.type] || u.type}</div>
                    <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: 2 }}>{new Date(u.created_at).toLocaleString('pt-BR')}{u.created_by_name ? ` · por ${u.created_by_name}` : ''}</div>
                  </div>
                  <button onClick={() => handleDelete(u)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4, color: DS.colors.textMuted }}
                    onMouseEnter={e => e.currentTarget.style.color = '#EF4444'}
                    onMouseLeave={e => e.currentTarget.style.color = DS.colors.textMuted}>
                    <Icon name="trash" size={13} color="currentColor" />
                  </button>
                </div>
                {u.text && <div style={{ fontSize: 13, color: DS.colors.text, marginTop: 6, lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>{u.text}</div>}
                {u.image_url && <img src={u.image_url} alt="" style={{ maxWidth: '100%', maxHeight: 200, marginTop: 8, borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}` }} />}
              </div>
            </div>
          ))}
        </div>
      )}

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

// ─────────────────────────────────────────────────────
// Arquivos — upload, listar, deletar, toggle visibilidade
// ─────────────────────────────────────────────────────
function AdminArquivosPanel({ event }) {
  const [files, setFiles] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [uploading, setUploading] = React.useState(false);
  const [category, setCategory] = React.useState('briefing');
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };
  const fileInputRef = React.useRef(null);

  const fetchFiles = () => {
    sb.from('project_files').select('*').eq('event_id', event.id).order('created_at', { ascending: false }).then(({ data }) => {
      setFiles(data || []);
      setLoading(false);
    });
  };

  React.useEffect(() => { fetchFiles(); }, [event.id]);

  const handleUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const uid = crypto.randomUUID();
      const safeName = file.name.replace(/[^a-zA-Z0-9._-]/g, '_');
      const storagePath = `event_${event.id}/${uid}_${safeName}`;

      const { error: upErr } = await sb.storage.from('project-files').upload(storagePath, file, { contentType: file.type });
      if (upErr) { showToast('Erro no upload: ' + upErr.message, 'error'); return; }

      const cu = window.currentUser || {};
      const { error: metaErr } = await sb.from('project_files').insert({
        event_id: event.id,
        category,
        filename: file.name,
        storage_path: storagePath,
        size_bytes: file.size,
        mime_type: file.type || null,
        uploaded_by: cu.id || null,
        uploaded_by_name: cu.name || null,
        visible_to_client: true,
      });
      if (metaErr) {
        // Rollback storage
        await sb.storage.from('project-files').remove([storagePath]);
        showToast('Erro ao salvar metadata: ' + metaErr.message, 'error');
        return;
      }
      showToast('Arquivo enviado! O cliente já pode baixar.');
      fetchFiles();

      // Avisa o cliente no WhatsApp — senão ele só descobre se abrir o portal
      const aviso = await window.notifyClientWhatsApp({
        clientName: event.client_name,
        text: `Olá! A Promoup acabou de enviar um novo arquivo (${fileCategoryLabel(category)}) da ação "${event.name}".\n\nAcesse o seu Portal do Cliente para baixar.`,
      });
      showToast(aviso.ok ? aviso.motivo : 'Arquivo salvo, mas o cliente não foi avisado: ' + aviso.motivo, aviso.ok ? 'success' : 'error');
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const handleDelete = async (f) => {
    if (!window.confirm(`Remover "${f.filename}"?\n\nO arquivo é apagado do storage e some do portal do cliente.`)) return;
    await sb.storage.from('project-files').remove([f.storage_path]);
    await sb.from('project_files').delete().eq('id', f.id);
    showToast('Arquivo removido.');
    fetchFiles();
  };

  const handleToggleVisible = async (f) => {
    await sb.from('project_files').update({ visible_to_client: !f.visible_to_client }).eq('id', f.id);
    fetchFiles();
  };

  const handleDownload = async (f) => {
    const { data, error } = await sb.storage.from('project-files').createSignedUrl(f.storage_path, 3600);
    if (error) { showToast('Erro: ' + error.message, 'error'); return; }
    window.open(data.signedUrl, '_blank');
  };

  if (loading) return <Spinner />;

  return (
    <Card style={{ padding: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>Arquivos deste evento ({files.length})</div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <Select value={category} onChange={setCategory} options={[
            { value: 'briefing', label: 'Briefing' },
            { value: 'arte', label: 'Arte' },
            { value: 'contrato', label: 'Contrato' },
            { value: 'nota_fiscal', label: 'Nota Fiscal' },
            { value: 'relatorio', label: 'Relatório' },
            { value: 'outro', label: 'Outro' },
          ]} />
          <input ref={fileInputRef} type="file" style={{ display: 'none' }} onChange={handleUpload}
            accept="image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/zip,text/plain" />
          <Btn icon="plus" onClick={() => fileInputRef.current?.click()} disabled={uploading}>{uploading ? 'Enviando...' : 'Enviar arquivo'}</Btn>
        </div>
      </div>

      {files.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Nenhum arquivo enviado ainda.</div>
      ) : (
        <div>
          {files.map((f, i) => (
            <div key={f.id} style={{ display: 'grid', gridTemplateColumns: '28px 1fr 120px 90px 100px 130px', gap: 12, padding: '12px 0', borderBottom: i < files.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center' }}>
              <Icon name="download" size={14} color={DS.colors.textMuted} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{f.filename}</div>
                <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: 2 }}>{fileCategoryLabel(f.category)} · {f.uploaded_by_name || '—'}</div>
              </div>
              <div style={{ fontSize: 11, color: DS.colors.textSec }}>{formatFileSize(f.size_bytes)}</div>
              <div style={{ fontSize: 11, color: DS.colors.textSec }}>{new Date(f.created_at).toLocaleDateString('pt-BR')}</div>
              <button onClick={() => handleToggleVisible(f)}
                style={{ padding: '4px 8px', borderRadius: 4, border: 'none', fontSize: 11, fontWeight: 600, background: f.visible_to_client ? '#DCFCE7' : '#F1F5F9', color: f.visible_to_client ? DS.colors.success : DS.colors.textMuted, cursor: 'pointer', fontFamily: 'inherit' }}
                title="Alternar visibilidade pro cliente">
                {f.visible_to_client ? 'Visível ✓' : 'Oculto'}
              </button>
              <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                <Btn variant="ghost" size="sm" onClick={() => handleDownload(f)}>Baixar</Btn>
                <button onClick={() => handleDelete(f)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4, color: DS.colors.textMuted }}
                  onMouseEnter={e => e.currentTarget.style.color = '#EF4444'}
                  onMouseLeave={e => e.currentTarget.style.color = DS.colors.textMuted}>
                  <Icon name="trash" size={13} color="currentColor" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

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

// ─────────────────────────────────────────────────────
// Aprovações — admin cria solicitação, cliente decide
// ─────────────────────────────────────────────────────
function AdminAprovacoesPanel({ event }) {
  const [approvals, setApprovals] = React.useState([]);
  const [budgets, setBudgets] = React.useState([]);
  const [clientRow, setClientRow] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [showForm, setShowForm] = React.useState(false);
  const [form, setForm] = React.useState({ resource_type: 'orcamento', resource_id: '', title: '', description: '' });
  const [saving, setSaving] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };

  const fetchAll = async () => {
    setLoading(true);
    // Precisa do client_id via clients.name = event.client_name
    const { data: cli } = await sb.from('clients').select('id, name').eq('name', event.client_name).maybeSingle();
    setClientRow(cli || null);
    if (!cli) { setLoading(false); return; }
    const [{ data: apprs }, { data: buds }] = await Promise.all([
      sb.from('approvals').select('*').eq('event_id', event.id).order('created_at', { ascending: false }),
      sb.from('budgets').select('id, code, event_name').eq('client_name', event.client_name),
    ]);
    setApprovals(apprs || []);
    setBudgets(buds || []);
    setLoading(false);
  };

  React.useEffect(() => { fetchAll(); }, [event.id, event.client_name]);

  const handleCreate = async () => {
    if (!form.title.trim()) { showToast('Título é obrigatório.', 'error'); return; }
    if (!clientRow) { showToast('Cliente não encontrado no CRM.', 'error'); return; }
    setSaving(true);
    const cu = window.currentUser || {};
    const { error } = await sb.from('approvals').insert({
      resource_type: form.resource_type,
      resource_id: form.resource_id || String(event.id),
      event_id: event.id,
      client_id: clientRow.id,
      title: form.title.trim(),
      description: form.description.trim() || null,
      status: 'pendente',
      requested_by: cu.id || null,
    });
    if (error) { showToast('Erro: ' + error.message, 'error'); setSaving(false); return; }

    if (window.createNotification) {
      await window.createNotification({
        type: 'approval_pending', title: `Aprovação criada: ${form.title}`, message: `Aguardando decisão do cliente ${clientRow.name}`, link: 'events', icon: 'clock',
      });
    }

    // Avisa o cliente no WhatsApp que tem algo esperando decisão dele
    const aviso = await window.notifyClientWhatsApp({
      clientId: clientRow.id,
      text: `Olá! A Promoup enviou um item para a sua aprovação:\n\n*${form.title.trim()}*${form.description.trim() ? '\n' + form.description.trim() : ''}\n\nEntre no seu Portal do Cliente, aba Aprovações, para aprovar ou pedir ajuste.`,
    });

    setForm({ resource_type: 'orcamento', resource_id: '', title: '', description: '' });
    setShowForm(false);
    setSaving(false);
    fetchAll();
    showToast(aviso.ok ? 'Aprovação enviada e cliente avisado no WhatsApp!' : 'Aprovação enviada, mas sem aviso: ' + aviso.motivo, aviso.ok ? 'success' : 'error');
  };

  if (loading) return <Spinner />;
  if (!clientRow) {
    return (
      <Card style={{ padding: 40, textAlign: 'center' }}>
        <Icon name="alert" size={32} color={DS.colors.warning} />
        <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text, marginTop: 12 }}>Cliente não vinculado no CRM</div>
        <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 6 }}>Este evento tem client_name "{event.client_name || '(vazio)'}" mas não há cliente com esse nome exato em Clientes. Cadastre ou ajuste o nome no evento.</div>
      </Card>
    );
  }

  const badgeVariant = { pendente: 'warning', aprovado: 'success', ajuste_solicitado: 'primary' };
  const badgeLabel = { pendente: 'Aguardando cliente', aprovado: 'Aprovado', ajuste_solicitado: 'Ajuste solicitado' };

  return (
    <Card style={{ padding: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>Solicitações ({approvals.length})</div>
        <Btn icon="plus" onClick={() => setShowForm(true)}>Nova aprovação</Btn>
      </div>

      {showForm && (
        <Card style={{ padding: 18, marginBottom: 16, background: '#F8FAFC', border: `2px dashed ${DS.colors.border}` }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Select label="Tipo" value={form.resource_type} onChange={v => setForm(f => ({ ...f, resource_type: v }))} options={[
                { value: 'orcamento', label: 'Orçamento' },
                { value: 'arte', label: 'Arte' },
                { value: 'cronograma', label: 'Cronograma' },
                { value: 'outro', label: 'Outro' },
              ]} />
              {form.resource_type === 'orcamento' && budgets.length > 0 && (
                <Select label="Vincular orçamento (opcional)" value={form.resource_id} onChange={v => setForm(f => ({ ...f, resource_id: v }))} options={[
                  { value: '', label: '— nenhum —' },
                  ...budgets.map(b => ({ value: String(b.id), label: `${b.code} · ${b.event_name || ''}` })),
                ]} />
              )}
            </div>
            <Input label="Título *" value={form.title} onChange={v => setForm(f => ({ ...f, title: v }))} placeholder="Ex: Aprovação do orçamento #123" />
            <div>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: DS.colors.textSec, marginBottom: 6 }}>Descrição (opcional)</label>
              <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                placeholder="Contexto pro cliente entender o que está aprovando"
                rows={3}
                style={{ width: '100%', padding: '10px 12px', border: `1px solid ${DS.colors.border}`, borderRadius: DS.radius.sm, fontSize: 13, fontFamily: 'inherit', color: DS.colors.text, resize: 'vertical', boxSizing: 'border-box', background: '#fff' }} />
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <Btn variant="secondary" onClick={() => setShowForm(false)}>Cancelar</Btn>
              <Btn onClick={handleCreate} disabled={saving}>{saving ? 'Enviando...' : 'Enviar pro cliente'}</Btn>
            </div>
          </div>
        </Card>
      )}

      {approvals.length === 0 ? (
        <div style={{ padding: 32, textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Nenhuma solicitação de aprovação nesse evento.</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {approvals.map(a => (
            <div key={a.id} style={{ padding: 14, background: '#F8FAFC', borderRadius: DS.radius.sm, border: `1px solid ${DS.colors.border}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{a.resource_type}</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginTop: 2 }}>{a.title}</div>
                  {a.description && <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 4 }}>{a.description}</div>}
                </div>
                <Badge variant={badgeVariant[a.status] || 'default'}>{badgeLabel[a.status] || a.status}</Badge>
              </div>
              {a.status === 'ajuste_solicitado' && a.ajuste_reason && (
                <div style={{ padding: '8px 12px', background: '#FEF3C7', border: '1px solid #FDE68A', borderRadius: DS.radius.sm, fontSize: 12, color: '#92400E', marginTop: 8 }}>
                  <strong>Cliente pediu:</strong> {a.ajuste_reason}
                </div>
              )}
              {a.decided_at && (
                <div style={{ fontSize: 11, color: DS.colors.textMuted, marginTop: 8 }}>
                  Decidido por {a.decided_by_name || 'cliente'} em {new Date(a.decided_at).toLocaleString('pt-BR')}
                </div>
              )}
            </div>
          ))}
        </div>
      )}

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

Object.assign(window, { AdminClientArea, AdminEventPanel, AdminTimelinePanel, AdminArquivosPanel, AdminAprovacoesPanel });
