
import React, { useState, useEffect, useMemo } from 'react';
import ReactDOM from 'react-dom/client';
import { 
  LayoutDashboard, MessageSquare, Users, Kanban, CheckSquare, Settings, 
  ShieldAlert, LogOut, Bell, Search, Plus, Filter, MoreVertical, Send, 
  ArrowRight, CheckCircle2, XCircle, Clock, AlertCircle, TrendingUp,
  Building2, UserPlus, Trash2, Edit3, Save, X, ChevronRight, UserCheck
} from 'lucide-react';
import { 
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, 
  AreaChart, Area, PieChart, Pie, Cell 
} from 'recharts';

// --- TYPES ---
type UserRole = 'DEVELOPER' | 'DIRECTOR' | 'MANAGER' | 'CONSULTANT';
interface User { id: string; companyId: string; name: string; email: string; role: UserRole; teamId?: string; active: boolean; }
interface Contact { id: string; companyId: string; name: string; phone: string; email: string; type: string; allowAI: boolean; companyName?: string; assignedUserId?: string; status: string; extension?: string; stageId: string; }
interface Stage { id: string; name: string; order: number; noReplyTimeout: number; routingMode: string; isMandatory?: boolean; }
interface Company { id: string; name: string; active: boolean; userLimit: number; memoryLimitGb: number; }

// --- CONSTANTS ---
const COLORS = { primary: '#ff7a59', secondary: '#2d3e50', success: '#00a4bd', warning: '#f5c26b' };

// --- SHARED COMPONENTS ---
const Badge = ({ children, color = 'gray' }: any) => {
  const colors: any = {
    orange: 'bg-orange-50 text-orange-600 border-orange-100',
    blue: 'bg-blue-50 text-blue-600 border-blue-100',
    green: 'bg-green-50 text-green-600 border-green-100',
    gray: 'bg-gray-50 text-gray-600 border-gray-100',
    red: 'bg-red-50 text-red-600 border-red-100'
  };
  return <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider border ${colors[color]}`}>{children}</span>;
};

const Modal = ({ title, isOpen, onClose, children }: any) => {
  if (!isOpen) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-200">
      <div className="bg-white w-full max-w-lg rounded-[2rem] shadow-2xl overflow-hidden animate-in zoom-in-95 duration-300">
        <div className="px-8 py-6 border-b flex justify-between items-center bg-slate-50/50">
          <h3 className="text-xl font-black text-slate-800 tracking-tight">{title}</h3>
          <button onClick={onClose} className="p-2 hover:bg-white rounded-full transition-colors border border-transparent hover:border-slate-200"><X size={20}/></button>
        </div>
        <div className="p-8 max-h-[80vh] overflow-y-auto">{children}</div>
      </div>
    </div>
  );
};

// --- PAGES ---

// 1. DASHBOARD
const DashboardPage = () => {
  const data = [
    { name: 'Seg', v: 40 }, { name: 'Ter', v: 55 }, { name: 'Qua', v: 45 }, 
    { name: 'Qui', v: 70 }, { name: 'Sex', v: 60 }, { name: 'Sab', v: 30 }, { name: 'Dom', v: 20 }
  ];
  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-black text-slate-800 tracking-tight">Visão Geral</h2>
          <p className="text-sm text-slate-400 font-medium">Performance e KPIs da operação.</p>
        </div>
        <div className="flex gap-2">
          <button className="bg-white border text-xs font-bold px-4 py-2 rounded-xl hover:bg-gray-50 transition-colors">Exportar CSV</button>
          <button className="bg-orange-500 text-white text-xs font-bold px-4 py-2 rounded-xl shadow-lg shadow-orange-500/20 hover:bg-orange-600 transition-colors">Filtrar Equipe</button>
        </div>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        {[
          { label: 'Conversas Ativas', val: '154', icon: <MessageSquare size={16}/>, color: 'text-orange-500' },
          { label: 'Novos Leads', val: '24', icon: <Users size={16}/>, color: 'text-blue-500' },
          { label: 'Tempo Médio', val: '3m 12s', icon: <Clock size={16}/>, color: 'text-green-500' },
          { label: 'Taxa Resposta', val: '94%', icon: <TrendingUp size={16}/>, color: 'text-purple-500' },
        ].map((s, i) => (
          <div key={i} className="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
            <div className="flex justify-between items-start mb-2">
              <span className={`p-2 rounded-xl bg-gray-50 ${s.color}`}>{s.icon}</span>
              <span className="text-[10px] font-bold text-green-500">+12%</span>
            </div>
            <p className="text-gray-400 text-[10px] font-bold uppercase tracking-widest">{s.label}</p>
            <h3 className="text-2xl font-black text-slate-800">{s.val}</h3>
          </div>
        ))}
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm h-80">
          <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2 uppercase text-[10px] tracking-widest text-slate-400"><TrendingUp size={14} className="text-orange-500"/> Volume de Mensagens</h3>
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={data}>
              <defs>
                <linearGradient id="colorV" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#ff7a59" stopOpacity={0.1}/>
                  <stop offset="95%" stopColor="#ff7a59" stopOpacity={0}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
              <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{fontSize: 10, fill: '#94a3b8'}} />
              <Tooltip contentStyle={{borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)'}} />
              <Area type="monotone" dataKey="v" stroke="#ff7a59" strokeWidth={3} fillOpacity={1} fill="url(#colorV)" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
        <div className="bg-white p-6 rounded-2xl border border-gray-100 shadow-sm">
          <h3 className="font-black text-slate-800 mb-6 flex items-center gap-2 uppercase text-[10px] tracking-widest text-slate-400"><Users size={14} className="text-orange-500"/> Ranking Performance</h3>
          <div className="space-y-4">
            {['Bruno Silva', 'Alice Souza', 'Daniel Bueno'].map((name, i) => (
              <div key={i} className="flex items-center justify-between group">
                <div className="flex items-center gap-3">
                   <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center font-black text-[10px] text-slate-400">{i+1}</div>
                   <div>
                     <p className="text-xs font-bold text-slate-700">{name}</p>
                     <p className="text-[10px] text-slate-400">Time Vendas SP</p>
                   </div>
                </div>
                <div className="flex items-center gap-2">
                   <div className="w-24 h-1.5 bg-slate-100 rounded-full overflow-hidden">
                      <div className="h-full bg-orange-500" style={{width: `${90 - i * 10}%`}}></div>
                   </div>
                   <span className="text-xs font-black text-slate-800">{95 - i * 5}%</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// 2. KANBAN
interface KanbanProps {
  stages: Stage[];
  contacts: Contact[];
  onMove: (contactId: string, newStageId: string) => void;
  onEdit: (contact: Contact) => void;
}

const KanbanPage = ({ stages, contacts, onMove, onEdit }: KanbanProps) => {
  const [draggedId, setDraggedId] = useState<string | null>(null);

  const handleDragStart = (e: React.DragEvent, id: string) => {
    setDraggedId(id);
    e.dataTransfer.setData('contactId', id);
    e.dataTransfer.effectAllowed = 'move';
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent, stageId: string) => {
    e.preventDefault();
    const contactId = e.dataTransfer.getData('contactId');
    if (contactId) {
      onMove(contactId, stageId);
    }
    setDraggedId(null);
  };

  return (
    <div className="h-full flex flex-col space-y-4 overflow-hidden">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-black text-slate-800 tracking-tight">Pipeline de Atendimento</h2>
          <p className="text-sm text-slate-400 font-medium">Arraste os cards para mudar o status.</p>
        </div>
        <button className="bg-orange-500 text-white text-xs font-bold px-4 py-2 rounded-xl flex items-center gap-2 shadow-lg shadow-orange-500/20 hover:bg-orange-600 transition-all">
          <Plus size={14} /> Novo Card
        </button>
      </div>

      <div className="flex-1 overflow-x-auto pb-4 custom-scrollbar">
        <div className="flex gap-4 h-full min-w-max px-1">
          {(stages || []).sort((a, b) => a.order - b.order).map(stage => (
            <div 
              key={stage.id} 
              onDragOver={handleDragOver}
              onDrop={(e) => handleDrop(e, stage.id)}
              className="kanban-column flex flex-col bg-slate-100/50 rounded-[2.5rem] p-4 border border-slate-200/50"
            >
              <div className="flex justify-between items-center px-4 py-2 mb-4">
                <span className="text-[10px] font-black text-slate-500 uppercase tracking-widest">{stage.name}</span>
                <span className="bg-white px-2.5 py-1 rounded-full text-[10px] font-black border border-slate-200 text-slate-400">
                  {contacts.filter(c => c.stageId === stage.id).length}
                </span>
              </div>

              <div className="flex-1 overflow-y-auto space-y-3 px-1 custom-scrollbar">
                {contacts
                  .filter(c => c.stageId === stage.id)
                  .map((c) => (
                    <div 
                      key={c.id} 
                      draggable 
                      onDragStart={(e) => handleDragStart(e, c.id)}
                      onClick={() => onEdit(c)}
                      className={`bg-white p-5 rounded-3xl border border-slate-200 shadow-sm hover:border-orange-500/40 cursor-grab active:cursor-grabbing transition-all hover:shadow-lg group relative ${draggedId === c.id ? 'opacity-40 grayscale' : ''}`}
                    >
                      <div className="flex justify-between items-start mb-3">
                        <Badge color={c.type === 'Venda' ? 'orange' : 'blue'}>{c.type || 'Geral'}</Badge>
                        <button className="text-slate-200 group-hover:text-slate-400 transition-colors"><MoreVertical size={14}/></button>
                      </div>
                      <h4 className="font-black text-slate-800 text-sm mb-1 leading-tight">{c.name}</h4>
                      <p className="text-[10px] text-slate-400 font-bold uppercase tracking-tight mb-4">{c.companyName || 'S/ Empresa'}</p>
                      
                      <div className="flex justify-between items-center pt-3 border-t border-slate-50">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 rounded-2xl bg-orange-100 border-2 border-white text-[9px] flex items-center justify-center font-black text-orange-600 shadow-sm">{c.name[0]}</div>
                          <span className="text-[10px] font-bold text-slate-400">Responsável</span>
                        </div>
                        <span className="text-[10px] text-slate-400 flex items-center gap-1 font-bold"><Clock size={10}/> 2h</span>
                      </div>
                    </div>
                  ))}
                {contacts.filter(c => c.stageId === stage.id).length === 0 && (
                  <div className="border-2 border-dashed border-slate-200/50 rounded-3xl h-32 flex items-center justify-center text-[10px] font-black text-slate-300 uppercase tracking-widest">
                    Vazio
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// 3. CONTACTS
const ContactsPage = ({ contacts, onEdit }: { contacts: Contact[], onEdit: (c?: Contact) => void }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const filtered = contacts.filter(c => c.name.toLowerCase().includes(searchTerm.toLowerCase()));

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-black text-slate-800 tracking-tight">Base de Contatos</h2>
          <p className="text-sm text-slate-400 font-medium">Controle total dos seus leads.</p>
        </div>
        <button onClick={() => onEdit()} className="bg-orange-500 text-white text-xs font-bold px-5 py-2.5 rounded-xl flex items-center gap-2 shadow-lg shadow-orange-500/20 hover:bg-orange-600 transition-all">
          <UserPlus size={16} /> Novo Contato
        </button>
      </div>

      <div className="bg-white rounded-[2.5rem] border border-slate-200 shadow-sm overflow-hidden">
        <div className="p-6 border-b border-slate-100 bg-slate-50/50 flex justify-between items-center">
          <div className="flex items-center gap-4 bg-white border border-slate-200 px-5 py-2.5 rounded-2xl w-96 shadow-sm">
            <Search size={16} className="text-slate-400"/>
            <input 
              value={searchTerm} 
              onChange={e => setSearchTerm(e.target.value)} 
              placeholder="Buscar por nome, e-mail ou empresa..." 
              className="bg-transparent border-none outline-none text-xs w-full font-bold text-slate-700"
            />
          </div>
          <div className="flex gap-2">
            <button className="p-2.5 border rounded-xl bg-white text-slate-400 hover:text-orange-500 hover:border-orange-200 transition-all shadow-sm"><Filter size={18}/></button>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-100">
                <th className="px-8 py-5 text-[10px] font-black uppercase text-slate-400 tracking-widest">Contato</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase text-slate-400 tracking-widest">Empresa</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase text-slate-400 tracking-widest">Etapa</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase text-slate-400 tracking-widest">IA</th>
                <th className="px-8 py-5 text-right"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.map(c => (
                <tr key={c.id} className="hover:bg-slate-50/80 transition-colors group">
                  <td className="px-8 py-6">
                    <div className="flex items-center gap-4">
                       <div className="w-12 h-12 rounded-2xl bg-slate-100 flex items-center justify-center font-black text-slate-500 text-sm shadow-sm">{c.name[0]}</div>
                       <div>
                         <p className="text-sm font-black text-slate-800">{c.name}</p>
                         <p className="text-[11px] text-slate-400 font-bold uppercase tracking-tight">{c.phone}</p>
                       </div>
                    </div>
                  </td>
                  <td className="px-8 py-6">
                    <span className="text-xs font-bold text-slate-600">{c.companyName || '-'}</span>
                  </td>
                  <td className="px-8 py-6">
                    <Badge color="blue">{c.stageId.toUpperCase()}</Badge>
                  </td>
                  <td className="px-8 py-6">
                    <div className={`w-10 h-5 rounded-full relative transition-colors cursor-pointer ${c.allowAI ? 'bg-orange-500' : 'bg-slate-200'}`}>
                      <div className={`absolute top-1 w-3 h-3 bg-white rounded-full transition-all ${c.allowAI ? 'right-1' : 'left-1'}`}></div>
                    </div>
                  </td>
                  <td className="px-8 py-6 text-right">
                    <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                       <button onClick={() => onEdit(c)} className="p-2.5 text-slate-400 hover:text-orange-500 bg-white border border-transparent hover:border-slate-100 rounded-xl shadow-sm transition-all"><Edit3 size={16}/></button>
                       <button className="p-2.5 text-slate-400 hover:text-red-500 bg-white border border-transparent hover:border-slate-100 rounded-xl shadow-sm transition-all"><Trash2 size={16}/></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

// 4. SETTINGS
const SettingsPage = ({ stages }: { stages: Stage[] }) => {
  const [activeTab, setActiveTab] = useState<'pipeline' | 'teams' | 'fields' | 'webhooks'>('pipeline');

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-black text-slate-800 tracking-tight">Configurações</h2>
        <p className="text-sm text-slate-400 font-medium">Ajustes e personalização da plataforma.</p>
      </div>
      
      <div className="flex gap-1 border-b border-slate-100">
        {['pipeline', 'teams', 'fields', 'webhooks'].map(tab => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab as any)}
            className={`px-6 py-3 border-b-2 font-bold text-[10px] uppercase tracking-widest transition-all ${activeTab === tab ? 'border-orange-500 text-orange-600' : 'border-transparent text-slate-400'}`}
          >
            {tab}
          </button>
        ))}
      </div>
      
      <div className="bg-white p-8 rounded-[2.5rem] border border-slate-200 shadow-sm min-h-[400px]">
        {activeTab === 'pipeline' && (
          <div className="space-y-4">
            <div className="flex justify-between items-center mb-6">
               <h4 className="text-xs font-black text-slate-400 uppercase tracking-widest">Etapas do Funil</h4>
               <button className="bg-slate-900 text-white text-[10px] font-black uppercase tracking-widest px-4 py-2 rounded-xl shadow-lg">+ Nova Etapa</button>
            </div>
            {stages.map(stage => (
              <div key={stage.id} className="p-5 bg-slate-50 border border-slate-100 rounded-2xl flex justify-between items-center group hover:border-orange-200 transition-all">
                <div className="flex items-center gap-4">
                  <div className="w-8 h-8 bg-white border rounded-lg flex items-center justify-center font-black text-slate-400 text-xs">{stage.order}</div>
                  <div>
                    <span className="font-black text-slate-800 text-sm">{stage.name}</span>
                    <div className="flex gap-2 mt-1">
                      <Badge color="gray">{stage.routingMode}</Badge>
                      {stage.isMandatory && <Badge color="orange">Obrigatória</Badge>}
                    </div>
                  </div>
                </div>
                <button className="p-2.5 text-slate-300 hover:text-slate-600 transition-colors"><Edit3 size={18}/></button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// 5. SUPER ADMIN
const SuperAdminPage = ({ companies }: { companies: Company[] }) => {
  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-black text-slate-800 tracking-tight">Painel SaaS Adm</h2>
          <p className="text-sm text-slate-400 font-medium">Controle central de empresas e usuários.</p>
        </div>
        <button className="bg-slate-900 text-white text-xs font-bold px-5 py-2.5 rounded-xl flex items-center gap-2 shadow-lg">
          <Building2 size={16} /> Nova Empresa
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="md:col-span-2 bg-white rounded-[2.5rem] border border-slate-200 overflow-hidden shadow-sm">
           <div className="px-8 py-5 bg-slate-50 border-b flex items-center justify-between">
              <h3 className="text-xs font-black text-slate-500 uppercase tracking-widest">Empresas Ativas</h3>
           </div>
           <table className="w-full text-left">
             <thead className="bg-slate-50 border-b border-slate-100">
               <tr>
                 <th className="px-8 py-4 text-[10px] font-black uppercase text-slate-400 tracking-widest">Empresa</th>
                 <th className="px-8 py-4 text-[10px] font-black uppercase text-slate-400 tracking-widest text-center">Usuários</th>
                 <th className="px-8 py-4 text-[10px] font-black uppercase text-slate-400 tracking-widest text-center">Status</th>
                 <th className="px-8 py-4 text-right"></th>
               </tr>
             </thead>
             <tbody className="divide-y divide-slate-100">
               {companies.map(co => (
                 <tr key={co.id} className="hover:bg-slate-50 transition-colors">
                   <td className="px-8 py-5">
                     <p className="text-sm font-black text-slate-800">{co.name}</p>
                     <p className="text-[10px] text-slate-400 font-bold uppercase">Plano Premium</p>
                   </td>
                   <td className="px-8 py-5 text-center font-black text-slate-700 text-sm">{co.userLimit}</td>
                   <td className="px-8 py-5 text-center">
                     <Badge color={co.active ? 'green' : 'red'}>{co.active ? 'Ativo' : 'Suspenso'}</Badge>
                   </td>
                   <td className="px-8 py-5 text-right">
                     <button className="p-2.5 hover:bg-white rounded-xl transition-all border border-transparent hover:border-slate-100 text-slate-400"><Settings size={18}/></button>
                   </td>
                 </tr>
               ))}
             </tbody>
           </table>
        </div>
        <div className="bg-white rounded-[2.5rem] border border-slate-200 p-8 shadow-sm flex flex-col items-center justify-center text-center space-y-5">
           <div className="w-20 h-20 bg-blue-50 text-blue-500 rounded-[2rem] flex items-center justify-center shadow-inner"><UserPlus size={40}/></div>
           <h3 className="text-xl font-black text-slate-800">Convidar Adm</h3>
           <p className="text-xs text-slate-400 font-medium max-w-[200px]">Acesso exclusivo para desenvolvedores de sistema.</p>
           <div className="w-full">
             <input placeholder="E-mail do desenvolvedor" className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-xs font-bold mb-3 outline-none focus:ring-4 focus:ring-blue-500/5"/>
             <button className="w-full bg-blue-500 text-white py-4 rounded-2xl text-xs font-black uppercase tracking-widest shadow-xl shadow-blue-500/20 hover:bg-blue-600 transition-all">Enviar Convite</button>
           </div>
        </div>
      </div>
    </div>
  );
};

// --- APP ROOT ---
const App = () => {
  const [user, setUser] = useState<User | null>(null);
  const [tab, setTab] = useState('dashboard');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingContact, setEditingContact] = useState<Contact | null>(null);
  
  const [data, setData] = useState<any>({ 
    users: [], 
    contacts: [
      { id: 'c1', name: 'João Silva', phone: '11 99999-0001', companyName: 'Logística S.A', allowAI: true, status: 'IN_PROGRESS', type: 'Venda', stageId: 's1', email: 'joao@log.com' },
      { id: 'c2', name: 'Maria Souza', phone: '11 98888-0002', companyName: 'Tech Inovação', allowAI: false, status: 'NO_REPLY', type: 'Suporte', stageId: 's2', email: 'maria@tech.com' },
      { id: 'c3', name: 'Daniel Bueno', phone: '11 97777-0003', companyName: 'Studio DB', allowAI: true, status: 'IN_PROGRESS', type: 'Venda', stageId: 's1', email: 'daniel@studio.com' }
    ], 
    stages: [
      { id: 's1', name: 'Novo Contato', order: 1, routingMode: 'CAROUSEL' },
      { id: 's2', name: 'Em Atendimento', order: 2, routingMode: 'DEMAND' },
      { id: 's3', name: 'Aguardando Cliente', order: 3, routingMode: 'PORTFOLIO' },
      { id: 's4', name: 'Finalizado', order: 4, routingMode: 'MANAGER' }
    ], 
    companies: [
      { id: 'co-1', name: 'LOX Tech Solutions', active: true, userLimit: 50, memoryLimitGb: 10 },
      { id: 'co-2', name: 'Braun Energia', active: true, userLimit: 5, memoryLimitGb: 2 }
    ] 
  });

  const handleLogin = (email: string, pass: string) => {
    if (email === 'daniel.bueno.studio@gmail.com' && pass === '123456') {
      setUser({ id: 'u-1', companyId: 'co-1', name: 'Daniel Bueno', email, role: 'DEVELOPER', active: true });
    } else {
      alert("Credenciais de teste: daniel.bueno.studio@gmail.com / 123456");
    }
  };

  const moveContact = (contactId: string, newStageId: string) => {
    setData(prev => ({
      ...prev,
      contacts: prev.contacts.map(c => c.id === contactId ? { ...c, stageId: newStageId } : c)
    }));
  };

  const openEdit = (contact?: Contact) => {
    setEditingContact(contact || { id: '', companyId: '', name: '', phone: '', email: '', type: 'Venda', allowAI: false, status: 'IN_PROGRESS', stageId: 's1' });
    setIsModalOpen(true);
  };

  const saveContact = (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingContact) return;

    if (editingContact.id) {
      setData(prev => ({
        ...prev,
        contacts: prev.contacts.map(c => c.id === editingContact.id ? editingContact : c)
      }));
    } else {
      const newId = 'c' + (data.contacts.length + 1);
      setData(prev => ({
        ...prev,
        contacts: [...prev.contacts, { ...editingContact, id: newId }]
      }));
    }
    setIsModalOpen(false);
  };

  if (!user) {
    // Reusing the inline login style for simplicity since we're in one file
    return (
      <div className="min-h-screen bg-slate-900 flex items-center justify-center p-6">
        <div className="max-w-md w-full">
          <div className="text-center mb-10">
            <div className="w-20 h-20 bg-orange-500 rounded-[2.5rem] mx-auto flex items-center justify-center text-white text-4xl font-black shadow-2xl shadow-orange-500/40 mb-6">L</div>
            <h1 className="text-3xl font-black text-white tracking-tight">LOX Atendimentos</h1>
            <p className="text-slate-400 font-medium mt-2 uppercase text-[10px] tracking-widest font-black">CRM & Gestão de Atendimento</p>
          </div>
          <div className="bg-white p-10 rounded-[2.5rem] shadow-2xl">
            <form className="space-y-5" onSubmit={e => { e.preventDefault(); handleLogin('daniel.bueno.studio@gmail.com', '123456'); }}>
              <div>
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">E-mail Corporativo</label>
                <input defaultValue="daniel.bueno.studio@gmail.com" className="w-full bg-slate-50 border border-slate-100 p-4 rounded-2xl outline-none focus:ring-4 focus:ring-orange-500/10 focus:border-orange-200 transition-all font-bold text-slate-700" placeholder="seu@email.com"/>
              </div>
              <div>
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">Senha de Acesso</label>
                <input type="password" defaultValue="123456" className="w-full bg-slate-50 border border-slate-100 p-4 rounded-2xl outline-none focus:ring-4 focus:ring-orange-500/10 focus:border-orange-200 transition-all font-bold text-slate-700" placeholder="••••••••"/>
              </div>
              <button className="w-full bg-slate-900 text-white py-4 rounded-2xl font-black uppercase tracking-widest shadow-xl shadow-slate-200 hover:bg-slate-800 transition-all pt-5">Entrar no Sistema</button>
            </form>
            <p className="text-center mt-8 text-slate-400 text-[10px] font-bold uppercase tracking-widest">Acesso de Desenvolvedor • Versão 1.2</p>
          </div>
        </div>
      </div>
    );
  }

  const menu = [
    { id: 'dashboard', label: 'Início', icon: <LayoutDashboard size={20}/>, roles: ['DEVELOPER', 'DIRECTOR', 'MANAGER', 'CONSULTANT'] },
    { id: 'kanban', label: 'CRM Kanban', icon: <Kanban size={20}/>, roles: ['DEVELOPER', 'DIRECTOR', 'MANAGER', 'CONSULTANT'] },
    { id: 'contacts', label: 'Contatos', icon: <Users size={20}/>, roles: ['DEVELOPER', 'DIRECTOR', 'MANAGER', 'CONSULTANT'] },
    { id: 'settings', label: 'Ajustes', icon: <Settings size={20}/>, roles: ['DEVELOPER', 'DIRECTOR'] },
    { id: 'admin', label: 'SaaS Adm', icon: <ShieldAlert size={20}/>, roles: ['DEVELOPER'] },
  ];

  const visibleMenu = menu.filter(m => m.roles.includes(user.role));

  return (
    <div className="flex h-screen overflow-hidden bg-slate-50 font-sans">
      <aside className="w-64 bg-slate-900 flex flex-col shrink-0 shadow-2xl z-20">
        <div className="p-10 border-b border-slate-800 flex items-center gap-4">
          <div className="w-9 h-9 bg-orange-500 rounded-2xl flex items-center justify-center font-black text-white shadow-lg shadow-orange-500/20">L</div>
          <span className="font-black text-white text-2xl tracking-tighter">LOX</span>
        </div>
        <nav className="flex-1 p-5 space-y-1 overflow-y-auto custom-scrollbar">
          {visibleMenu.map(item => (
            <button key={item.id} onClick={() => setTab(item.id)} className={`w-full flex items-center gap-3 px-5 py-3.5 rounded-2xl transition-all ${tab === item.id ? 'bg-orange-500 text-white shadow-xl shadow-orange-500/30' : 'text-slate-400 hover:bg-slate-800 hover:text-slate-200'}`}>
              {item.icon} <span className="text-sm font-black">{item.label}</span>
            </button>
          ))}
        </nav>
        <div className="p-5 border-t border-slate-800 bg-slate-900/50">
          <button onClick={() => setUser(null)} className="w-full flex items-center gap-3 px-5 py-4 text-slate-500 hover:text-red-400 transition-colors bg-slate-800/50 rounded-2xl">
            <LogOut size={20}/> <span className="text-sm font-black uppercase tracking-widest">Sair</span>
          </button>
        </div>
      </aside>

      <div className="flex-1 flex flex-col overflow-hidden relative">
        <header className="h-24 bg-white border-b border-slate-100 flex items-center justify-between px-10 shrink-0 z-10 shadow-sm">
          <div className="flex items-center gap-4 bg-slate-50 px-5 py-3 rounded-2xl border border-slate-200 w-96 group focus-within:ring-4 focus-within:ring-orange-500/5 transition-all">
            <Search size={18} className="text-slate-400 group-focus-within:text-orange-500 transition-colors"/>
            <input placeholder="Pesquisar..." className="bg-transparent border-none outline-none text-sm w-full font-bold text-slate-700"/>
          </div>
          <div className="flex items-center gap-8">
            <button className="text-slate-400 relative p-3 hover:bg-slate-50 rounded-2xl transition-all border border-transparent hover:border-slate-100"><Bell size={22}/></button>
            <div className="h-10 w-px bg-slate-100"></div>
            <div className="flex items-center gap-4">
              <div className="text-right">
                <p className="text-sm font-black text-slate-800 leading-none">{user.name}</p>
                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1.5 leading-none">{user.role}</p>
              </div>
              <div className="w-12 h-12 bg-slate-100 rounded-3xl border-2 border-white shadow-sm flex items-center justify-center font-black text-slate-500 uppercase">{user.name[0]}</div>
            </div>
          </div>
        </header>

        <main className="flex-1 overflow-y-auto p-10 custom-scrollbar bg-[#f8fafc]">
          {tab === 'dashboard' && <DashboardPage />}
          {tab === 'kanban' && <KanbanPage stages={data.stages} contacts={data.contacts} onMove={moveContact} onEdit={openEdit} />}
          {tab === 'contacts' && <ContactsPage contacts={data.contacts} onEdit={openEdit} />}
          {tab === 'settings' && <SettingsPage stages={data.stages} />}
          {tab === 'admin' && <SuperAdminPage companies={data.companies} />}
        </main>
      </div>

      <Modal title={editingContact?.id ? "Detalhes do Negócio" : "Novo Contato"} isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
        <form onSubmit={saveContact} className="space-y-6">
           <div className="grid grid-cols-2 gap-5">
              <div>
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">Nome do Contato</label>
                <input required value={editingContact?.name} onChange={e => setEditingContact({...editingContact!, name: e.target.value})} className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm font-bold outline-none focus:ring-4 focus:ring-orange-500/10"/>
              </div>
              <div>
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">WhatsApp / Telefone</label>
                <input required value={editingContact?.phone} onChange={e => setEditingContact({...editingContact!, phone: e.target.value})} className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm font-bold outline-none focus:ring-4 focus:ring-orange-500/10"/>
              </div>
           </div>
           <div>
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">E-mail</label>
              <input value={editingContact?.email} onChange={e => setEditingContact({...editingContact!, email: e.target.value})} className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm font-bold outline-none focus:ring-4 focus:ring-orange-500/10" placeholder="exemplo@empresa.com"/>
           </div>
           <div>
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">Empresa</label>
              <input value={editingContact?.companyName} onChange={e => setEditingContact({...editingContact!, companyName: e.target.value})} className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm font-bold outline-none focus:ring-4 focus:ring-orange-500/10" placeholder="Nome da Empresa"/>
           </div>
           <div className="grid grid-cols-2 gap-5">
              <div>
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">Tipo</label>
                <select value={editingContact?.type} onChange={e => setEditingContact({...editingContact!, type: e.target.value})} className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm font-bold outline-none appearance-none cursor-pointer">
                  <option value="Venda">Venda</option>
                  <option value="Suporte">Suporte</option>
                  <option value="Geral">Geral</option>
                </select>
              </div>
              <div>
                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-2 px-1">Etapa Atual</label>
                <select value={editingContact?.stageId} onChange={e => setEditingContact({...editingContact!, stageId: e.target.value})} className="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm font-bold outline-none appearance-none cursor-pointer">
                  {data.stages.map((s: any) => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              </div>
           </div>
           <div className="flex items-center justify-between p-5 bg-orange-50 rounded-[2rem] border border-orange-100">
              <div>
                <p className="text-xs font-black text-orange-600 uppercase tracking-wider">Ativar Inteligência Artificial</p>
                <p className="text-[10px] text-orange-400 font-bold uppercase tracking-tight">A IA responderá automaticamente as mensagens</p>
              </div>
              <button type="button" onClick={() => setEditingContact({...editingContact!, allowAI: !editingContact?.allowAI})} className={`w-14 h-7 rounded-full relative transition-colors ${editingContact?.allowAI ? 'bg-orange-500' : 'bg-slate-300'}`}>
                 <div className={`absolute top-1 w-5 h-5 bg-white rounded-full transition-all shadow-sm ${editingContact?.allowAI ? 'right-1' : 'left-1'}`}></div>
              </button>
           </div>
           <button type="submit" className="w-full bg-slate-900 text-white py-5 rounded-[2rem] font-black uppercase tracking-widest shadow-xl shadow-slate-200 hover:bg-slate-800 transition-all active:scale-[0.98]">Salvar Dados do Negócio</button>
        </form>
      </Modal>

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .kanban-column { min-width: 340px; max-width: 340px; }
      `}</style>
    </div>
  );
};

// --- INITIALIZE ---
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);
