const { useState, useEffect, useRef, useCallback } = React;
const Domain = window.ProjectOSDomain;

// ── FIREBASE DB HELPERS ────────────────────────────────────────────────────────
const FB = () => window.__FB;

const db_get = async (col, id) => {
  const { db, doc, getDoc } = FB();
  const snap = await getDoc(doc(db, col, id));
  return snap.exists() ? { id: snap.id, ...snap.data() } : null;
};
const db_getAll = async (col) => {
  const { db, collection, getDocs } = FB();
  const snap = await getDocs(collection(db, col));
  return snap.docs.map(d => ({ id: d.id, ...d.data() }));
};
const db_set = async (col, id, data) => {
  const { db, doc, setDoc } = FB();
  await setDoc(doc(db, col, id), data);
};
const db_del = async (col, id) => {
  const { db, doc, deleteDoc } = FB();
  await deleteDoc(doc(db, col, id));
};
const db_listen = (col, cb) => {
  const { db, collection, onSnapshot } = FB();
  return onSnapshot(collection(db, col), snap => {
    cb(snap.docs.map(d => ({ id: d.id, ...d.data() })));
  });
};

const db_logActivity = async (data = {}) => {
  try {
    const log = Domain.activity.create(data);
    await db_set("activityLogs", log.id, log);
  } catch (e) {
    console.warn("Activity log skipped:", e);
  }
};

const db_saveProjectMember = async (project, userId, createdBy = "", active = true) => {
  try {
    const draft = Domain.membership.create({
      projectId: project.id,
      userId,
      workspaceId: Domain.workspace.idOf(project),
      createdBy,
      active,
    });
    const existing = await db_get("projectMembers", draft.id);
    await db_set("projectMembers", draft.id, { ...draft, ...(existing || {}), active, updatedAt: now() });
  } catch (e) {
    console.warn("Project membership sync skipped:", e);
  }
};

const db_syncProjectMembers = async (project, createdBy = "") => {
  for (const member of Domain.membership.fromProject(project, createdBy)) {
    await db_saveProjectMember(project, member.userId, createdBy, true);
  }
};

const db_saveTaskDocument = async (task, options = {}) => {
  try {
    const normalized = Domain.task.normalize(task, options);
    await db_set("tasks", normalized.id, normalized);
  } catch (e) {
    console.warn("Task sync skipped:", e);
  }
};

const db_softDeleteTaskDocument = async (task, options = {}) => {
  await db_saveTaskDocument({ ...task, deletedAt: now(), updatedAt: now() }, options);
};

const db_syncProjectTasks = async (project, createdBy = "") => {
  for (const task of project.tasks || []) {
    await db_saveTaskDocument(task, {
      projectId: project.id,
      workspaceId: Domain.workspace.idOf(project),
      createdBy,
      sourceType: "project",
    });
  }
};

const db_saveMilestoneDocument = async (project, milestone, createdBy = "") => {
  try {
    const normalized = Domain.milestone.normalize(milestone, { projectId: project.id, workspaceId: Domain.workspace.idOf(project), createdBy });
    await db_set("milestones", normalized.id, normalized);
  } catch (e) { console.warn("Milestone sync skipped:", e); }
};

const db_softDeleteMilestoneDocument = async (project, milestone, createdBy = "") => {
  await db_saveMilestoneDocument(project, { ...milestone, deletedAt: now(), updatedAt: now() }, createdBy);
};

const db_syncProjectMilestones = async (project, createdBy = "") => {
  for (const milestone of project.milestones || []) await db_saveMilestoneDocument(project, milestone, createdBy);
};

const db_saveNoteDocument = async (project, note, createdBy = "") => {
  try {
    const normalized = Domain.note.normalize(note, { projectId: project.id, workspaceId: Domain.workspace.idOf(project), createdBy });
    await db_set("notes", normalized.id, normalized);
  } catch (e) { console.warn("Note sync skipped:", e); }
};

const db_syncProjectNotes = async (project, createdBy = "") => {
  for (const note of project.notes || []) await db_saveNoteDocument(project, note, createdBy);
};

const db_saveFinanceEntry = async (project, createdBy = "") => {
  try {
    const normalized = Domain.finance.normalizeEntry(project, { workspaceId: Domain.workspace.idOf(project), createdBy });
    await db_set("financeEntries", normalized.id, normalized);
  } catch (e) { console.warn("Finance sync skipped:", e); }
};

const db_syncProjectChildren = async (project, createdBy = "") => {
  await db_syncProjectMembers(project, createdBy);
  await db_syncProjectTasks(project, createdBy);
  await db_syncProjectMilestones(project, createdBy);
  await db_syncProjectNotes(project, createdBy);
  await db_saveFinanceEntry(project, createdBy);
};



// ── LOCAL FALLBACK (antes do Firebase carregar) ────────────────────────────────
const LS = {
  get:(k,fb)=>{try{const v=localStorage.getItem(k);return v?JSON.parse(v):fb;}catch{return fb;}},
  set:(k,v)=>{try{localStorage.setItem(k,JSON.stringify(v));}catch{}}
};

// ── CONSTANTS ──────────────────────────────────────────────────────────────────
const INIT_CATS=["Site","Aplicativo","Marketing","Financeiro","Outro"];
const STATUSES=[
  {value:"planning",label:"Planejamento",color:"#6366f1"},
  {value:"active",label:"Em Andamento",color:"#10b981"},
  {value:"paused",label:"Pausado",color:"#f59e0b"},
  {value:"completed",label:"Concluído",color:"#3b82f6"},
  {value:"archived",label:"Arquivado",color:"#6b7280"},
];
const ROLES=[
  {value:"admin",label:"Administrador",desc:"Acesso total ao sistema"},
  {value:"manager",label:"Gerente",desc:"Gerencia projetos e usuários"},
  {value:"member",label:"Membro",desc:"Acessa e edita projetos vinculados"},
  {value:"viewer",label:"Visualizador",desc:"Somente visualização"},
];
const TCOLS=[{id:"todo",label:"A Fazer"},{id:"doing",label:"Andamento"},{id:"done",label:"Concluído"}];
const PC={Baixa:"#64748b",Média:"#f59e0b",Alta:"#ef4444",Crítica:"#dc2626"};
const ICONS=["📰","🏛️","⚽","🍳","✝️","📱","🌐","📁","💡","🎯","🚀","🎨","📊","🔬","💰","🎵","📚","🏆","🌱","⭐","🐾","📖","🗺️","🧪","🎭","🏗️","💎","🔑","🌍","🛒"];
const CLRS=["#6366f1","#10b981","#f59e0b","#ef4444","#3b82f6","#a78bfa","#22c55e","#f97316","#0ea5e9","#ec4899","#14b8a6","#84cc16"];

const INIT_PROJECTS=[
  {id:"p1",name:"Dicionário News",description:"Site de dicionário temático sobre notícias e jornalismo.",category:"Site",status:"active",progress:35,color:"#6366f1",icon:"📰",startDate:"2024-06-01",targetDate:"2025-06-01",milestones:[{id:"m1",title:"Pesquisa inicial",date:"2024-07-01",completed:true},{id:"m2",title:"MVP lançado",date:"2024-12-01",completed:false}],tasks:[{id:"t1",title:"Definir 500 termos base",status:"done",priority:"Alta"},{id:"t2",title:"Revisar conteúdo",status:"doing",priority:"Média"}],team:["u1"],notes:[{id:"n1",text:"Foco inicial em monetização via AdSense.",author:"Administrador",date:"2024-06-05"}],monetization:{model:"AdSense + Licença",revenue:0,target:5000},createdAt:"2024-06-01",updatedAt:"2024-06-01"},
  {id:"p2",name:"Dicionário do Concurso",description:"Site de glossário para candidatos de concursos públicos.",category:"Site",status:"active",progress:50,color:"#10b981",icon:"🏛️",startDate:"2024-05-01",targetDate:"2025-03-01",milestones:[{id:"m1",title:"Estrutura criada",date:"2024-06-01",completed:true}],tasks:[{id:"t1",title:"Listar disciplinas",status:"done",priority:"Alta"}],team:["u1"],notes:[],monetization:{model:"Assinatura + Licença",revenue:0,target:8000},createdAt:"2024-05-01",updatedAt:"2024-05-01"},
  {id:"p3",name:"Dicionário Muda Animal",description:"Site sobre vocabulário de mudança de hábitos e comportamento.",category:"Site",status:"planning",progress:10,color:"#f59e0b",icon:"🐾",startDate:"2024-09-01",targetDate:"2025-09-01",milestones:[],tasks:[],team:["u1"],notes:[],monetization:{model:"Licença",revenue:0,target:3000},createdAt:"2024-09-01",updatedAt:"2024-09-01"},
  {id:"p4",name:"Dicionário do Futebol",description:"Site com termos técnicos e gírias do futebol.",category:"Site",status:"active",progress:60,color:"#22c55e",icon:"⚽",startDate:"2024-03-01",targetDate:"2024-12-01",milestones:[{id:"m1",title:"500 termos",date:"2024-05-01",completed:true}],tasks:[{id:"t1",title:"SEO e otimização",status:"doing",priority:"Alta"}],team:["u1"],notes:[],monetization:{model:"AdSense + Parceiros",revenue:1200,target:10000},createdAt:"2024-03-01",updatedAt:"2024-03-01"},
  {id:"p5",name:"Dicionário das Receitas",description:"Site de glossário culinário com termos de gastronomia.",category:"Site",status:"active",progress:45,color:"#ef4444",icon:"🍳",startDate:"2024-07-01",targetDate:"2025-07-01",milestones:[],tasks:[],team:["u1"],notes:[],monetization:{model:"Afiliados + Licença",revenue:300,target:6000},createdAt:"2024-07-01",updatedAt:"2024-07-01"},
  {id:"p6",name:"Dicionário da Fé",description:"Site de vocabulário religioso e espiritual ecumênico.",category:"Site",status:"planning",progress:15,color:"#a78bfa",icon:"✝️",startDate:"2024-10-01",targetDate:"2025-12-01",milestones:[],tasks:[],team:["u1"],notes:[],monetization:{model:"Doações + Licença",revenue:0,target:4000},createdAt:"2024-10-01",updatedAt:"2024-10-01"},
  {id:"p7",name:"Criação de Aplicativos",description:"Portfólio de micro-apps para diversas categorias.",category:"Aplicativo",status:"planning",progress:5,color:"#0ea5e9",icon:"📱",startDate:"2025-01-01",targetDate:"2026-06-01",milestones:[],tasks:[],team:["u1"],notes:[],monetization:{model:"App Store + Play Store",revenue:0,target:20000},createdAt:"2025-01-01",updatedAt:"2025-01-01"},
  {id:"p8",name:"Sites Internacionais",description:"Sites em múltiplos idiomas para mercado global.",category:"Site",status:"planning",progress:0,color:"#f97316",icon:"🌐",startDate:"2025-02-01",targetDate:"2026-12-01",milestones:[],tasks:[],team:["u1"],notes:[],monetization:{model:"AdSense Internacional + Licença",revenue:0,target:50000},createdAt:"2025-02-01",updatedAt:"2025-02-01"},
];

// ── UTILS ──────────────────────────────────────────────────────────────────────
const uid  = () => Math.random().toString(36).slice(2,10);
const now  = () => new Date().toISOString().split("T")[0];
const fmt  = d  => d ? new Date(d+"T12:00:00").toLocaleDateString("pt-BR") : "—";
const pCol = p  => p>=75?"#10b981":p>=40?"#f59e0b":"#6366f1";
const stI  = s  => STATUSES.find(x=>x.value===s)||STATUSES[0];
const roI  = r  => ROLES.find(x=>x.value===r)||ROLES[2];
const avt  = n  => (n||"?").split(" ").slice(0,2).map(w=>w[0]||"").join("").toUpperCase()||"??";
function useMobile(){const [m,setM]=useState(window.innerWidth<768);useEffect(()=>{const h=()=>setM(window.innerWidth<768);window.addEventListener("resize",h);return()=>window.removeEventListener("resize",h);},[]);return m;}
function useTheme(){
  const [theme,setTheme]=useState(()=>LS.get("projectos_theme","night"));
  useEffect(()=>{
    const mode=theme==="day"?"day":"night";
    document.body.dataset.theme=mode;
    document.querySelector('meta[name="theme-color"]')?.setAttribute("content",mode==="day"?"#f6f8fb":"#070711");
    LS.set("projectos_theme",mode);
  },[theme]);
  return [theme,()=>setTheme(t=>t==="day"?"night":"day")];
}

// ── TOAST NOTIFICATION ─────────────────────────────────────────────────────────
function Toast({msg,type}){
  const colors={success:"#10b981",error:"#ef4444",info:"#6366f1",warn:"#f59e0b"};
  return <div style={{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#1e293b",border:`1px solid ${colors[type]||colors.info}44`,borderRadius:10,padding:"10px 20px",color:colors[type]||colors.info,fontSize:14,fontWeight:600,zIndex:9999,animation:"fadeIn .2s ease",whiteSpace:"nowrap",boxShadow:"0 4px 24px #00000088"}}>{msg}</div>;
}

// ── BASE UI ────────────────────────────────────────────────────────────────────
const PBar=({value,h=6,color})=>(<div style={{background:"#1e293b",borderRadius:999,overflow:"hidden",height:h}}><div style={{width:`${Math.min(100,Math.max(0,value))}%`,height:"100%",background:color||pCol(value),borderRadius:999,transition:"width .4s ease"}}/></div>);
const Bdg=({label,color="#6366f1",sm})=>(<span style={{background:color+"22",color,border:`1px solid ${color}44`,borderRadius:999,padding:sm?"2px 8px":"4px 12px",fontSize:sm?11:12,fontWeight:600,whiteSpace:"nowrap",display:"inline-block"}}>{label}</span>);

const Btn=({children,onClick,v="primary",sm,icon,disabled,danger,fw,loading})=>{
  const VS={primary:{background:"#f59e0b",color:"#0f0f17",border:"none"},ghost:{background:"transparent",color:"#94a3b8",border:"1px solid #1e293b"},outline:{background:"transparent",color:"#f59e0b",border:"1px solid #f59e0b44"},danger:{background:"#ef444422",color:"#ef4444",border:"1px solid #ef444433"},success:{background:"#10b98122",color:"#10b981",border:"1px solid #10b98133"}};
  const s=danger?"danger":v;
  return <button onClick={onClick} disabled={disabled||loading} style={{...VS[s],borderRadius:8,padding:sm?"8px 12px":"10px 18px",fontSize:sm?13:14,fontWeight:600,cursor:(disabled||loading)?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,opacity:(disabled||loading)?.6:1,transition:"all .15s",whiteSpace:"nowrap",width:fw?"100%":"auto",minHeight:sm?36:42}}>
    {loading?<span style={{animation:"spin .8s linear infinite",display:"inline-block"}}>⏳</span>:icon&&<Ic n={icon} s={sm?14:16}/>}{children}
  </button>;
};

const Inp=({label,value,onChange,type="text",placeholder,rows,required,options,sm,helper})=>{
  const b={background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"10px 12px",fontSize:sm?13:15,width:"100%",outline:"none",minHeight:rows?"auto":44};
  return(<div style={{display:"flex",flexDirection:"column",gap:5}}>
    {label&&<label style={{fontSize:12,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:.8}}>{label}{required&&<span style={{color:"#ef4444"}}> *</span>}</label>}
    {options?<select value={value} onChange={e=>onChange(e.target.value)} style={b}>{options.map(o=><option key={typeof o==="string"?o:o.value} value={typeof o==="string"?o:o.value}>{typeof o==="string"?o:o.label}</option>)}</select>
    :rows?<textarea value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} rows={rows} style={{...b,resize:"vertical"}}/>
    :<input type={type} value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} style={b}/>}
    {helper&&<span style={{fontSize:11,color:"#475569"}}>{helper}</span>}
  </div>);
};

const Card=({children,style={},onClick})=>(<div onClick={onClick} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:12,padding:16,cursor:onClick?"pointer":"default",transition:"border-color .2s,transform .15s",...style}} onMouseEnter={e=>{if(onClick){e.currentTarget.style.borderColor="#f59e0b44";e.currentTarget.style.transform="translateY(-1px)";}}} onMouseLeave={e=>{if(onClick){e.currentTarget.style.borderColor="#1e293b";e.currentTarget.style.transform="none";}}}>{children}</div>);

const Modal=({title,children,onClose,wide})=>{
  const m=useMobile();
  useEffect(()=>{document.body.style.overflow="hidden";return()=>{document.body.style.overflow="";};},[]);
  return(<div style={{position:"fixed",inset:0,background:"#000000cc",zIndex:1000,display:"flex",alignItems:m?"flex-end":"center",justifyContent:"center",padding:m?0:16}} onClick={onClose}>
    <div onClick={e=>e.stopPropagation()} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:m?"16px 16px 0 0":16,padding:m?"20px 16px 36px":28,width:"100%",maxWidth:wide?700:520,maxHeight:m?"92vh":"88vh",overflowY:"auto",animation:m?"slideUp .25s ease":"fadeIn .2s ease"}}>
      {m&&<div style={{width:40,height:4,background:"#1e293b",borderRadius:2,margin:"0 auto 20px"}}/>}
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
        <h3 style={{color:"#f1f5f9",fontSize:17,fontWeight:700,margin:0}}>{title}</h3>
        <button onClick={onClose} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",fontSize:22,lineHeight:1,padding:"0 4px"}}>✕</button>
      </div>
      {children}
    </div>
  </div>);
};

const SH=({title,sub,action})=>(<div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:20,gap:12,flexWrap:"wrap"}}><div><h2 style={{color:"#f1f5f9",fontSize:20,fontWeight:800,margin:0}}>{title}</h2>{sub&&<p style={{color:"#475569",fontSize:13,margin:"4px 0 0"}}>{sub}</p>}</div>{action}</div>);
const ThemeToggle=({theme,onToggle})=>{
  const day=theme==="day";
  return <button onClick={onToggle} title={day?"Ativar modo noite":"Ativar modo dia"} aria-label={day?"Ativar modo noite":"Ativar modo dia"} style={{width:34,height:34,borderRadius:"50%",border:`1px solid ${day?"#d8e0ea":"#1e293b"}`,background:day?"#fff7ed":"#111827",color:day?"#f59e0b":"#a5b4fc",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:17,boxShadow:day?"0 1px 8px #f59e0b22":"0 1px 8px #00000055",transition:"all .15s"}}>{day?"\u263e":"\u2600"}</button>;
};

// ── ICONS ──────────────────────────────────────────────────────────────────────
const Ic=({n,s=16,c="currentColor"})=>{
  const D={
    dash:<path d="M3 9h18M3 15h18M9 3v18M15 3v18" strokeWidth="1.5" stroke={c} fill="none" strokeLinecap="round"/>,
    folder:<path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" stroke={c} fill="none" strokeWidth="1.5"/>,
    users:<><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke={c} fill="none" strokeWidth="1.5"/><circle cx="9" cy="7" r="4" stroke={c} fill="none" strokeWidth="1.5"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke={c} fill="none" strokeWidth="1.5"/></>,
    time:<><line x1="3" y1="6" x2="21" y2="6" stroke={c} strokeWidth="1.5" strokeLinecap="round"/><line x1="3" y1="12" x2="21" y2="12" stroke={c} strokeWidth="1.5" strokeLinecap="round"/><line x1="3" y1="18" x2="21" y2="18" stroke={c} strokeWidth="1.5" strokeLinecap="round"/><circle cx="9" cy="6" r="2.5" fill={c}/><circle cx="15" cy="12" r="2.5" fill={c}/><circle cx="7" cy="18" r="2.5" fill={c}/></>,
    plus:<path d="M12 5v14M5 12h14" stroke={c} fill="none" strokeWidth="2" strokeLinecap="round"/>,
    edit:<path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    trash:<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    check:<path d="M20 6L9 17l-5-5" stroke={c} fill="none" strokeWidth="2" strokeLinecap="round"/>,
    logout:<path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    money:<><circle cx="12" cy="12" r="10" stroke={c} fill="none" strokeWidth="1.5"/><path d="M12 8v8M9 10h4.5a1.5 1.5 0 010 3H9m0 0h4.5a1.5 1.5 0 010 3H9" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/></>,
    chart:<path d="M18 20V10M12 20V4M6 20v-6" stroke={c} fill="none" strokeWidth="2" strokeLinecap="round"/>,
    eye:<><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke={c} fill="none" strokeWidth="1.5"/><circle cx="12" cy="12" r="3" stroke={c} fill="none" strokeWidth="1.5"/></>,
    note:<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    gear:<><circle cx="12" cy="12" r="3" stroke={c} fill="none" strokeWidth="1.5"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" stroke={c} fill="none" strokeWidth="1.5"/></>,
    back:<path d="M19 12H5M12 19l-7-7 7-7" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    task:<><rect x="9" y="11" width="13" height="2" rx="1" fill={c}/><rect x="9" y="6" width="13" height="2" rx="1" fill={c}/><rect x="9" y="16" width="13" height="2" rx="1" fill={c}/><path d="M5 7l-2 2-1-1M5 12l-2 2-1-1M5 17l-2 2-1-1" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/></>,
    shield:<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke={c} fill="none" strokeWidth="1.5" strokeLinejoin="round"/>,
    tag:<path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82zM7 7h.01" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    link:<path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/>,
    cloud:<><polyline points="16 16 12 12 8 16" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><line x1="12" y1="12" x2="12" y2="21" stroke={c} strokeWidth="1.5" strokeLinecap="round"/><path d="M20.39 18.39A5 5 0 0018 9h-1.26A8 8 0 103 16.3" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/></>,
    install:<><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/><polyline points="7 10 12 15 17 10" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><line x1="12" y1="15" x2="12" y2="3" stroke={c} strokeWidth="1.5" strokeLinecap="round"/></>,
    help:<><circle cx="12" cy="12" r="10" stroke={c} fill="none" strokeWidth="1.5"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/><line x1="12" y1="17" x2="12.01" y2="17" stroke={c} strokeWidth="2" strokeLinecap="round"/></>,
    upload:<><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round"/><polyline points="17 8 12 3 7 8" stroke={c} fill="none" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><line x1="12" y1="3" x2="12" y2="15" stroke={c} strokeWidth="1.5" strokeLinecap="round"/></>,
    star:<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke={c} fill="none" strokeWidth="1.5" strokeLinejoin="round"/>,
  };
  return <svg width={s} height={s} viewBox="0 0 24 24" style={{display:"inline-block",verticalAlign:"middle",flexShrink:0}}>{D[n]||null}</svg>;
};

// ── SETUP SCREEN (Firebase config) ────────────────────────────────────────────
function SetupScreen(){
  return(
    <div style={{minHeight:"100vh",background:"#070711",display:"flex",alignItems:"center",justifyContent:"center",padding:20}}>
      <div style={{width:"100%",maxWidth:560}}>
        <div style={{textAlign:"center",marginBottom:32}}>
          <div style={{fontSize:56,marginBottom:12}}>🔥</div>
          <h1 style={{color:"#f1f5f9",fontSize:26,fontWeight:800,margin:0}}>Configurar Firebase</h1>
          <p style={{color:"#475569",fontSize:14,marginTop:8,lineHeight:1.6}}>Para dados persistentes na nuvem, siga os passos abaixo e cole suas credenciais no arquivo HTML.</p>
        </div>
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          {[
            {n:"1",t:"Criar projeto Firebase",d:"Acesse console.firebase.google.com → Criar projeto → dê um nome → clique em Continuar",link:"https://console.firebase.google.com"},
            {n:"2",t:"Ativar Authentication",d:"No menu lateral: Build → Authentication → Get started → Email/Password → Ativar → Salvar"},
            {n:"3",t:"Criar banco Firestore",d:"Build → Firestore Database → Create database → Start in test mode → Escolha a região → Done"},
            {n:"4",t:"Registrar o app",d:"Visão geral do projeto → </> (Web) → Dê um nome → Register app → Copie as credenciais firebaseConfig"},
            {n:"5",t:"Criar usuário admin",d:"Authentication → Users → Add user → Email: admin@sistema.com → Senha: admin123"},
            {n:"6",t:"Colar no HTML",d:"Abra o arquivo projectos.html, encontre a seção COLE SUAS CREDENCIAIS e substitua os valores"},
          ].map(s=>(
            <div key={s.n} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:12,padding:"14px 16px",display:"flex",gap:14,alignItems:"flex-start"}}>
              <div style={{width:32,height:32,borderRadius:"50%",background:"#f59e0b22",border:"2px solid #f59e0b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:13,fontWeight:800,color:"#f59e0b",flexShrink:0}}>{s.n}</div>
              <div style={{flex:1}}>
                <div style={{fontSize:14,fontWeight:700,color:"#f1f5f9",marginBottom:4}}>{s.t}</div>
                <div style={{fontSize:13,color:"#64748b",lineHeight:1.5}}>{s.d}</div>
                {s.link&&<a href={s.link} target="_blank" style={{fontSize:12,color:"#f59e0b",marginTop:4,display:"inline-block"}}>{s.link} →</a>}
              </div>
            </div>
          ))}
          <div style={{background:"#10b98111",border:"1px solid #10b98133",borderRadius:12,padding:"14px 16px"}}>
            <div style={{fontSize:13,color:"#10b981",fontWeight:700,marginBottom:6}}>✅ Regras do Firestore</div>
            <pre style={{fontSize:12,color:"#94a3b8",background:"#0a0a14",borderRadius:8,padding:12,overflow:"auto",lineHeight:1.6}}>{`Use o arquivo firestore.rules deste projeto como fonte oficial.

Deploy:
npx.cmd firebase-tools deploy --only firestore:rules --project teste-5b9f6`}</pre>
          </div>
          <div style={{background:"#6366f111",border:"1px solid #6366f133",borderRadius:12,padding:"14px 16px",fontSize:13,color:"#a5b4fc",lineHeight:1.6}}>
            💡 <strong>Dica:</strong> O Firebase gratuito (Spark) suporta até 1GB de dados, 50K leituras/dia e 20K escritas/dia — mais que suficiente para começar!
          </div>
        </div>
      </div>
    </div>
  );
}

// ── LOGIN ──────────────────────────────────────────────────────────────────────
function Login({onLogin,toast}){
  const [email,setEmail]=useState("admin@sistema.com");
  const [pass,setPass]=useState("");
  const [showPass,setShowPass]=useState(false);
  const [loading,setLoading]=useState(false);

  const go=async()=>{
    if(!email||!pass)return;
    setLoading(true);
    try{
      const { auth, signInWithEmailAndPassword } = FB();
      const cred = await signInWithEmailAndPassword(auth, email, pass);
      const uid = cred.user.uid;

      // Busca ou cria o perfil automaticamente
      let userData = await db_get("users", uid);
      if(!userData){
        const allUsers = await db_getAll("users");
        const isFirst = allUsers.length === 0;
        const nameRaw = cred.user.email.split("@")[0].replace(/[^a-zA-Z\s]/g," ").trim();
        const name = nameRaw.charAt(0).toUpperCase()+nameRaw.slice(1) || "Administrador";
        userData = {
          name,
          email: cred.user.email,
          role: isFirst ? "admin" : "member",
          active: true,
          avatar: avt(name),
          phone: "",
          createdAt: now(),
          workspaceId: Domain.workspace.defaultId,
        };
        await db_set("users", uid, userData);
      }

      if(!userData.active){
        await FB().signOut(auth);
        toast("Usuário inativo. Fale com o administrador.","error");
        setLoading(false);
        return;
      }

      onLogin({...userData, id: uid});
    }catch(e){
      const msg = e.code==="auth/invalid-credential"||e.code==="auth/wrong-password"||e.code==="auth/user-not-found"
        ? "E-mail ou senha inválidos."
        : e.code==="auth/too-many-requests"
        ? "Muitas tentativas. Aguarde alguns minutos."
        : "Erro ao entrar: "+e.message;
      toast(msg,"error");
      setLoading(false);
    }
  };

  return(
    <div style={{minHeight:"100vh",background:"#070711",display:"flex",alignItems:"center",justifyContent:"center",padding:20}}>
      <div style={{width:"100%",maxWidth:380}}>
        <div style={{textAlign:"center",marginBottom:36}}>
          <div style={{fontSize:64,marginBottom:12}}>📖</div>
          <h1 style={{color:"#f1f5f9",fontSize:30,fontWeight:800,margin:0,letterSpacing:-1}}>ProjectOS</h1>
          <p style={{color:"#475569",fontSize:14,marginTop:8}}>Gestão de Projetos · Dados na Nuvem ☁️</p>
        </div>
        <Card style={{padding:24,marginBottom:12}}>
          <div style={{display:"flex",flexDirection:"column",gap:16}}>
            <Inp label="E-mail" value={email} onChange={setEmail} type="email" placeholder="seu@email.com"/>
            {/* Senha com botão ver/ocultar */}
            <div style={{display:"flex",flexDirection:"column",gap:5}}>
              <label style={{fontSize:12,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:.8}}>Senha</label>
              <div style={{position:"relative"}}>
                <input
                  type={showPass?"text":"password"}
                  value={pass}
                  onChange={e=>setPass(e.target.value)}
                  onKeyDown={e=>e.key==="Enter"&&go()}
                  placeholder="••••••••"
                  style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"10px 44px 10px 12px",fontSize:15,width:"100%",outline:"none",minHeight:44}}
                />
                <button
                  onClick={()=>setShowPass(!showPass)}
                  style={{position:"absolute",right:10,top:"50%",transform:"translateY(-50%)",background:"none",border:"none",cursor:"pointer",color:"#64748b",padding:4,display:"flex",alignItems:"center"}}
                  title={showPass?"Ocultar senha":"Ver senha"}
                >
                  {showPass
                    ? <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="1.5" strokeLinecap="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                    : <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="1.5" strokeLinecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                  }
                </button>
              </div>
            </div>
            <Btn onClick={go} loading={loading} fw>{loading?"Entrando...":"Entrar"}</Btn>
          </div>
        </Card>
        <div style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:10,padding:"12px 16px",display:"flex",gap:10,alignItems:"center"}}>
          <Ic n="cloud" s={16} c="#6366f1"/>
          <span style={{fontSize:12,color:"#475569"}}>Dados sincronizados em tempo real via Firebase 🔥</span>
        </div>
      </div>
    </div>
  );
}

// ── NAV ────────────────────────────────────────────────────────────────────────
function BotNav({view,go,user}){
  const nav=[{id:"dashboard",label:"Início",icon:"dash"},{id:"projects",label:"Projetos",icon:"folder"},{id:"timeline",label:"Timeline",icon:"time"},{id:"tasks",label:"Tarefas",icon:"task"},{id:"finances",label:"Finanças",icon:"money"}];
  return(<nav style={{position:"fixed",bottom:0,left:0,right:0,background:"#0a0a14",borderTop:"1px solid #1e293b",display:"flex",zIndex:100,paddingBottom:"env(safe-area-inset-bottom,0px)"}}>
    {nav.map(n=>{const a=view===n.id||(view==="project_detail"&&n.id==="projects");return(<button key={n.id} onClick={()=>go(n.id)} style={{flex:1,padding:"10px 4px 8px",border:"none",background:"none",color:a?"#f59e0b":"#475569",cursor:"pointer",display:"flex",flexDirection:"column",alignItems:"center",gap:3}}><Ic n={n.icon} s={20} c={a?"#f59e0b":"#475569"}/><span style={{fontSize:10,fontWeight:a?700:500}}>{n.label}</span></button>);})}
  </nav>);
}

function Sidebar({view,go,user,onLogout,col,setCol}){
  const nav=[
    {id:"dashboard",label:"Dashboard",icon:"dash"},
    {id:"projects",label:"Projetos",icon:"folder"},
    {id:"timeline",label:"Timeline",icon:"time"},
    {id:"tasks",label:"Tarefas",icon:"task"},
    {id:"finances",label:"Financeiro",icon:"money"},
    ...(user.role==="admin"?[{id:"admin",label:"Painel Admin",icon:"shield"}]:[]),
    {id:"help",label:"Ajuda",icon:"help"},
    {id:"settings",label:"Config.",icon:"gear"},
  ];
  return(<aside style={{width:col?60:220,minHeight:"100vh",background:"#0a0a14",borderRight:"1px solid #1e293b",display:"flex",flexDirection:"column",transition:"width .2s",flexShrink:0,overflow:"hidden"}}>
    <div style={{padding:col?"14px 10px":"18px 16px",borderBottom:"1px solid #1e293b",display:"flex",alignItems:"center",gap:8,justifyContent:col?"center":"flex-start"}}><span style={{fontSize:24,flexShrink:0}}>📖</span>{!col&&<span style={{color:"#f1f5f9",fontWeight:800,fontSize:15,letterSpacing:-.5,whiteSpace:"nowrap"}}>ProjectOS</span>}</div>
    <nav style={{flex:1,padding:"10px 6px",display:"flex",flexDirection:"column",gap:2,overflowY:"auto"}}>{nav.map(n=>{const a=view===n.id||(n.id==="projects"&&view==="project_detail");return(<button key={n.id} onClick={()=>go(n.id)} style={{display:"flex",alignItems:"center",gap:10,padding:col?"10px":"10px 12px",borderRadius:8,border:"none",background:a?"#f59e0b11":"transparent",color:a?"#f59e0b":"#64748b",cursor:"pointer",fontWeight:600,fontSize:13,transition:"all .15s",justifyContent:col?"center":"flex-start",width:"100%"}}><Ic n={n.icon} s={18} c={a?"#f59e0b":"#64748b"}/>{!col&&n.label}</button>);})}</nav>
    <div style={{padding:"10px 6px",borderTop:"1px solid #1e293b"}}>
      {!col&&<div style={{padding:"8px 12px",marginBottom:4}}><div style={{fontSize:13,fontWeight:600,color:"#94a3b8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{user.name}</div><div style={{fontSize:11,color:"#475569"}}>{roI(user.role).label}</div></div>}
      <button onClick={onLogout} style={{display:"flex",alignItems:"center",gap:8,padding:col?"10px":"10px 12px",borderRadius:8,border:"none",background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:13,fontWeight:600,width:"100%",justifyContent:col?"center":"flex-start"}}><Ic n="logout" s={16} c="#ef4444"/>{!col&&"Sair"}</button>
      <button onClick={()=>setCol(!col)} style={{display:"flex",alignItems:"center",gap:8,padding:col?"10px":"10px 12px",borderRadius:8,border:"none",background:"transparent",color:"#334155",cursor:"pointer",fontSize:12,width:"100%",justifyContent:col?"center":"flex-start",marginTop:2}}>{col?"▶":"◀"}</button>
    </div>
  </aside>);
}

// ── DASHBOARD ──────────────────────────────────────────────────────────────────
function Dashboard({projects,user,go,setSel}){
  const m=useMobile();
  const portfolio=Domain.metrics.portfolio(projects,user);
  const myP=portfolio.projects;
  const rev=portfolio.revenue;
  const tar=portfolio.target;
  const active=myP.filter(p=>p.status==="active");
  const needsAttention=myP.filter(p=>p.status!=="completed"&&p.status!=="archived").sort((a,b)=>a.progress-b.progress).slice(0,5);
  const nextTargets=myP.filter(p=>p.targetDate&&p.status!=="completed"&&p.status!=="archived").sort((a,b)=>a.targetDate.localeCompare(b.targetDate)).slice(0,5);
  const openProject=p=>{setSel(p.id);go("project_detail");};
  const StatC=({label,value,icon,color,sub})=>(<Card style={{flex:"1 1 160px"}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8}}><div style={{minWidth:0}}><div style={{fontSize:m?22:28,fontWeight:800,color,fontFamily:"'Space Mono',monospace",letterSpacing:-1}}>{value}</div><div style={{fontSize:12,color:"#64748b",marginTop:3}}>{label}</div>{sub&&<div style={{fontSize:11,color:"#475569",marginTop:4}}>{sub}</div>}</div><div style={{background:color+"22",padding:10,borderRadius:10,flexShrink:0}}><Ic n={icon} s={20} c={color}/></div></div></Card>);
  return(<div style={{padding:m?"16px":"32px",maxWidth:1400,paddingBottom:m?80:32}}>
    {/* Header */}
    <div style={{marginBottom:28,display:"flex",justifyContent:"space-between",alignItems:"flex-end",flexWrap:"wrap",gap:12}}>
      <div><h2 style={{color:"#f1f5f9",fontSize:m?20:26,fontWeight:800,margin:0}}>Olá, {user.name?.split(" ")[0]} 👋</h2><p style={{color:"#475569",fontSize:13,margin:"6px 0 0"}}>{new Date().toLocaleDateString("pt-BR",{weekday:"long",day:"numeric",month:"long",year:"numeric"})}</p></div>
      {!m&&<Btn sm v="outline" icon="plus" onClick={()=>go("projects")}>Novo Projeto</Btn>}
    </div>

    {/* Stats row */}
    <div style={{display:"grid",gridTemplateColumns:m?"repeat(2,1fr)":"repeat(5,1fr)",gap:14,marginBottom:24}}>
      <StatC label="Total de Projetos" value={portfolio.total} icon="folder" color="#6366f1"/>
      <StatC label="Em Andamento" value={portfolio.active} icon="chart" color="#10b981"/>
      <StatC label="Planejamento" value={portfolio.planning} icon="dash" color="#f59e0b"/>
      <StatC label="Concluídos" value={portfolio.completed} icon="check" color="#3b82f6"/>
      <StatC label="Receita Total" value={`R$ ${rev.toLocaleString("pt-BR")}`} icon="money" color="#a78bfa" sub={tar>0?`${((rev/tar)*100).toFixed(1)}% da meta`:"Meta não definida"}/>
    </div>

    {/* Main 2-col grid on desktop */}
    <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:20,marginBottom:20}}>
      {/* Status dos projetos */}
      <Card>
        <h3 style={{color:"#e2e8f0",fontSize:14,fontWeight:700,margin:"0 0 16px",display:"flex",alignItems:"center",gap:8}}><Ic n="chart" s={16} c="#6366f1"/> Status dos Projetos</h3>
        <div style={{display:"flex",flexDirection:"column",gap:12}}>
          {STATUSES.map(s=>{const cnt=myP.filter(p=>p.status===s.value).length;const pct=myP.length?(cnt/myP.length)*100:0;return(<div key={s.value}><div style={{display:"flex",justifyContent:"space-between",marginBottom:5}}><span style={{fontSize:13,color:"#94a3b8"}}>{s.label}</span><span style={{fontSize:13,color:s.color,fontWeight:700,fontFamily:"'Space Mono',monospace"}}>{cnt}</span></div><PBar value={pct} color={s.color} h={6}/></div>);})}
        </div>
      </Card>

      {/* Projetos em andamento com progresso */}
      <Card>
        <h3 style={{color:"#e2e8f0",fontSize:14,fontWeight:700,margin:"0 0 16px",display:"flex",alignItems:"center",gap:8}}><Ic n="dash" s={16} c="#10b981"/> Progresso dos Projetos Ativos</h3>
        {active.length===0?<div style={{textAlign:"center",padding:24,color:"#334155",fontSize:13}}>Nenhum projeto em andamento.</div>:
        <div style={{display:"flex",flexDirection:"column",gap:12}}>
          {active.slice(0,6).map(p=><div key={p.id} onClick={()=>openProject(p)} style={{cursor:"pointer"}}>
            <div style={{display:"flex",justifyContent:"space-between",marginBottom:5,alignItems:"center"}}>
              <span style={{fontSize:13,color:"#e2e8f0",display:"flex",alignItems:"center",gap:6}}><span style={{fontSize:16}}>{p.icon}</span><span style={{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:160}}>{p.name}</span></span>
              <span style={{fontSize:12,color:pCol(p.progress),fontFamily:"'Space Mono',monospace",fontWeight:700,flexShrink:0}}>{p.progress}%</span>
            </div>
            <PBar value={p.progress} color={p.color} h={5}/>
          </div>)}
        </div>}
      </Card>
    </div>

    <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:20}}>
      <Card>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
          <h3 style={{color:"#e2e8f0",fontSize:14,fontWeight:700,margin:0,display:"flex",alignItems:"center",gap:8}}><Ic n="dash" s={16} c="#f59e0b"/> Pedem Atenção</h3>
          <Btn sm v="ghost" onClick={()=>go("projects")} icon="eye">Projetos</Btn>
        </div>
        {needsAttention.length===0?<div style={{textAlign:"center",padding:28,color:"#334155",fontSize:13}}>Nada pendente por aqui.</div>:
        <div style={{display:"flex",flexDirection:"column",gap:10}}>
          {needsAttention.map(p=>{const si=stI(p.status);return(<div key={p.id} onClick={()=>openProject(p)} style={{display:"grid",gridTemplateColumns:"auto minmax(0,1fr) auto",gap:10,alignItems:"center",padding:"10px 12px",borderRadius:8,background:"#070711",border:"1px solid #1e293b",cursor:"pointer"}}>
            <div style={{width:34,height:34,borderRadius:8,background:p.color+"22",display:"flex",alignItems:"center",justifyContent:"center",fontSize:17}}>{p.icon}</div>
            <div style={{minWidth:0}}><div style={{fontSize:13,fontWeight:700,color:"#e2e8f0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{p.name}</div><div style={{fontSize:11,color:si.color,marginTop:2}}>{si.label}</div></div>
            <div style={{width:70,textAlign:"right"}}><div style={{fontSize:12,color:pCol(p.progress),fontWeight:800,fontFamily:"'Space Mono',monospace",marginBottom:3}}>{p.progress}%</div><PBar value={p.progress} color={p.color} h={4}/></div>
          </div>);})}
        </div>}
      </Card>

      <Card>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
          <h3 style={{color:"#e2e8f0",fontSize:14,fontWeight:700,margin:0,display:"flex",alignItems:"center",gap:8}}><Ic n="time" s={16} c="#10b981"/> Próximas Entregas</h3>
          <Btn sm v="ghost" onClick={()=>go("timeline")} icon="time">Timeline</Btn>
        </div>
        {nextTargets.length===0?<div style={{textAlign:"center",padding:28,color:"#334155",fontSize:13}}>Sem datas alvo definidas.</div>:
        <div style={{display:"flex",flexDirection:"column",gap:10}}>
          {nextTargets.map(p=><div key={p.id} onClick={()=>openProject(p)} style={{display:"grid",gridTemplateColumns:"auto minmax(0,1fr) auto",gap:10,alignItems:"center",padding:"10px 12px",borderRadius:8,background:"#070711",border:"1px solid #1e293b",cursor:"pointer"}}>
            <div style={{width:34,height:34,borderRadius:8,background:p.color+"22",display:"flex",alignItems:"center",justifyContent:"center",fontSize:17}}>{p.icon}</div>
            <div style={{minWidth:0}}><div style={{fontSize:13,fontWeight:700,color:"#e2e8f0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{p.name}</div><div style={{fontSize:11,color:"#64748b",marginTop:2}}>{p.category}</div></div>
            <div style={{fontSize:12,color:"#10b981",fontWeight:800,whiteSpace:"nowrap"}}>{fmt(p.targetDate)}</div>
          </div>)}
        </div>}
      </Card>
    </div>
  </div>);
}

// ── PROJECTS ───────────────────────────────────────────────────────────────────
function Projects({projects,users,user,reloadProjects,go,setSel,cats,toast}){
  const m=useMobile();
  const [search,setSearch]=useState("");const [fSt,setFSt]=useState("active");const [fCat,setFCat]=useState("all");const [viewMode,setViewMode]=useState("list");
  const [modal,setModal]=useState(false);const [editId,setEditId]=useState(null);const [saving,setSaving]=useState(false);const [showAdvanced,setShowAdvanced]=useState(false);
  const ef=Domain.project.createDraft(cats);
  const [form,setForm]=useState(ef);
  const myP=Domain.metrics.visibleProjects(projects,user);
  const filt=myP.filter(p=>{const q=search.toLowerCase();return(p.name.toLowerCase().includes(q)||p.description.toLowerCase().includes(q))&&(fSt==="all"||p.status===fSt)&&(fCat==="all"||p.category===fCat);}).sort((a,b)=>{const ar=a.lastAccessedAt||a.updatedAt||a.createdAt||"";const br=b.lastAccessedAt||b.updatedAt||b.createdAt||"";return br.localeCompare(ar)||a.name.localeCompare(b.name);});
  const listMode=viewMode==="list"&&!m;
  const canE=p=>Domain.permissions.canEditProject(user,p);
  const openProject=p=>{setSel(p.id);go("project_detail");};
  const openNewProject=()=>{setForm(ef);setEditId(null);setShowAdvanced(false);setModal(true);};
  const openEditProject=p=>{setForm({...p,monetization:{...p.monetization}});setEditId(p.id);setShowAdvanced(true);setModal(true);};
  const save=async()=>{
    if(!form.name){toast("Nome do projeto é obrigatório.","error");return;}setSaving(true);
    try{
      const project=editId?Domain.project.normalize(form,projects.find(p=>p.id===editId)||{}):Domain.project.create(form,user.id);
      const validation=Domain.project.validate(project);
      if(!validation.valid){toast(validation.errors[0],"error");setSaving(false);return;}
      await db_set("projects",editId||project.id,project);
      await db_syncProjectChildren(project,user.id);
      await db_logActivity({workspaceId:Domain.workspace.idOf(project),action:editId?"project_updated":"project_created",entityType:"project",entityId:project.id,projectId:project.id,actorId:user.id,actorName:user.name,summary:editId?`Projeto atualizado: ${project.name}`:`Projeto criado: ${project.name}`,metadata:{status:project.status,progress:project.progress}});
      await reloadProjects();toast(editId?"Projeto salvo!":"Projeto criado!","success");setModal(false);
    }catch(e){toast("Erro ao salvar: "+e.message,"error");}
    setSaving(false);
  };
  const del=async id=>{if(!confirm("Excluir projeto?"))return;const project=projects.find(p=>p.id===id);await db_del("projects",id);if(project)await db_logActivity({workspaceId:Domain.workspace.idOf(project),action:"project_deleted",entityType:"project",entityId:id,projectId:id,actorId:user.id,actorName:user.name,summary:`Projeto excluído: ${project.name}`});await reloadProjects();toast("Projeto excluído.","info");};
  return(<div style={{padding:m?"16px":"28px",maxWidth:1440,paddingBottom:m?80:28}}>
    <SH title="Projetos" sub={`${filt.length} projeto(s)`} action={(user.role==="admin"||user.role==="manager")&&<Btn icon="plus" onClick={openNewProject} sm>Novo Projeto</Btn>}/>
    <div style={{display:"flex",flexDirection:"column",gap:10,marginBottom:20}}>
      <div style={{position:"relative"}}><div style={{position:"absolute",left:12,top:"50%",transform:"translateY(-50%)",pointerEvents:"none"}}><Ic n="eye" s={14} c="#475569"/></div><input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Buscar projetos..." style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"10px 12px 10px 36px",fontSize:14,width:"100%",outline:"none",minHeight:44}}/></div>
      <div style={{display:"flex",gap:8,overflowX:"auto",paddingBottom:4}}>{[{value:"all",label:"Todos"},...STATUSES].map(s=><button key={s.value} onClick={()=>setFSt(s.value)} style={{padding:"6px 12px",borderRadius:20,border:`1px solid ${fSt===s.value?"#f59e0b44":"#1e293b"}`,flexShrink:0,background:fSt===s.value?"#f59e0b22":"#0f172a",color:fSt===s.value?"#f59e0b":"#64748b",cursor:"pointer",fontSize:12,fontWeight:600}}>{s.label}</button>)}</div>
      <div style={{display:"flex",gap:8,overflowX:"auto",paddingBottom:4}}>{[{value:"all",label:"Todas categorias"},...cats.map(c=>({value:c,label:c}))].map(c=><button key={c.value} onClick={()=>setFCat(c.value)} style={{padding:"6px 12px",borderRadius:20,border:`1px solid ${fCat===c.value?"#a78bfa44":"#1e293b"}`,flexShrink:0,background:fCat===c.value?"#a78bfa22":"#0f172a",color:fCat===c.value?"#a78bfa":"#64748b",cursor:"pointer",fontSize:12,fontWeight:600}}>{c.label}</button>)}</div>
      {!m&&<div style={{display:"flex",justifyContent:"flex-end",gap:6}}>{[{id:"cards",label:"Cards"},{id:"list",label:"Lista"}].map(v=><button key={v.id} onClick={()=>setViewMode(v.id)} style={{padding:"7px 12px",borderRadius:8,border:`1px solid ${viewMode===v.id?"#f59e0b44":"#1e293b"}`,background:viewMode===v.id?"#f59e0b22":"#0f172a",color:viewMode===v.id?"#f59e0b":"#64748b",cursor:"pointer",fontSize:12,fontWeight:700}}>{v.label}</button>)}</div>}
    </div>
    <div style={{display:"grid",gridTemplateColumns:listMode?"1fr":"repeat(auto-fit,minmax(320px,1fr))",gap:listMode?10:14}}>
      {filt.map(p=>{const si=stI(p.status);const taskCount=(p.tasks||[]).length;const target=p.monetization?.target||0;const revenue=p.monetization?.revenue||0;return(<Card key={p.id} style={{display:listMode?"grid":"flex",gridTemplateColumns:listMode?"minmax(0,1.5fr) 180px auto":undefined,flexDirection:listMode?undefined:"column",gap:listMode?16:12,alignItems:listMode?"center":"stretch",padding:listMode?"14px 16px":16}}>
        <div style={{display:"flex",gap:12,alignItems:"flex-start",minWidth:0}}>
          <div style={{background:p.color+"22",borderRadius:8,width:42,height:42,display:"flex",alignItems:"center",justifyContent:"center",fontSize:22,flexShrink:0}}>{p.icon}</div>
          <div style={{minWidth:0,flex:1}}>
            <div onClick={()=>openProject(p)} style={{fontSize:14,fontWeight:800,color:"#f1f5f9",cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{p.name}</div>
            <div style={{display:"flex",gap:6,flexWrap:"wrap",marginTop:5}}><Bdg label={si.label} color={si.color} sm/><Bdg label={p.category} color="#475569" sm/>{taskCount>0&&<Bdg label={`${taskCount} tarefa(s)`} color="#6366f1" sm/>}</div>
            <p style={{fontSize:12,color:"#64748b",margin:"8px 0 0",lineHeight:1.45,display:"-webkit-box",WebkitLineClamp:listMode?1:2,WebkitBoxOrient:"vertical",overflow:"hidden"}}>{p.description||"Sem descrição."}</p>
          </div>
        </div>
        <div style={{minWidth:0}}>
          <div style={{display:"flex",justifyContent:"space-between",marginBottom:5}}><span style={{fontSize:12,color:"#64748b"}}>Progresso</span><span style={{fontSize:12,color:pCol(p.progress),fontWeight:800,fontFamily:"'Space Mono',monospace"}}>{p.progress}%</span></div>
          <PBar value={p.progress} color={p.color}/>
          {(p.monetization?.model||revenue>0||target>0)&&<div style={{display:"flex",justifyContent:"space-between",gap:8,marginTop:8,fontSize:11,color:"#64748b"}}><span style={{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{p.monetization?.model||"Sem modelo"}</span><span style={{color:"#10b981",fontWeight:700,flexShrink:0}}>R$ {revenue.toLocaleString("pt-BR")}</span></div>}
        </div>
        <div style={{display:"flex",gap:8,flexWrap:"wrap",justifyContent:listMode?"flex-end":"flex-start",alignItems:"center",borderLeft:listMode?"1px solid #1e293b":"none",paddingLeft:listMode?12:0}}>
          <Btn sm v="outline" onClick={()=>openProject(p)} icon="eye">Ver</Btn>
          {canE(p)&&<Btn sm v="ghost" onClick={()=>openEditProject(p)} icon="edit">Editar</Btn>}
          {user.role==="admin"&&<Btn sm danger onClick={()=>del(p.id)} icon="trash">Excluir</Btn>}
        </div>
      </Card>);})}
      {filt.length===0&&<div style={{gridColumn:"1/-1",textAlign:"center",padding:60,color:"#475569"}}>Nenhum projeto encontrado.</div>}
    </div>
    {modal&&<Modal title={editId?"Editar Projeto":"Novo Projeto"} onClose={()=>setModal(false)} wide>
      <div style={{display:"flex",flexDirection:"column",gap:16}}>
        <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1.4fr .8fr",gap:14}}>
          <Inp label="Nome" value={form.name} onChange={v=>setForm({...form,name:v})} required placeholder="Ex: Dicionário News"/>
          <Inp label="Categoria" value={form.category} onChange={v=>setForm({...form,category:v})} options={cats}/>
        </div>
        <Inp label="Descrição" value={form.description} onChange={v=>setForm({...form,description:v})} rows={3} placeholder="Objetivo, escopo ou próxima entrega do projeto..."/>
        <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:14}}>
          <Inp label="Status" value={form.status} onChange={v=>setForm({...form,status:v})} options={STATUSES.map(s=>({value:s.value,label:s.label}))}/>
          <div>
            <label style={{fontSize:12,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:.8,display:"block",marginBottom:6}}>Progresso: {form.progress}%</label>
            <input type="range" min={0} max={100} value={form.progress} onChange={e=>setForm({...form,progress:+e.target.value})} style={{width:"100%",accentColor:"#f59e0b"}}/>
          </div>
        </div>

        <button onClick={()=>setShowAdvanced(v=>!v)} style={{background:"#0a0a14",border:"1px solid #1e293b",borderRadius:8,color:"#94a3b8",padding:"10px 12px",cursor:"pointer",fontSize:13,fontWeight:700,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
          <span>Campos avançados</span><span style={{color:"#f59e0b"}}>{showAdvanced?"Ocultar":"Mostrar"}</span>
        </button>

        {showAdvanced&&<div style={{display:"flex",flexDirection:"column",gap:16,borderTop:"1px solid #1e293b",paddingTop:16}}>
          <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:14}}>
            <Inp label="Início" value={form.startDate} onChange={v=>setForm({...form,startDate:v})} type="date"/>
            <Inp label="Data Alvo" value={form.targetDate} onChange={v=>setForm({...form,targetDate:v})} type="date"/>
          </div>
          <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:16}}>
            <div><label style={{fontSize:12,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:.8,display:"block",marginBottom:8}}>Ícone</label><div style={{display:"flex",flexWrap:"wrap",gap:6}}>{ICONS.map(ic=><button key={ic} onClick={()=>setForm({...form,icon:ic})} style={{fontSize:20,padding:"5px 7px",borderRadius:6,border:`2px solid ${form.icon===ic?"#f59e0b":"transparent"}`,background:"#0a0a14",cursor:"pointer"}}>{ic}</button>)}</div></div>
            <div><label style={{fontSize:12,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:.8,display:"block",marginBottom:8}}>Cor</label><div style={{display:"flex",gap:8,flexWrap:"wrap"}}>{CLRS.map(c=><button key={c} onClick={()=>setForm({...form,color:c})} style={{width:30,height:30,borderRadius:"50%",background:c,border:`3px solid ${form.color===c?"white":"transparent"}`,cursor:"pointer"}}/>)}</div></div>
          </div>
          <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1.2fr .8fr .8fr",gap:14}}>
            <Inp label="Modelo de Monetização" value={form.monetization.model} onChange={v=>setForm({...form,monetization:{...form.monetization,model:v}})} placeholder="Ex: AdSense, Licença..."/>
            <Inp label="Receita atual (R$)" value={form.monetization.revenue} onChange={v=>setForm({...form,monetization:{...form.monetization,revenue:+v}})} type="number"/>
            <Inp label="Meta de receita (R$)" value={form.monetization.target} onChange={v=>setForm({...form,monetization:{...form.monetization,target:+v}})} type="number"/>
          </div>
        </div>}
        <div style={{display:"flex",gap:10,marginTop:4}}><Btn v="ghost" onClick={()=>setModal(false)} fw>Cancelar</Btn><Btn onClick={save} loading={saving} icon="check" fw>{editId?"Salvar":"Criar Projeto"}</Btn></div>
      </div>
    </Modal>}
  </div>);
}

// ── PROJECT DETAIL ─────────────────────────────────────────────────────────────
function Detail({pid,projects,users,user,reloadProjects,go,toast,globalTasks,reloadGlobalTasks}){
  const m=useMobile();
  const [tab,setTab]=useState("tasks");
  const [showM,setShowM]=useState(false);const [showT,setShowT]=useState(false);const [showN,setShowN]=useState(false);
  const [mF,setMF]=useState({title:"",date:now()});const [tF,setTF]=useState({title:"",priority:"Média",status:"todo",dueDate:"",assigneeId:""});const [nF,setNF]=useState({text:""});
  const [ePct,setEPct]=useState(false);const [nPct,setNPct]=useState(0);
  const p=projects.find(x=>x.id===pid);
  useEffect(()=>{
    if(!p)return;
    let cancelled=false;
    (async()=>{
      try{
        const lastAccessedAt=new Date().toISOString();
        await db_set("projects",p.id,{...p,lastAccessedAt,lastAccessedBy:user.id});
        if(!cancelled)await reloadProjects();
      }catch(e){console.warn("Project access tracking skipped:",e);}
    })();
    return()=>{cancelled=true;};
  },[pid]);
  if(!p)return<div style={{padding:20,color:"#64748b"}}>Projeto não encontrado.</div>;
  const si=stI(p.status);const ce=user.role==="admin"||user.role==="manager"||(p.team||[]).includes(user.id);
  const upd=async ch=>{await db_set("projects",p.id,Domain.workspace.withRecord({...p,...ch,updatedAt:now()}));await reloadProjects();};
  const addM=async()=>{if(!mF.title)return;const milestone={id:"m"+uid(),...mF,completed:false,createdBy:user.id,createdAt:now(),updatedAt:now()};await upd({milestones:[...(p.milestones||[]),milestone]});await db_saveMilestoneDocument(p,milestone,user.id);await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"milestone_created",entityType:"milestone",entityId:milestone.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Marco criado: ${milestone.title}`});setMF({title:"",date:now()});setShowM(false);toast("Marco adicionado!","success");};
  const addT=async()=>{if(!tF.title)return;const task={id:"t"+uid(),...tF,comments:[],checklist:[],history:[{id:"h"+uid(),text:"Tarefa criada",author:user.name,authorId:user.id,date:new Date().toISOString()}],createdBy:user.id,createdAt:now(),updatedAt:now()};await upd({tasks:[...(p.tasks||[]),task]});await db_saveTaskDocument(task,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:user.id,sourceType:"project"});await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_created",entityType:"task",entityId:task.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa criada: ${task.title}`,metadata:{status:task.status,priority:task.priority}});setTF({title:"",priority:"Média",status:"todo",dueDate:"",assigneeId:""});setShowT(false);toast("Tarefa adicionada!","success");};
  const addN=async()=>{if(!nF.text)return;const note={id:"n"+uid(),text:nF.text,author:user.name,createdBy:user.id,date:now(),createdAt:now(),updatedAt:now()};await upd({notes:[...(p.notes||[]),note]});await db_saveNoteDocument(p,note,user.id);await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"note_created",entityType:"note",entityId:note.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:"Nota criada"});setNF({text:""});setShowN(false);toast("Nota salva!","success");};
  const updateProjectTask=async(task,status)=>{const updated={...task,status,history:[...(task.history||[]),{id:"h"+uid(),text:`Status alterado para ${status}`,author:user.name,authorId:user.id,date:new Date().toISOString()}].slice(-30),updatedAt:now(),completedAt:status==="done"?now():null};await db_saveTaskDocument(updated,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:user.id,sourceType:"project"});await upd({tasks:(p.tasks||[]).map(x=>x.id===task.id?updated:x)});await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_moved",entityType:"task",entityId:task.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa movida: ${task.title}`,metadata:{from:task.status,to:status}});};
  const updateMilestone=async(milestone,changes)=>{const updated={...milestone,...changes,updatedAt:now(),completedAt:changes.completed?now():null};await db_saveMilestoneDocument(p,updated,user.id);await upd({milestones:(p.milestones||[]).map(x=>x.id===milestone.id?updated:x)});await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"milestone_updated",entityType:"milestone",entityId:milestone.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Marco atualizado: ${milestone.title}`,metadata:changes});};
  const deleteProjectTask=async(task)=>{await db_softDeleteTaskDocument(task,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:user.id,sourceType:"project"});await upd({tasks:(p.tasks||[]).filter(x=>x.id!==task.id)});await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_deleted",entityType:"task",entityId:task.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa excluída: ${task.title}`});};

  // Tarefas vinculadas a este projeto
  const taskProjectIds=t=>t.projects||t.projectIds||[];
  const linkedGlobal=(globalTasks||[]).filter(t=>taskProjectIds(t).includes(p.id));
  const projectTaskCount=(p.tasks||[]).length;
  const combinedTasks=[...(p.tasks||[]),...linkedGlobal];
  const totalTasks=combinedTasks.length;
  const doneTasks=combinedTasks.filter(t=>t.status==="done").length;
  const nextTask=combinedTasks.find(t=>t.status!=="done");
  const nextMilestone=(p.milestones||[]).filter(mil=>!mil.completed).sort((a,b)=>(a.date||"").localeCompare(b.date||""))[0];
  const lastNote=(p.notes||[]).slice().sort((a,b)=>(b.date||"").localeCompare(a.date||""))[0];
  const pendingMilestones=(p.milestones||[]).filter(mil=>!mil.completed).length;
  const revenue=p.monetization?.revenue||0;
  const target=p.monetization?.target||0;
  const revenuePct=target>0?Math.min(100,(revenue/target)*100):0;
  const statusLabel=s=>s==="todo"?"A Fazer":s==="doing"?"Andamento":"Feito";
  const statusColor=s=>s==="done"?"#10b981":s==="doing"?"#6366f1":"#64748b";
  const TABS=[{id:"tasks",label:`${m?"Tarefas":"Tarefas"} (${totalTasks})`},{id:"milestones",label:`${m?"Marcos":"Marcos"} (${(p.milestones||[]).length})`},{id:"notes",label:`${m?"Notas":"Notas"} (${(p.notes||[]).length})`},{id:"team",label:"Equipe"},{id:"overview",label:m?"Resumo": "Resumo"}];
  return(<div style={{padding:m?"16px":"28px",maxWidth:1440,paddingBottom:m?80:28}}>
    <button onClick={()=>go("projects")} style={{background:"none",border:"none",color:"#64748b",cursor:"pointer",fontSize:13,padding:"0 0 12px",display:"flex",alignItems:"center",gap:4}}><Ic n="back" s={14} c="#64748b"/> Voltar</button>
    <div style={{marginBottom:20}}>
      <div style={{display:"flex",alignItems:"flex-start",gap:12,flexWrap:"wrap"}}>
        <div style={{background:p.color+"22",borderRadius:12,padding:"10px 12px",fontSize:28,flexShrink:0}}>{p.icon}</div>
        <div style={{flex:1,minWidth:0}}><h2 style={{color:"#f1f5f9",fontSize:m?18:22,fontWeight:800,margin:0,wordBreak:"break-word"}}>{p.name}</h2><div style={{display:"flex",gap:8,marginTop:6,flexWrap:"wrap"}}><Bdg label={si.label} color={si.color}/><Bdg label={p.category} color="#475569"/></div></div>
      </div>
      <div style={{marginTop:16}}>
        <div style={{display:"flex",justifyContent:"space-between",marginBottom:6,alignItems:"center"}}>
          <span style={{fontSize:13,color:"#64748b"}}>Progresso geral</span>
          <div style={{display:"flex",alignItems:"center",gap:8}}><span style={{fontSize:14,fontWeight:700,color:pCol(ePct?nPct:p.progress),fontFamily:"'Space Mono',monospace"}}>{ePct?nPct:p.progress}%</span>{ce&&!ePct&&<button onClick={()=>{setNPct(p.progress);setEPct(true);}} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",padding:2}}><Ic n="edit" s={13} c="#64748b"/></button>}</div>
        </div>
        <PBar value={ePct?nPct:p.progress} h={8} color={p.color}/>
        {ePct&&<div style={{display:"flex",gap:10,alignItems:"center",marginTop:10}}><input type="range" min={0} max={100} value={nPct} onChange={e=>setNPct(+e.target.value)} style={{flex:1,accentColor:"#f59e0b"}}/><Btn sm onClick={async()=>{await upd({progress:nPct});setEPct(false);toast("Progresso atualizado!","success");}}>OK</Btn><Btn sm v="ghost" onClick={()=>setEPct(false)}>✕</Btn></div>}
      </div>
    </div>
    <div style={{display:"grid",gridTemplateColumns:m?"repeat(2,1fr)":"repeat(4,1fr)",gap:10,marginBottom:14}}>
      {[{label:"Tarefas",value:`${doneTasks}/${totalTasks}`,color:"#6366f1"},{label:"Marcos pendentes",value:pendingMilestones,color:"#f59e0b"},{label:"Equipe",value:(p.team||[]).length,color:"#10b981"},{label:"Meta receita",value:target>0?`${revenuePct.toFixed(0)}%`:"--",color:"#a78bfa"}].map(s=><div key={s.label} style={{background:"#0a0a14",border:"1px solid #1e293b",borderRadius:8,padding:"10px 12px",minHeight:62}}><div style={{fontSize:11,color:"#64748b",fontWeight:700,textTransform:"uppercase",letterSpacing:.6,marginBottom:4}}>{s.label}</div><div style={{fontSize:18,color:s.color,fontWeight:800,fontFamily:"'Space Mono',monospace"}}>{s.value}</div></div>)}
    </div>
    {ce&&<div style={{display:"flex",gap:8,flexWrap:"wrap",marginBottom:18}}>
      <Btn sm icon="plus" onClick={()=>{setTab("tasks");setShowT(true);}}>Tarefa</Btn>
      <Btn sm v="ghost" icon="check" onClick={()=>{setTab("milestones");setShowM(true);}}>Marco</Btn>
      <Btn sm v="ghost" icon="note" onClick={()=>{setTab("notes");setShowN(true);}}>Nota</Btn>
    </div>}
    <div style={{display:"grid",gridTemplateColumns:m?"1fr":"repeat(3,1fr)",gap:12,marginBottom:18}}>
      <Card style={{cursor:"pointer"}} onClick={()=>setTab("tasks")}><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 8px"}}>Próxima tarefa</h4><div style={{fontSize:14,color:"#e2e8f0",fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{nextTask?.title||"Nenhuma tarefa pendente"}</div>{nextTask&&<div style={{marginTop:8}}><Bdg label={statusLabel(nextTask.status)} color={statusColor(nextTask.status)} sm/> <Bdg label={nextTask.priority||"Média"} color={PC[nextTask.priority]||"#64748b"} sm/></div>}</Card>
      <Card style={{cursor:"pointer"}} onClick={()=>setTab("milestones")}><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 8px"}}>Próximo marco</h4><div style={{fontSize:14,color:"#e2e8f0",fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{nextMilestone?.title||"Nenhum marco pendente"}</div>{nextMilestone&&<div style={{fontSize:12,color:"#f59e0b",marginTop:8,fontWeight:700}}>{fmt(nextMilestone.date)}</div>}</Card>
      <Card style={{cursor:"pointer"}} onClick={()=>setTab("notes")}><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 8px"}}>Última nota</h4><div style={{fontSize:13,color:lastNote?"#e2e8f0":"#64748b",lineHeight:1.45,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}}>{lastNote?.text||"Nenhuma nota registrada"}</div>{lastNote&&<div style={{fontSize:11,color:"#475569",marginTop:8}}>{fmt(lastNote.date)}</div>}</Card>
    </div>
    <div style={{display:"flex",gap:0,borderBottom:"1px solid #1e293b",marginBottom:20,overflowX:"auto"}}>{TABS.map(t=><button key={t.id} onClick={()=>setTab(t.id)} style={{padding:m?"9px 12px":"10px 14px",border:"none",background:"none",color:tab===t.id?"#f59e0b":"#64748b",borderBottom:`2px solid ${tab===t.id?"#f59e0b":"transparent"}`,cursor:"pointer",fontSize:m?12:13,fontWeight:600,whiteSpace:"nowrap"}}>{t.label}</button>)}</div>
    {tab==="overview"&&(<div style={{display:"grid",gridTemplateColumns:m?"1fr":"2fr 1fr",gap:16}}>
      <div style={{display:"flex",flexDirection:"column",gap:14}}>
        <Card><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 10px"}}>Descrição</h4><p style={{color:"#e2e8f0",fontSize:14,lineHeight:1.7,margin:0}}>{p.description||"Sem descrição."}</p></Card>
        <Card><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 10px"}}>Marcos Recentes</h4>{(p.milestones||[]).length===0&&<p style={{color:"#475569",fontSize:13}}>Nenhum marco.</p>}<div style={{display:"flex",flexDirection:"column",gap:8}}>{(p.milestones||[]).slice(0,4).map(mil=>(<div key={mil.id} style={{display:"flex",gap:10,alignItems:"center"}}><div onClick={()=>ce&&updateMilestone(mil,{completed:!mil.completed})} style={{width:22,height:22,borderRadius:"50%",border:`2px solid ${mil.completed?"#10b981":"#334155"}`,background:mil.completed?"#10b98133":"transparent",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",cursor:ce?"pointer":"default"}}>{mil.completed&&<Ic n="check" s={10} c="#10b981"/>}</div><span style={{flex:1,fontSize:13,color:mil.completed?"#64748b":"#e2e8f0",textDecoration:mil.completed?"line-through":"none"}}>{mil.title}</span><span style={{fontSize:11,color:"#475569",flexShrink:0}}>{fmt(mil.date)}</span></div>))}</div></Card>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:14}}>
        <Card><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 10px"}}>Datas</h4>{[["Início",fmt(p.startDate)],["Meta",fmt(p.targetDate)],["Atualizado",fmt(p.updatedAt)]].map(([k,v])=>(<div key={k} style={{display:"flex",justifyContent:"space-between",marginBottom:8}}><span style={{fontSize:13,color:"#64748b"}}>{k}</span><span style={{fontSize:13,color:"#e2e8f0"}}>{v}</span></div>))}</Card>
        <Card><h4 style={{color:"#64748b",fontSize:11,textTransform:"uppercase",letterSpacing:1,margin:"0 0 10px"}}>Monetização</h4><div style={{marginBottom:8}}><span style={{fontSize:12,color:"#64748b"}}>Modelo: </span><span style={{fontSize:12,color:"#e2e8f0"}}>{p.monetization?.model||"—"}</span></div><div style={{display:"flex",justifyContent:"space-between",marginBottom:8}}><span style={{fontSize:13,color:"#64748b"}}>Receita</span><span style={{fontSize:14,color:"#10b981",fontWeight:700}}>R$ {(p.monetization?.revenue||0).toLocaleString("pt-BR")}</span></div><div style={{display:"flex",justifyContent:"space-between",marginBottom:10}}><span style={{fontSize:13,color:"#64748b"}}>Meta</span><span style={{fontSize:13,color:"#e2e8f0"}}>R$ {(p.monetization?.target||0).toLocaleString("pt-BR")}</span></div>{(p.monetization?.target||0)>0&&<><PBar value={Math.min(100,(p.monetization.revenue/p.monetization.target)*100)} color="#10b981" h={5}/><div style={{fontSize:11,color:"#64748b",marginTop:4}}>{((p.monetization.revenue/p.monetization.target)*100).toFixed(1)}% da meta</div></>}</Card>
      </div>
    </div>)}
    {tab==="tasks"&&(<div>
      {ce&&<div style={{marginBottom:14,display:"flex",gap:8,alignItems:"center"}}>
        <Btn sm icon="plus" onClick={()=>setShowT(true)}>Nova Tarefa</Btn>
        {linkedGlobal.length>0&&<span style={{fontSize:12,color:"#6366f1",background:"#6366f111",border:"1px solid #6366f133",borderRadius:20,padding:"4px 10px"}}>{linkedGlobal.length} tarefa(s) compartilhada(s)</span>}
      </div>}
      <div style={{display:"grid",gridTemplateColumns:m?"1fr":"repeat(3,1fr)",gap:12}}>
        {TCOLS.map(col=>{
          const projTasks=(p.tasks||[]).filter(t=>t.status===col.id);
          const globalCol=linkedGlobal.filter(t=>t.status===col.id);
          return(<div key={col.id} style={{background:"#0a0a14",borderRadius:10,padding:14}}>
            <div style={{fontSize:12,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:1,marginBottom:10}}>{col.label} <span style={{fontWeight:400}}>({projTasks.length+globalCol.length})</span></div>
            <div style={{display:"flex",flexDirection:"column",gap:8}}>
              {/* Tarefas internas do projeto */}
              {projTasks.map(t=>(<div key={t.id} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,padding:12}}>
                <div style={{fontSize:13,color:"#e2e8f0",fontWeight:600,marginBottom:8}}>{t.title}</div>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                  <Bdg label={t.priority} color={PC[t.priority]} sm/>
                  <div style={{display:"flex",gap:4}}>
                    {TCOLS.findIndex(c=>c.id===col.id)>0&&<button onClick={()=>updateProjectTask(t,TCOLS[TCOLS.findIndex(c=>c.id===col.id)-1].id)} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",fontSize:18,padding:"0 2px",lineHeight:1}}>‹</button>}
                    {TCOLS.findIndex(c=>c.id===col.id)<TCOLS.length-1&&<button onClick={()=>updateProjectTask(t,TCOLS[TCOLS.findIndex(c=>c.id===col.id)+1].id)} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",fontSize:18,padding:"0 2px",lineHeight:1}}>›</button>}
                    {ce&&<button onClick={()=>deleteProjectTask(t)} style={{background:"none",border:"none",cursor:"pointer",color:"#ef444466",fontSize:14,padding:"0 2px"}}>✕</button>}
                  </div>
                </div>
              </div>))}
              {/* Tarefas compartilhadas com este projeto */}
              {globalCol.map(t=>(<div key={t.id} style={{background:"#0f172a",border:"1px solid #6366f133",borderRadius:8,padding:12}}>
                <div style={{fontSize:10,color:"#6366f1",fontWeight:600,textTransform:"uppercase",letterSpacing:.6,marginBottom:4}}>Compartilhada</div>
                <div style={{fontSize:13,color:"#e2e8f0",fontWeight:600,marginBottom:t.description?6:8}}>{t.title}</div>
                {t.description&&<div style={{fontSize:11,color:"#475569",marginBottom:8,lineHeight:1.4}}>{t.description}</div>}
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                  <Bdg label={t.priority} color={PC[t.priority]} sm/>
                  <div style={{display:"flex",gap:4}}>
                    {TCOLS.findIndex(c=>c.id===col.id)>0&&<button onClick={async()=>{const updated=Domain.workspace.withRecord({...t,status:TCOLS[TCOLS.findIndex(c=>c.id===col.id)-1].id,updatedAt:now()});await db_set("globalTasks",t.id,updated);await db_saveTaskDocument(updated,{projectIds:updated.projects||updated.projectIds||[],createdBy:updated.createdBy||user.id,sourceType:"global"});await reloadGlobalTasks();}} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",fontSize:18,padding:"0 2px",lineHeight:1}}>‹</button>}
                    {TCOLS.findIndex(c=>c.id===col.id)<TCOLS.length-1&&<button onClick={async()=>{const updated=Domain.workspace.withRecord({...t,status:TCOLS[TCOLS.findIndex(c=>c.id===col.id)+1].id,updatedAt:now()});await db_set("globalTasks",t.id,updated);await db_saveTaskDocument(updated,{projectIds:updated.projects||updated.projectIds||[],createdBy:updated.createdBy||user.id,sourceType:"global"});await reloadGlobalTasks();}} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",fontSize:18,padding:"0 2px",lineHeight:1}}>›</button>}
                    <span style={{fontSize:11,color:"#6366f1",padding:"0 4px",cursor:"default"}} title="Gerencie pela tela de Tarefas">🔗</span>
                  </div>
                </div>
              </div>))}
              {projTasks.length===0&&globalCol.length===0&&<div style={{textAlign:"center",padding:20,color:"#1e293b",fontSize:12}}>Vazio</div>}
            </div>
          </div>);
        })}
      </div>
      {showT&&<Modal title="Nova Tarefa" onClose={()=>setShowT(false)}><div style={{display:"flex",flexDirection:"column",gap:14}}><Inp label="Título" value={tF.title} onChange={v=>setTF({...tF,title:v})} required/><div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:12}}><Inp label="Status" value={tF.status} onChange={v=>setTF({...tF,status:v})} options={TCOLS.map(c=>({value:c.id,label:c.label}))}/><Inp label="Prioridade" value={tF.priority} onChange={v=>setTF({...tF,priority:v})} options={["Baixa","Média","Alta","Crítica"]}/></div><div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:12}}><Inp label="Prazo" value={tF.dueDate||""} onChange={v=>setTF({...tF,dueDate:v})} type="date"/><Inp label="Responsável" value={tF.assigneeId||""} onChange={v=>setTF({...tF,assigneeId:v})} options={[{value:"",label:"Sem responsável"},...users.map(u=>({value:u.id,label:u.name}))]}/></div><div style={{display:"flex",gap:10,marginTop:8}}><Btn v="ghost" onClick={()=>setShowT(false)} fw>Cancelar</Btn><Btn onClick={addT} icon="plus" fw>Adicionar</Btn></div></div></Modal>}
    </div>)}
    {tab==="milestones"&&(<div>
      {ce&&<div style={{marginBottom:14}}><Btn sm icon="plus" onClick={()=>setShowM(true)}>Novo Marco</Btn></div>}
      <div style={{display:"flex",flexDirection:"column",gap:10}}>
        {(p.milestones||[]).sort((a,b)=>a.date.localeCompare(b.date)).map(mil=>(<Card key={mil.id} style={{display:"flex",gap:14,alignItems:"center",padding:"14px 16px"}}>
          <div onClick={()=>ce&&updateMilestone(mil,{completed:!mil.completed})} style={{width:32,height:32,borderRadius:"50%",border:`2px solid ${mil.completed?"#10b981":"#334155"}`,background:mil.completed?"#10b98122":"transparent",display:"flex",alignItems:"center",justifyContent:"center",cursor:ce?"pointer":"default",flexShrink:0}}>{mil.completed&&<Ic n="check" s={14} c="#10b981"/>}</div>
          <div style={{flex:1}}><div style={{fontSize:14,fontWeight:600,color:mil.completed?"#64748b":"#e2e8f0",textDecoration:mil.completed?"line-through":"none"}}>{mil.title}</div><div style={{fontSize:12,color:"#475569",marginTop:2}}>{fmt(mil.date)}</div></div>
          <Bdg label={mil.completed?"Feito":"Pendente"} color={mil.completed?"#10b981":"#64748b"} sm/>
          {ce&&<button onClick={async()=>{await db_softDeleteMilestoneDocument(p,mil,user.id);await upd({milestones:(p.milestones||[]).filter(x=>x.id!==mil.id)});}} style={{background:"none",border:"none",cursor:"pointer",padding:4}}><Ic n="trash" s={14} c="#ef4444"/></button>}
        </Card>))}
        {(p.milestones||[]).length===0&&<div style={{textAlign:"center",padding:40,color:"#475569"}}>Nenhum marco.</div>}
      </div>
      {showM&&<Modal title="Novo Marco" onClose={()=>setShowM(false)}><div style={{display:"flex",flexDirection:"column",gap:14}}><Inp label="Título" value={mF.title} onChange={v=>setMF({...mF,title:v})} required/><Inp label="Data" value={mF.date} onChange={v=>setMF({...mF,date:v})} type="date"/><div style={{display:"flex",gap:10,marginTop:8}}><Btn v="ghost" onClick={()=>setShowM(false)} fw>Cancelar</Btn><Btn onClick={addM} icon="plus" fw>Adicionar</Btn></div></div></Modal>}
    </div>)}
    {tab==="notes"&&(<div>
      {ce&&<div style={{marginBottom:14}}><Btn sm icon="plus" onClick={()=>setShowN(true)}>Nova Nota</Btn></div>}
      <div style={{display:"flex",flexDirection:"column",gap:10}}>
        {(p.notes||[]).sort((a,b)=>b.date.localeCompare(a.date)).map(n=>(<Card key={n.id}><div style={{display:"flex",justifyContent:"space-between",marginBottom:8}}><span style={{fontSize:12,color:"#f59e0b",fontWeight:700}}>{n.author}</span><span style={{fontSize:12,color:"#475569"}}>{fmt(n.date)}</span></div><p style={{fontSize:14,color:"#e2e8f0",lineHeight:1.6,margin:0}}>{n.text}</p></Card>))}
        {(p.notes||[]).length===0&&<div style={{textAlign:"center",padding:40,color:"#475569"}}>Nenhuma nota.</div>}
      </div>
      {showN&&<Modal title="Nova Nota" onClose={()=>setShowN(false)}><Inp label="Nota" value={nF.text} onChange={v=>setNF({text:v})} rows={5} placeholder="Escreva sua nota..."/><div style={{display:"flex",gap:10,marginTop:16}}><Btn v="ghost" onClick={()=>setShowN(false)} fw>Cancelar</Btn><Btn onClick={addN} icon="note" fw>Salvar</Btn></div></Modal>}
    </div>)}
    {tab==="team"&&(<div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))",gap:14}}>{(p.team||[]).map(tid=>{const u=users.find(x=>x.id===tid);return u?<Card key={tid} style={{textAlign:"center"}}><div style={{width:52,height:52,borderRadius:"50%",background:"#1e293b",margin:"0 auto 12px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"#94a3b8"}}>{u.avatar}</div><div style={{fontSize:14,fontWeight:700,color:"#f1f5f9"}}>{u.name}</div><div style={{fontSize:12,color:"#64748b",margin:"4px 0 8px"}}>{u.email}</div><Bdg label={roI(u.role).label} color="#6366f1" sm/></Card>:null;})}</div>)}
  </div>);
}

// ── TIMELINE ───────────────────────────────────────────────────────────────────
function Timeline({projects,user}){
  const m=useMobile();
  const myP=Domain.metrics.visibleProjects(projects,user);
  const [selProjs,setSelProjs]=useState(["all"]);
  const [evType,setEvType]=useState("all");

  const toggleProj=id=>{
    if(id==="all"){setSelProjs(["all"]);return;}
    setSelProjs(prev=>{
      const without=prev.filter(x=>x!=="all");
      const next=without.includes(id)?without.filter(x=>x!==id):[...without,id];
      return next.length===0?["all"]:next;
    });
  };

  const filteredP=selProjs.includes("all")?myP:myP.filter(p=>selProjs.includes(p.id));
  const evs=[];
  filteredP.forEach(p=>{
    if((evType==="all"||evType==="start")&&p.startDate)  evs.push({date:p.startDate, label:`🚀 ${p.name} — Início`,color:p.color,type:"start"});
    if((evType==="all"||evType==="target")&&p.targetDate) evs.push({date:p.targetDate,label:`🎯 ${p.name} — Meta`,  color:p.color,type:"target"});
    if(evType==="all"||evType==="milestone")
      (p.milestones||[]).forEach(mil=>evs.push({date:mil.date,label:`${mil.completed?"✅":"🔹"} ${p.name}: ${mil.title}`,color:mil.completed?"#10b981":"#6366f1",type:"milestone"}));
  });
  evs.sort((a,b)=>a.date.localeCompare(b.date));
  const years=[...new Set(evs.map(e=>e.date.split("-")[0]))];

  const FilterPanel=()=>(
    <div style={{display:"flex",flexDirection:"column",gap:14}}>
      {/* Tipo */}
      <div>
        <div style={{fontSize:11,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:.8,marginBottom:8}}>Tipo de Evento</div>
        <div style={{display:"flex",flexDirection:m?"row":"column",gap:6,flexWrap:m?"wrap":"nowrap"}}>
          {[{id:"all",label:"Todos eventos",ic:"🗓️"},{id:"start",label:"Inícios 🚀"},{id:"target",label:"Metas 🎯"},{id:"milestone",label:"Marcos 🔹"}].map(t=>(
            <button key={t.id} onClick={()=>setEvType(t.id)} style={{padding:"7px 12px",borderRadius:8,border:`1px solid ${evType===t.id?"#6366f144":"#1e293b"}`,background:evType===t.id?"#6366f122":"transparent",color:evType===t.id?"#a5b4fc":"#64748b",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left",width:"100%"}}>{t.label}</button>
          ))}
        </div>
      </div>
      {/* Projetos */}
      <div>
        <div style={{fontSize:11,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:.8,marginBottom:8}}>Projetos</div>
        <div style={{display:"flex",flexDirection:m?"row":"column",gap:6,flexWrap:m?"wrap":"nowrap"}}>
          <button onClick={()=>toggleProj("all")} style={{padding:"7px 12px",borderRadius:8,border:`1px solid ${selProjs.includes("all")?"#f59e0b44":"#1e293b"}`,background:selProjs.includes("all")?"#f59e0b22":"transparent",color:selProjs.includes("all")?"#f59e0b":"#64748b",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left",width:"100%"}}>
            Todos os projetos
          </button>
          {myP.map(p=>{
            const active=selProjs.includes(p.id);
            return(
              <button key={p.id} onClick={()=>toggleProj(p.id)} style={{padding:"7px 12px",borderRadius:8,border:`1px solid ${active?p.color+"55":"#1e293b"}`,background:active?p.color+"22":"transparent",color:active?p.color:"#64748b",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left",width:"100%",display:"flex",alignItems:"center",gap:8}}>
                <span style={{flexShrink:0}}>{p.icon}</span>
                <span style={{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{p.name}</span>
                {active&&<span style={{marginLeft:"auto",flexShrink:0,fontSize:10}}>✓</span>}
              </button>
            );
          })}
        </div>
      </div>
      {/* Stats */}
      <div style={{background:"#0a0a14",borderRadius:10,padding:"12px 14px"}}>
        <div style={{fontSize:11,color:"#475569",fontWeight:700,textTransform:"uppercase",letterSpacing:.8,marginBottom:8}}>Resumo</div>
        <div style={{display:"flex",flexDirection:"column",gap:6}}>
          <div style={{display:"flex",justifyContent:"space-between"}}><span style={{fontSize:12,color:"#64748b"}}>Total eventos</span><span style={{fontSize:12,color:"#f59e0b",fontWeight:700}}>{evs.length}</span></div>
          <div style={{display:"flex",justifyContent:"space-between"}}><span style={{fontSize:12,color:"#64748b"}}>Projetos</span><span style={{fontSize:12,color:"#e2e8f0",fontWeight:700}}>{filteredP.length}</span></div>
          <div style={{display:"flex",justifyContent:"space-between"}}><span style={{fontSize:12,color:"#64748b"}}>Anos</span><span style={{fontSize:12,color:"#e2e8f0",fontWeight:700}}>{years.length}</span></div>
        </div>
      </div>
    </div>
  );

  return(
    <div style={{padding:m?"16px":"32px",maxWidth:1300,paddingBottom:m?80:32}}>
      <SH title="Timeline Geral" sub={`${evs.length} evento(s) · ${filteredP.length} projeto(s)`}/>

      {m?(
        // Mobile: filtros em cima, timeline embaixo
        <>
          <Card style={{marginBottom:16,padding:"14px 16px"}}><FilterPanel/></Card>
          <TimelineBody evs={evs} years={years} m={m}/>
        </>
      ):(
        // Desktop: 2 colunas — filtros esquerda, timeline direita
        <div style={{display:"grid",gridTemplateColumns:"240px 1fr",gap:20,alignItems:"start"}}>
          <div style={{position:"sticky",top:80}}>
            <Card style={{padding:"16px"}}><FilterPanel/></Card>
          </div>
          <TimelineBody evs={evs} years={years} m={m}/>
        </div>
      )}
    </div>
  );
}

function TimelineBody({evs,years,m}){
  if(evs.length===0) return <div style={{textAlign:"center",padding:60,color:"#475569",background:"#0f172a",borderRadius:12,border:"1px solid #1e293b"}}>Nenhum evento encontrado.<br/><span style={{fontSize:12,marginTop:4,display:"block"}}>Adicione datas e marcos nos projetos.</span></div>;
  return(
    <div style={{position:"relative",paddingLeft:40}}>
      <div style={{position:"absolute",left:18,top:0,bottom:0,width:2,background:"#1e293b"}}/>
      {years.map(year=>(
        <div key={year}>
          <div style={{display:"flex",alignItems:"center",gap:12,marginBottom:16,marginTop:8,marginLeft:-30}}>
            <div style={{width:36,height:36,borderRadius:"50%",background:"#0f172a",border:"2px solid #f59e0b",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,zIndex:1}}>
              <span style={{fontSize:10,fontWeight:700,color:"#f59e0b",fontFamily:"'Space Mono',monospace"}}>{year}</span>
            </div>
            <span style={{fontSize:12,color:"#334155",fontWeight:600}}>{evs.filter(e=>e.date.startsWith(year)).length} evento(s)</span>
          </div>
          {evs.filter(e=>e.date.startsWith(year)).map((e,i)=>(
            <div key={i} style={{display:"flex",gap:14,alignItems:"flex-start",marginBottom:10,marginLeft:-8}}>
              <div style={{width:20,height:20,borderRadius:"50%",background:e.color+"33",border:`2px solid ${e.color}`,flexShrink:0,marginTop:2,zIndex:1}}/>
              <Card style={{flex:1,padding:"10px 14px"}}>
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8}}>
                  <span style={{fontSize:13,color:"#e2e8f0",lineHeight:1.4}}>{e.label}</span>
                  <span style={{fontSize:11,color:"#475569",fontFamily:"'Space Mono',monospace",flexShrink:0,marginLeft:8}}>{fmt(e.date)}</span>
                </div>
              </Card>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

// ── TASKS ─────────────────────────────────────────────────────────────────────
function Tasks({projects,user,users=[],globalTasks,reloadProjects,reloadGlobalTasks,toast}){
  const m=useMobile();
  const [filterStatus,setFilterStatus]=useState("all");
  const [filterProj,setFilterProj]=useState("all");
  const [filterAssignee,setFilterAssignee]=useState("all");
  const [filterPriority,setFilterPriority]=useState("all");
  const [filterDue,setFilterDue]=useState("all");
  const [viewMode,setViewMode]=useState("list");
  const [modal,setModal]=useState(false);
  const [editId,setEditId]=useState(null);
  const [saving,setSaving]=useState(false);
  const draggingRef=useRef(null); // {id, isGlobal, projId, status}
  const [dragOver,setDragOver]=useState(null); // colId
  const ef={title:"",priority:"Média",status:"todo",projects:[],description:"",dueDate:"",assigneeId:"",checklist:[],comments:[],history:[]};
  const [form,setForm]=useState(ef);
  const [newCheck,setNewCheck]=useState("");
  const [newComment,setNewComment]=useState("");

  const myP=Domain.metrics.visibleProjects(projects,user).slice().sort((a,b)=>{const ar=a.lastAccessedAt||a.updatedAt||a.createdAt||"";const br=b.lastAccessedAt||b.updatedAt||b.createdAt||"";return br.localeCompare(ar)||a.name.localeCompare(b.name);});
  const myPids=new Set(myP.map(p=>p.id));
  const canEdit=user.role==="admin"||user.role==="manager";
  const canMoveGlobalTasks=["admin","manager","member"].includes(user.role);
  const canMoveTask=t=>t.isGlobal?canMoveGlobalTasks:canEdit;
  const canManageTask=t=>t.isGlobal?canEdit:canEdit;

  const taskProjectIds=t=>t.projects||t.projectIds||[];
  const visibleGlobal=globalTasks.filter(t=>user.role==="admin"||taskProjectIds(t).some(pid=>myPids.has(pid)));
  const projectTasks=[];
  myP.forEach(p=>(p.tasks||[]).forEach(t=>projectTasks.push({...t,isProjectTask:true,projectsInfo:[{id:p.id,name:p.name,icon:p.icon,color:p.color}],_projId:p.id})));

  const allTasks=[
    ...visibleGlobal.map(t=>({...t,isGlobal:true,projectsInfo:taskProjectIds(t).map(pid=>myP.find(p=>p.id===pid)).filter(Boolean)})),
    ...projectTasks,
  ];

  const todayStr=now();
  const quickViews=[
    {id:"all",label:"Todas",apply:()=>{setFilterStatus("all");setFilterProj("all");setFilterAssignee("all");setFilterPriority("all");setFilterDue("all");}},
    {id:"mine",label:"Minhas",apply:()=>{setFilterAssignee(user.id);setFilterStatus("all");setFilterDue("all");}},
    {id:"late",label:"Atrasadas",apply:()=>{setFilterDue("late");setFilterStatus("all");}},
    {id:"today",label:"Hoje",apply:()=>{setFilterDue("today");setFilterStatus("all");}},
    {id:"noOwner",label:"Sem responsável",apply:()=>{setFilterAssignee("none");}},
    {id:"noDue",label:"Sem prazo",apply:()=>{setFilterDue("none");}},
    {id:"high",label:"Alta prioridade",apply:()=>{setFilterPriority("Alta");setFilterStatus("all");}},
  ];
  const dueMatches=t=>filterDue==="all"||(filterDue==="none"&&!t.dueDate)||(filterDue==="today"&&t.dueDate===todayStr)||(filterDue==="late"&&t.dueDate&&t.dueDate<todayStr&&t.status!=="done")||(filterDue==="future"&&t.dueDate&&t.dueDate>todayStr);
  const activeFilterCount=[filterStatus!=="all",filterProj!=="all",filterAssignee!=="all",filterPriority!=="all",filterDue!=="all"].filter(Boolean).length;
  const clearTaskFilters=()=>{setFilterStatus("all");setFilterProj("all");setFilterAssignee("all");setFilterPriority("all");setFilterDue("all");};

  // Filtros compartilhados entre lista e Kanban
  const filtered=allTasks.filter(t=>{
    const matchProj=filterProj==="all"||(t.isGlobal?taskProjectIds(t).includes(filterProj):t.projectsInfo?.some(p=>p.id===filterProj));
    const matchAssignee=filterAssignee==="all"||(filterAssignee==="none"?!t.assigneeId:t.assigneeId===filterAssignee);
    const matchPriority=filterPriority==="all"||t.priority===filterPriority;
    return matchProj&&matchAssignee&&matchPriority&&dueMatches(t);
  });
  const filteredByStatus=filtered.filter(t=>filterStatus==="all"||t.status===filterStatus);
  const allProjectIds=myP.map(p=>p.id);
  const memberOptions=[{value:"",label:"Sem responsável"},...users.map(u=>({value:u.id,label:u.name}))];
  const personName=id=>users.find(u=>u.id===id)?.name||"";
  const dueColor=t=>t.dueDate&&t.status!=="done"&&t.dueDate<todayStr?"#ef4444":"#64748b";
  const checklistStats=t=>{const list=t.checklist||[];return {total:list.length,done:list.filter(i=>i.done).length};};
  const addHistory=(base,text)=>[...(base.history||[]),{id:"h"+uid(),text,author:user.name,authorId:user.id,date:new Date().toISOString()}].slice(-30);
  const addChecklistItem=()=>{const text=newCheck.trim();if(!text)return;setForm({...form,checklist:[...(form.checklist||[]),{id:"c"+uid(),text,done:false,createdAt:new Date().toISOString()}]});setNewCheck("");};
  const patchChecklistItem=(id,patch)=>setForm({...form,checklist:(form.checklist||[]).map(i=>i.id===id?{...i,...patch}:i)});
  const removeChecklistItem=id=>setForm({...form,checklist:(form.checklist||[]).filter(i=>i.id!==id)});
  const addTaskComment=()=>{const text=newComment.trim();if(!text)return;setForm({...form,comments:[...(form.comments||[]),{id:"cm"+uid(),text,author:user.name,authorId:user.id,date:new Date().toISOString()}]});setNewComment("");};

  const colTasks=colId=>filtered.filter(t=>(filterStatus==="all"||t.status===colId)&&t.status===colId);

  // ── DRAG & DROP ──
  const onDragStart=(e,t)=>{
    draggingRef.current={id:t.id,isGlobal:!!t.isGlobal,projId:t._projId,status:t.status};
    e.dataTransfer.effectAllowed="move";
    e.dataTransfer.setData("text/plain", t.id);
    e.currentTarget.style.opacity=".5";
  };
  const onDragEnd=e=>{e.currentTarget.style.opacity="1";draggingRef.current=null;setDragOver(null);};
  const onDragOver=(e,colId)=>{e.preventDefault();setDragOver(prev=>prev===colId?prev:colId);};
  const onDrop=async(e,colId)=>{
    e.preventDefault();setDragOver(null);
    const dragging=draggingRef.current;
    if(!dragging||dragging.status===colId)return;
    if(dragging.isGlobal&&!canMoveGlobalTasks)return;
    if(!dragging.isGlobal&&!canEdit)return;
    if(dragging.isGlobal){
      const t=globalTasks.find(x=>x.id===dragging.id);
      if(!t)return;
      const updated=Domain.workspace.withRecord({...t,status:colId,history:addHistory(t,`Status alterado para ${statusLabel(colId)}`),updatedAt:now(),completedAt:colId==="done"?now():null});
      await db_set("globalTasks",t.id,updated);
      await db_saveTaskDocument(updated,{projectIds:updated.projects||updated.projectIds||[],createdBy:updated.createdBy||user.id,sourceType:"global"});
      await db_logActivity({workspaceId:Domain.workspace.idOf(updated),action:"task_moved",entityType:"task",entityId:updated.id,actorId:user.id,actorName:user.name,summary:`Tarefa movida: ${updated.title}`,metadata:{from:t.status,to:colId,projectIds:updated.projects||updated.projectIds||[]}});
      await reloadGlobalTasks();
    } else {
      // tarefa de projeto
      const p=projects.find(x=>x.id===dragging.projId);
      if(!p)return;
      const task=(p.tasks||[]).find(t=>t.id===dragging.id);
      if(!task)return;
      const updatedTask={...task,status:colId,history:addHistory(task,`Status alterado para ${statusLabel(colId)}`),updatedAt:now(),completedAt:colId==="done"?now():null};
      await db_set("projects",p.id,Domain.workspace.withRecord({...p,tasks:(p.tasks||[]).map(t=>t.id===dragging.id?updatedTask:t)}));
      await db_saveTaskDocument(updatedTask,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:user.id,sourceType:"project"});
      await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_moved",entityType:"task",entityId:updatedTask.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa movida: ${updatedTask.title}`,metadata:{from:task.status,to:colId}});
      await reloadProjects();
    }
    draggingRef.current=null;
  };

  const moveTask=async(t,newStatus)=>{
    if(!canMoveTask(t)||t.status===newStatus)return;
    if(t.isGlobal){const updated=Domain.workspace.withRecord({...t,status:newStatus,history:addHistory(t,`Status alterado para ${statusLabel(newStatus)}`),updatedAt:now(),completedAt:newStatus==="done"?now():null});await db_set("globalTasks",t.id,updated);await db_saveTaskDocument(updated,{projectIds:updated.projects||updated.projectIds||[],createdBy:updated.createdBy||user.id,sourceType:"global"});await db_logActivity({workspaceId:Domain.workspace.idOf(updated),action:"task_moved",entityType:"task",entityId:updated.id,actorId:user.id,actorName:user.name,summary:`Tarefa movida: ${updated.title}`,metadata:{from:t.status,to:newStatus,projectIds:updated.projects||updated.projectIds||[]}});await reloadGlobalTasks();return;}
    const p=projects.find(x=>x.id===t._projId);
    if(!p)return;
    const task=(p.tasks||[]).find(x=>x.id===t.id);
    if(!task)return;
    const updatedTask={...task,status:newStatus,history:addHistory(task,`Status alterado para ${statusLabel(newStatus)}`),updatedAt:now(),completedAt:newStatus==="done"?now():null};
    await db_set("projects",p.id,Domain.workspace.withRecord({...p,tasks:(p.tasks||[]).map(x=>x.id===t.id?updatedTask:x)}));
    await db_saveTaskDocument(updatedTask,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:user.id,sourceType:"project"});
    await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_moved",entityType:"task",entityId:updatedTask.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa movida: ${updatedTask.title}`,metadata:{from:task.status,to:newStatus}});
    await reloadProjects();
  };

  const delTask=async id=>{if(!confirm("Excluir tarefa?"))return;const task=globalTasks.find(t=>t.id===id);if(task){await db_softDeleteTaskDocument(task,{projectIds:task.projects||task.projectIds||[],createdBy:task.createdBy||user.id,sourceType:"global"});await db_logActivity({workspaceId:Domain.workspace.idOf(task),action:"task_deleted",entityType:"task",entityId:id,actorId:user.id,actorName:user.name,summary:`Tarefa excluída: ${task.title}`,metadata:{projectIds:task.projects||task.projectIds||[]}});}await db_del("globalTasks",id);await reloadGlobalTasks();toast("Tarefa excluída.","info");};


  const openEditTask=t=>{
    setForm({title:t.title,priority:t.priority||"Média",status:t.status||"todo",projects:t.isGlobal?(t.projects||t.projectIds||[]):[t._projId],description:t.description||"",dueDate:t.dueDate||"",assigneeId:t.assigneeId||t.assignedTo||"",checklist:t.checklist||[],comments:t.comments||[],history:t.history||[]});
    setNewCheck("");setNewComment("");
    setEditId(t.isGlobal?t.id:`project:${t._projId}:${t.id}`);
    setModal(true);
  };
  const deleteAnyTask=async t=>{
    if(t.isGlobal){await delTask(t.id);return;}
    if(!confirm("Excluir tarefa?"))return;
    const p=projects.find(x=>x.id===t._projId);
    if(!p)return;
    const task=(p.tasks||[]).find(x=>x.id===t.id);
    if(task){
      await db_softDeleteTaskDocument(task,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:task.createdBy||user.id,sourceType:"project"});
      await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_deleted",entityType:"task",entityId:t.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa excluída: ${task.title}`});
    }
    await db_set("projects",p.id,Domain.workspace.withRecord({...p,tasks:(p.tasks||[]).filter(x=>x.id!==t.id),updatedAt:now()}));
    await reloadProjects();
    toast("Tarefa excluída.","info");
  };

  const save=async()=>{
    if(!form.title)return;setSaving(true);
    try{
      if(editId&&String(editId).startsWith("project:")){
        const [,projId,taskId]=String(editId).split(":");
        const p=projects.find(x=>x.id===projId);
        const existing=(p?.tasks||[]).find(t=>t.id===taskId);
        if(!p||!existing)throw new Error("Tarefa do projeto não encontrada");
        const updatedTask={...existing,title:form.title,description:form.description||"",priority:form.priority,dueDate:form.dueDate||"",assigneeId:form.assigneeId||"",checklist:form.checklist||[],comments:form.comments||[],history:addHistory(existing,"Tarefa atualizada"),status:form.status,updatedAt:now(),completedAt:form.status==="done"?now():null};
        await db_set("projects",p.id,Domain.workspace.withRecord({...p,tasks:(p.tasks||[]).map(t=>t.id===taskId?updatedTask:t),updatedAt:now()}));
        await db_saveTaskDocument(updatedTask,{projectId:p.id,workspaceId:Domain.workspace.idOf(p),createdBy:updatedTask.createdBy||user.id,sourceType:"project"});
        await db_logActivity({workspaceId:Domain.workspace.idOf(p),action:"task_updated",entityType:"task",entityId:updatedTask.id,projectId:p.id,actorId:user.id,actorName:user.name,summary:`Tarefa atualizada: ${updatedTask.title}`,metadata:{status:updatedTask.status,priority:updatedTask.priority}});
        await reloadProjects();toast("Tarefa atualizada!","success");setModal(false);
      }else if(editId){
        const existing=globalTasks.find(t=>t.id===editId)||{};
        const task=Domain.workspace.withRecord({...existing,...form,id:editId,projectIds:form.projects||[],projects:form.projects||[],history:addHistory(existing,"Tarefa atualizada"),updatedAt:now()});
        await db_set("globalTasks",editId,task);
        await db_saveTaskDocument(task,{projectIds:task.projects||task.projectIds||[],createdBy:task.createdBy||user.id,sourceType:"global"});
        await db_logActivity({workspaceId:Domain.workspace.idOf(task),action:"task_updated",entityType:"task",entityId:task.id,actorId:user.id,actorName:user.name,summary:`Tarefa atualizada: ${task.title}`,metadata:{projectIds:task.projects||task.projectIds||[]}});
        await reloadGlobalTasks();toast("Tarefa atualizada!","success");setModal(false);
      }else{
        const task=Domain.task.create({...form,history:[{id:"h"+uid(),text:"Tarefa criada",author:user.name,authorId:user.id,date:new Date().toISOString()}]},user.id);
        await db_set("globalTasks",task.id,task);
        await db_saveTaskDocument(task,{projectIds:task.projects||task.projectIds||[],createdBy:user.id,sourceType:"global"});
        await db_logActivity({workspaceId:Domain.workspace.idOf(task),action:"task_created",entityType:"task",entityId:task.id,actorId:user.id,actorName:user.name,summary:`Tarefa criada: ${task.title}`,metadata:{projectIds:task.projects||task.projectIds||[]}});
        await reloadGlobalTasks();toast("Tarefa criada!","success");setModal(false);
      }
    }catch(err){toast("Erro: "+err.message,"error");}
    setSaving(false);
  };
  const statusLabel=s=>s==="todo"?"A Fazer":s==="doing"?"Andamento":"Feito";
  const statusColor=s=>s==="done"?"#10b981":s==="doing"?"#6366f1":"#64748b";
  const selectedProjectCount=(form.projects||[]).length;
  const allProjectsSelected=allProjectIds.length>0&&selectedProjectCount===allProjectIds.length;
  const editingProjectTask=String(editId||"").startsWith("project:");

  return(<div style={{padding:m?"16px":"32px",maxWidth:1400,paddingBottom:m?80:32}}>
    <SH title="Tarefas" sub={`${filteredByStatus.length} tarefa(s)`}
      action={canEdit&&<Btn icon="plus" sm onClick={()=>{setForm(ef);setEditId(null);setNewCheck("");setNewComment("");setModal(true);}}>Nova Tarefa</Btn>}/>

    <div style={{background:"#6366f111",border:"1px solid #6366f133",borderRadius:10,padding:"10px 14px",marginBottom:16,fontSize:13,color:"#a5b4fc",display:"flex",gap:8,alignItems:"center"}}>
      <span>💡</span>
      <span><strong>Lista</strong> e <strong>Kanban</strong> usam os mesmos dados. Na lista, altere o status pelo seletor; no Kanban, use as setas ou arraste.</span>
    </div>

    {/* Filtros */}
    <div style={{display:"flex",flexDirection:"column",gap:10,marginBottom:20}}>
      <div style={{display:"flex",gap:8,overflowX:"auto",paddingBottom:4}}>
        {quickViews.map(v=><button key={v.id} onClick={v.apply} style={{padding:"7px 12px",borderRadius:20,border:"1px solid #1e293b",background:"#0f172a",color:"#a5b4fc",cursor:"pointer",fontSize:12,fontWeight:800,whiteSpace:"nowrap",flexShrink:0}}>{v.label}</button>)}
        {activeFilterCount>0&&<button onClick={clearTaskFilters} style={{padding:"7px 12px",borderRadius:20,border:"1px solid #ef444433",background:"#ef444411",color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:800,whiteSpace:"nowrap",flexShrink:0}}>Limpar ({activeFilterCount})</button>}
      </div>
      <div style={{display:"grid",gridTemplateColumns:m?"1fr 1fr":"repeat(5,minmax(140px,1fr))",gap:8}}>
        <select value={filterStatus} onChange={e=>setFilterStatus(e.target.value)} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"9px 10px",fontSize:12,fontWeight:700,outline:"none"}}>
          {[{id:"all",label:"Todos status"},{id:"todo",label:"A Fazer"},{id:"doing",label:"Andamento"},{id:"done",label:"Concluído"}].map(s=><option key={s.id} value={s.id}>{s.label}</option>)}
        </select>
        <select value={filterProj} onChange={e=>setFilterProj(e.target.value)} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"9px 10px",fontSize:12,fontWeight:700,outline:"none"}}>
          <option value="all">Todos projetos</option>{myP.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}
        </select>
        <select value={filterAssignee} onChange={e=>setFilterAssignee(e.target.value)} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"9px 10px",fontSize:12,fontWeight:700,outline:"none"}}>
          <option value="all">Todos responsáveis</option><option value="none">Sem responsável</option>{users.map(u=><option key={u.id} value={u.id}>{u.name}</option>)}
        </select>
        <select value={filterPriority} onChange={e=>setFilterPriority(e.target.value)} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"9px 10px",fontSize:12,fontWeight:700,outline:"none"}}>
          <option value="all">Todas prioridades</option>{["Baixa","Média","Alta","Crítica"].map(p=><option key={p} value={p}>{p}</option>)}
        </select>
        <select value={filterDue} onChange={e=>setFilterDue(e.target.value)} style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"9px 10px",fontSize:12,fontWeight:700,outline:"none"}}>
          <option value="all">Todos prazos</option><option value="late">Atrasadas</option><option value="today">Hoje</option><option value="future">Futuras</option><option value="none">Sem prazo</option>
        </select>
      </div>
      <div style={{display:"flex",justifyContent:m?"flex-start":"flex-end",gap:6,paddingTop:2}}>{[{id:"list",label:"Lista"},{id:"kanban",label:"Kanban"}].map(v=><button key={v.id} onClick={()=>setViewMode(v.id)} style={{padding:"7px 12px",borderRadius:8,border:`1px solid ${viewMode===v.id?"#f59e0b44":"#1e293b"}`,background:viewMode===v.id?"#f59e0b22":"#0f172a",color:viewMode===v.id?"#f59e0b":"#64748b",cursor:"pointer",fontSize:12,fontWeight:700}}>{v.label}</button>)}</div>
    </div>
    {/* Visualizacao */}
    {viewMode==="list"&&(
      <div style={{display:"flex",flexDirection:"column",gap:8}}>
        {!m&&<div style={{display:"grid",gridTemplateColumns:"minmax(0,1.5fr) 170px 150px 130px",gap:12,padding:"0 14px 6px",fontSize:11,color:"#475569",fontWeight:800,textTransform:"uppercase",letterSpacing:.7}}>
          <span>Tarefa</span><span>Projetos</span><span>Status</span><span style={{textAlign:"right"}}>Acoes</span>
        </div>}
        {filteredByStatus.map((t,i)=>{
          const linked=t.projectsInfo||[];
          return(<Card key={t.id||i} style={{display:"grid",gridTemplateColumns:m?"1fr":"minmax(0,1.5fr) 170px 150px 130px",gap:m?10:12,alignItems:"center",padding:m?14:"12px 14px"}}>
            <div style={{minWidth:0}}>
              <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:t.description?4:0}}>
                {t.isGlobal&&<span style={{fontSize:10,color:"#6366f1",fontWeight:800,textTransform:"uppercase",letterSpacing:.6,border:"1px solid #6366f133",background:"#6366f111",borderRadius:99,padding:"2px 7px",flexShrink:0}}>{linked.length===0?"Avulsa":linked.length>1?"Compartilhada":"Vinculada"}</span>}
                <span style={{fontSize:13,color:"#e2e8f0",fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{t.title}</span>
              </div>
              {t.description&&<div style={{fontSize:12,color:"#64748b",lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}}>{t.description}</div>}
              {(t.dueDate||t.assigneeId)&&<div style={{display:"flex",gap:8,flexWrap:"wrap",marginTop:7,fontSize:11,color:"#64748b"}}>{t.dueDate&&<span style={{color:dueColor(t),fontWeight:700}}>Prazo: {fmt(t.dueDate)}</span>}{t.assigneeId&&<span>Resp.: {personName(t.assigneeId)||"-"}</span>}</div>}
              {checklistStats(t).total>0&&<div style={{fontSize:11,color:"#10b981",fontWeight:700,marginTop:5}}>Checklist: {checklistStats(t).done}/{checklistStats(t).total}</div>}
              {m&&<div style={{display:"flex",gap:6,flexWrap:"wrap",marginTop:8}}>{linked.length>0?linked.map(p=><Bdg key={p.id} label={`${p.icon} ${p.name}`} color={p.color} sm/>):<Bdg label="Sem projeto" color="#475569" sm/>}<Bdg label={t.priority} color={PC[t.priority]} sm/></div>}
            </div>
            {!m&&<div style={{display:"flex",gap:4,flexWrap:"wrap",minWidth:0}}>{linked.length>0?linked.slice(0,2).map(p=><span key={p.id} style={{fontSize:10,background:p.color+"22",color:p.color,border:`1px solid ${p.color}44`,borderRadius:99,padding:"2px 7px",maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{p.icon} {p.name}</span>):<Bdg label="Sem projeto" color="#475569" sm/>}{linked.length>2&&<Bdg label={`+${linked.length-2}`} color="#64748b" sm/>}</div>}
            <div style={{display:"flex",gap:8,alignItems:"center"}}>
              {!m&&<Bdg label={t.priority} color={PC[t.priority]} sm/>}
              <select value={t.status} disabled={!canMoveTask(t)} onChange={e=>moveTask(t,e.target.value)} style={{background:"#0a0a14",border:"1px solid #1e293b",borderRadius:8,color:canMoveTask(t)?"#e2e8f0":"#64748b",padding:"8px 10px",fontSize:12,fontWeight:700,width:m?"100%":120,outline:"none",cursor:canMoveTask(t)?"pointer":"not-allowed"}}>
                {TCOLS.map(c=><option key={c.id} value={c.id}>{c.label}</option>)}
              </select>
            </div>
            <div style={{display:"flex",gap:6,justifyContent:m?"flex-start":"flex-end",alignItems:"center"}}>
              {canMoveTask(t)&&TCOLS.findIndex(c=>c.id===t.status)>0&&<button title="Voltar status" onClick={()=>moveTask(t,TCOLS[TCOLS.findIndex(c=>c.id===t.status)-1].id)} style={{width:30,height:30,background:"#0a0a14",border:"1px solid #1e293b",borderRadius:6,cursor:"pointer",color:"#64748b",fontSize:17,padding:0,lineHeight:1}}>‹</button>}
              {canMoveTask(t)&&TCOLS.findIndex(c=>c.id===t.status)<TCOLS.length-1&&<button title="Avancar status" onClick={()=>moveTask(t,TCOLS[TCOLS.findIndex(c=>c.id===t.status)+1].id)} style={{width:30,height:30,background:"#0a0a14",border:"1px solid #1e293b",borderRadius:6,cursor:"pointer",color:"#64748b",fontSize:17,padding:0,lineHeight:1}}>›</button>}
              {canManageTask(t)&&<button title="Editar tarefa" onClick={()=>openEditTask(t)} style={{width:30,height:30,background:"#0a0a14",border:"1px solid #1e293b",borderRadius:6,cursor:"pointer",padding:0}}><Ic n="edit" s={13} c="#64748b"/></button>}
              {canManageTask(t)&&<button title="Excluir tarefa" onClick={()=>deleteAnyTask(t)} style={{width:32,height:30,background:"#ef444411",border:"1px solid #ef444433",borderRadius:6,cursor:"pointer",padding:0}}><Ic n="trash" s={13} c="#ef4444"/></button>}
            </div>
          </Card>);
        })}
        {filteredByStatus.length===0&&<div style={{textAlign:"center",padding:50,color:"#475569"}}>Nenhuma tarefa encontrada.</div>}
      </div>
    )}

    {viewMode==="kanban"&&<div style={{display:"grid",gridTemplateColumns:m?"1fr":"repeat(3,1fr)",gap:16}}>
      {TCOLS.map(col=>{
        const tasks=colTasks(col.id);
        const isOver=dragOver===col.id;
        return(
          <div key={col.id}
            onDragOver={e=>onDragOver(e,col.id)}
            onDrop={e=>onDrop(e,col.id)}
            style={{background:isOver?"#f59e0b08":"#0a0a14",borderRadius:12,padding:14,border:`2px solid ${isOver?"#f59e0b44":"transparent"}`,transition:"all .15s",minHeight:200}}>
            <div style={{fontSize:12,fontWeight:700,color:"#64748b",textTransform:"uppercase",letterSpacing:1,marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <span>{col.label}</span>
              <span style={{fontWeight:400,background:"#1e293b",borderRadius:99,padding:"2px 8px",fontSize:11}}>{tasks.length}</span>
            </div>
            <div style={{display:"flex",flexDirection:"column",gap:8}}>
              {tasks.map((t,i)=>(
                <div key={t.id||i}
                  draggable={canMoveTask(t)}
                  onDragStart={e=>onDragStart(e,t)}
                  onDragEnd={onDragEnd}
                  style={{background:"#0f172a",border:`1px solid ${t.isGlobal?"#6366f133":"#1e293b"}`,borderRadius:8,padding:12,cursor:canMoveTask(t)?"grab":"default",userSelect:"none",transition:"box-shadow .15s"}}
                  onMouseEnter={e=>e.currentTarget.style.boxShadow="0 2px 12px #00000044"}
                  onMouseLeave={e=>e.currentTarget.style.boxShadow="none"}>
                  {t.isGlobal&&<div style={{fontSize:10,color:"#6366f1",fontWeight:600,textTransform:"uppercase",letterSpacing:.6,marginBottom:4}}>Vinculada</div>}
                  <div style={{fontSize:13,color:"#e2e8f0",fontWeight:600,marginBottom:t.description?6:8,lineHeight:1.4}}>{t.title}</div>
                  {t.description&&<div style={{fontSize:12,color:"#475569",marginBottom:8,lineHeight:1.4}}>{t.description}</div>}
                  {(t.dueDate||t.assigneeId)&&<div style={{display:"flex",gap:8,flexWrap:"wrap",marginBottom:8,fontSize:11,color:"#64748b"}}>{t.dueDate&&<span style={{color:dueColor(t),fontWeight:700}}>Prazo: {fmt(t.dueDate)}</span>}{t.assigneeId&&<span>Resp.: {personName(t.assigneeId)||"-"}</span>}</div>}
                  {checklistStats(t).total>0&&<div style={{fontSize:11,color:"#10b981",fontWeight:700,marginBottom:8}}>Checklist: {checklistStats(t).done}/{checklistStats(t).total}</div>}
                  {t.projectsInfo?.length>0&&(
                    <div style={{display:"flex",gap:4,flexWrap:"wrap",marginBottom:8}}>
                      {t.projectsInfo.map(p=><span key={p.id} style={{fontSize:10,background:p.color+"22",color:p.color,border:`1px solid ${p.color}44`,borderRadius:99,padding:"1px 6px"}}>{p.icon} {m?"":(p.name.length>10?p.name.slice(0,10)+"...":p.name)}</span>)}
                    </div>
                  )}
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                    <Bdg label={t.priority} color={PC[t.priority]} sm/>
                    <div style={{display:"flex",gap:8,alignItems:"center"}}>
                      {canMoveTask(t)&&<div style={{display:"flex",gap:6,alignItems:"center",paddingRight:t.isGlobal&&canEdit?8:0,borderRight:t.isGlobal&&canEdit?"1px solid #1e293b":"none"}}>
                        {TCOLS.findIndex(c=>c.id===col.id)>0&&(
                          <button title="Voltar status" onClick={()=>moveTask(t,TCOLS[TCOLS.findIndex(c=>c.id===col.id)-1].id)} style={{width:26,height:26,background:"#0a0a14",border:"1px solid #1e293b",borderRadius:6,cursor:"pointer",color:"#64748b",fontSize:17,padding:0,lineHeight:1,display:"flex",alignItems:"center",justifyContent:"center"}}>‹</button>
                        )}
                        {TCOLS.findIndex(c=>c.id===col.id)<TCOLS.length-1&&(
                          <button title="Avancar status" onClick={()=>moveTask(t,TCOLS[TCOLS.findIndex(c=>c.id===col.id)+1].id)} style={{width:26,height:26,background:"#0a0a14",border:"1px solid #1e293b",borderRadius:6,cursor:"pointer",color:"#64748b",fontSize:17,padding:0,lineHeight:1,display:"flex",alignItems:"center",justifyContent:"center"}}>›</button>
                        )}
                      </div>}
                      {canManageTask(t)&&<div style={{display:"flex",gap:6,alignItems:"center",marginLeft:2}}>
                        <button title="Editar tarefa" onClick={()=>openEditTask(t)} style={{width:26,height:26,background:"#0a0a14",border:"1px solid #1e293b",borderRadius:6,cursor:"pointer",color:"#64748b",padding:0,display:"flex",alignItems:"center",justifyContent:"center"}}><Ic n="edit" s={12} c="#64748b"/></button>
                        <button title="Excluir tarefa" onClick={()=>deleteAnyTask(t)} style={{width:28,height:26,background:"#ef444411",border:"1px solid #ef444433",borderRadius:6,cursor:"pointer",color:"#ef4444",padding:0,display:"flex",alignItems:"center",justifyContent:"center"}}><Ic n="trash" s={12} c="#ef4444"/></button>
                      </div>}
                    </div>
                  </div>
                </div>
              ))}
              {tasks.length===0&&!isOver&&<div style={{textAlign:"center",padding:"24px 20px",color:"#1e293b",fontSize:12,border:"1px dashed #1e293b",borderRadius:8}}>Vazio</div>}
            </div>
          </div>
        );
      })}
    </div>}
    {modal&&<Modal title={editId?"Editar Tarefa":"Nova Tarefa"} onClose={()=>setModal(false)} wide>
      <div style={{display:"flex",flexDirection:"column",gap:16}}>
        <div style={{fontSize:11,color:"#64748b",fontWeight:800,textTransform:"uppercase",letterSpacing:.8}}>O que é</div>
        <Inp label="Título" value={form.title} onChange={v=>setForm({...form,title:v})} required placeholder="Ex: Configurar Google Analytics"/>
        <Inp label="Descrição (opcional)" value={form.description} onChange={v=>setForm({...form,description:v})} rows={2} placeholder="Detalhes da tarefa..."/>
        <div style={{fontSize:11,color:"#64748b",fontWeight:800,textTransform:"uppercase",letterSpacing:.8,marginTop:2}}>Andamento</div>
        <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:12}}>
          <Inp label="Status" value={form.status} onChange={v=>setForm({...form,status:v})} options={TCOLS.map(c=>({value:c.id,label:c.label}))}/>
          <Inp label="Prioridade" value={form.priority} onChange={v=>setForm({...form,priority:v})} options={["Baixa","Média","Alta","Crítica"]}/>
        </div>
        <div style={{display:"grid",gridTemplateColumns:m?"1fr":"1fr 1fr",gap:12}}>
          <Inp label="Prazo" value={form.dueDate||""} onChange={v=>setForm({...form,dueDate:v})} type="date"/>
          <Inp label="Responsável" value={form.assigneeId||""} onChange={v=>setForm({...form,assigneeId:v})} options={memberOptions}/>
        </div>
        <div style={{fontSize:11,color:"#64748b",fontWeight:800,textTransform:"uppercase",letterSpacing:.8,marginTop:2}}>Checklist</div>
        <div style={{display:"flex",gap:8,alignItems:"center"}}>
          <input value={newCheck} onChange={e=>setNewCheck(e.target.value)} onKeyDown={e=>{if(e.key==="Enter"){e.preventDefault();addChecklistItem();}}} placeholder="Adicionar item..." style={{background:"#0f172a",border:"1px solid #1e293b",borderRadius:8,color:"#e2e8f0",padding:"10px 12px",fontSize:14,width:"100%",outline:"none",minHeight:40}}/>
          <button onClick={addChecklistItem} style={{height:40,padding:"0 12px",borderRadius:8,border:"1px solid #1e293b",background:"#0a0a14",color:"#f59e0b",cursor:"pointer",fontWeight:800}}>+</button>
        </div>
        {(form.checklist||[]).length>0&&<div style={{display:"flex",flexDirection:"column",gap:6}}>{(form.checklist||[]).map(item=><div key={item.id} style={{display:"grid",gridTemplateColumns:"auto minmax(0,1fr) auto",gap:8,alignItems:"center",background:"#0a0a14",border:"1px solid #1e293b",borderRadius:8,padding:"8px 10px"}}><input type="checkbox" checked={!!item.done} onChange={e=>patchChecklistItem(item.id,{done:e.target.checked})}/><input value={item.text} onChange={e=>patchChecklistItem(item.id,{text:e.target.value})} style={{background:"transparent",border:"none",outline:"none",color:item.done?"#64748b":"#e2e8f0",textDecoration:item.done?"line-through":"none",fontSize:13}}/><button onClick={()=>removeChecklistItem(item.id)} style={{background:"none",border:"none",color:"#ef4444",cursor:"pointer",fontSize:16,lineHeight:1}}>×</button></div>)}</div>}
        <div style={{fontSize:11,color:"#64748b",fontWeight:800,textTransform:"uppercase",letterSpacing:.8,marginTop:2}}>Comentários</div>
        <Inp value={newComment} onChange={setNewComment} rows={2} placeholder="Adicionar comentário..."/>
        <div style={{display:"flex",justifyContent:"flex-end"}}><button onClick={addTaskComment} style={{padding:"7px 12px",borderRadius:8,border:"1px solid #1e293b",background:"#0a0a14",color:"#f59e0b",cursor:"pointer",fontSize:12,fontWeight:800}}>Adicionar comentário</button></div>
        {(form.comments||[]).length>0&&<div style={{display:"flex",flexDirection:"column",gap:8,maxHeight:180,overflowY:"auto"}}>{(form.comments||[]).slice().reverse().map(c=><div key={c.id} style={{background:"#0a0a14",border:"1px solid #1e293b",borderRadius:8,padding:"9px 10px"}}><div style={{fontSize:12,color:"#e2e8f0",lineHeight:1.45}}>{c.text}</div><div style={{fontSize:11,color:"#64748b",marginTop:5}}>{c.author||"Usuário"} · {c.date?new Date(c.date).toLocaleString("pt-BR"):""}</div></div>)}</div>}
        {(form.history||[]).length>0&&<><div style={{fontSize:11,color:"#64748b",fontWeight:800,textTransform:"uppercase",letterSpacing:.8,marginTop:2}}>Histórico</div><div style={{display:"flex",flexDirection:"column",gap:5,maxHeight:120,overflowY:"auto"}}>{(form.history||[]).slice().reverse().map(h=><div key={h.id} style={{fontSize:12,color:"#64748b"}}>{h.text} · {h.author||"Usuário"} · {h.date?new Date(h.date).toLocaleString("pt-BR"):""}</div>)}</div></>}
        <div style={{fontSize:11,color:"#64748b",fontWeight:800,textTransform:"uppercase",letterSpacing:.8,marginTop:2}}>Onde entra</div>
        {editingProjectTask&&<div style={{background:"#0a0a14",border:"1px solid #1e293b",borderRadius:8,padding:"10px 12px",fontSize:12,color:"#64748b"}}>Tarefa interna de projeto. O vínculo atual será mantido.</div>}
        <div style={{display:editingProjectTask?"none":"block"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:m?"flex-start":"center",gap:10,marginBottom:8,flexDirection:m?"column":"row"}}>
            <label style={{fontSize:12,color:"#64748b",fontWeight:600,textTransform:"uppercase",letterSpacing:.8}}>Aplicar em</label>
            <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
              <button onClick={()=>setForm({...form,projects:[]})} style={{padding:"6px 10px",borderRadius:8,border:`1px solid ${selectedProjectCount===0?"#f59e0b44":"#1e293b"}`,background:selectedProjectCount===0?"#f59e0b22":"#0a0a14",color:selectedProjectCount===0?"#f59e0b":"#64748b",cursor:"pointer",fontSize:12,fontWeight:700}}>Sem projeto</button>
              <button onClick={()=>setForm({...form,projects:allProjectIds})} style={{padding:"6px 10px",borderRadius:8,border:`1px solid ${allProjectsSelected?"#10b98144":"#1e293b"}`,background:allProjectsSelected?"#10b98122":"#0a0a14",color:allProjectsSelected?"#10b981":"#64748b",cursor:"pointer",fontSize:12,fontWeight:700}}>Todos</button>
            </div>
          </div>
          <div style={{fontSize:12,color:"#64748b",marginBottom:8}}>{selectedProjectCount===0?"Tarefa avulsa":allProjectsSelected?"Todos os projetos":`${selectedProjectCount} projeto(s) selecionado(s)`}</div>
          <div style={{display:"flex",flexDirection:"column",gap:6,maxHeight:m?260:320,overflowY:"auto",paddingRight:2}}>
            {myP.map(p=>{
              const linked=(form.projects||[]).includes(p.id);
              return(<div key={p.id} onClick={()=>setForm({...form,projects:linked?(form.projects||[]).filter(id=>id!==p.id):[...(form.projects||[]),p.id]})} style={{display:"flex",gap:10,alignItems:"center",padding:"8px 12px",borderRadius:8,border:`1px solid ${linked?p.color+"55":"#1e293b"}`,background:linked?p.color+"11":"#0a0a14",cursor:"pointer",transition:"all .15s"}}>
                <div style={{width:18,height:18,borderRadius:4,border:`2px solid ${linked?p.color:"#334155"}`,background:linked?p.color:"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
                  {linked&&<Ic n="check" s={10} c="#0f0f17"/>}
                </div>
                <span style={{fontSize:18,flexShrink:0}}>{p.icon}</span>
                <span style={{fontSize:13,fontWeight:600,color:"#e2e8f0",flex:1}}>{p.name}</span>
                <Bdg label={p.category} color="#475569" sm/>
              </div>);
            })}
          </div>
          {(form.projects||[]).length===0&&<div style={{fontSize:12,color:"#475569",marginTop:6}}>Sem vínculo: tarefa ficará avulsa.</div>}
        </div>
        <div style={{display:"flex",gap:10,marginTop:8}}>
          <Btn v="ghost" onClick={()=>setModal(false)} fw>Cancelar</Btn>
          <Btn onClick={save} loading={saving} icon="check" fw>{editId?"Salvar":"Criar Tarefa"}</Btn>
        </div>
      </div>
    </Modal>}
  </div>);
}
// ── FINANCES ───────────────────────────────────────────────────────────────────
function Finances({projects,user,reloadProjects,toast}){
  const m=useMobile();const [editId,setEditId]=useState(null);const [form,setForm]=useState({revenue:0,target:0,model:""});const [saving,setSaving]=useState(false);
  const myP=Domain.metrics.visibleProjects(projects,user);
  const rev=myP.reduce((a,p)=>a+(p.monetization?.revenue||0),0);const tar=myP.reduce((a,p)=>a+(p.monetization?.target||0),0);
  const save=async id=>{setSaving(true);const p=projects.find(x=>x.id===id);const updated=Domain.workspace.withRecord({...p,monetization:{...p.monetization,...form},updatedAt:now()});await db_set("projects",id,updated);await db_saveFinanceEntry(updated,user.id);await db_logActivity({workspaceId:Domain.workspace.idOf(updated),action:"revenue_changed",entityType:"financeEntry",entityId:`${id}_current`,projectId:id,actorId:user.id,actorName:user.name,summary:`Receita atualizada: ${updated.name}`,metadata:{previous:p.monetization||{},current:updated.monetization||{}}});await reloadProjects();setEditId(null);setSaving(false);toast("Receita atualizada!","success");};
  return(<div style={{padding:m?"16px":"28px",maxWidth:1440,paddingBottom:m?80:28}}>
    <SH title="Financeiro" sub="Receita e metas de monetização"/>
    <div style={{display:"flex",gap:12,marginBottom:24,flexWrap:"wrap"}}>{[{label:"Receita Total",v:`R$ ${rev.toLocaleString("pt-BR")}`,c:"#10b981"},{label:"Meta Total",v:`R$ ${tar.toLocaleString("pt-BR")}`,c:"#6366f1"},{label:"% da Meta",v:`${tar>0?((rev/tar)*100).toFixed(1):0}%`,c:"#f59e0b"}].map(s=>(<Card key={s.label} style={{flex:"1 1 160px",textAlign:"center"}}><div style={{fontSize:22,fontWeight:800,color:s.c,fontFamily:"'Space Mono',monospace"}}>{s.v}</div><div style={{fontSize:12,color:"#64748b",marginTop:4}}>{s.label}</div></Card>))}</div>
    <div style={{display:"flex",flexDirection:"column",gap:10}}>{myP.map(p=>(<Card key={p.id}><div style={{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"}}><span style={{fontSize:24,flexShrink:0}}>{p.icon}</span><div style={{flex:1,minWidth:120}}><div style={{fontSize:14,fontWeight:700,color:"#f1f5f9"}}>{p.name}</div><div style={{fontSize:12,color:"#64748b",marginTop:2}}>{p.monetization?.model||"Sem modelo"}</div></div>
      {editId===p.id?(<div style={{display:"flex",flexDirection:"column",gap:10,width:"100%",marginTop:10}}><Inp sm label="Modelo" value={form.model} onChange={v=>setForm({...form,model:v})}/><Inp sm label="Receita (R$)" value={form.revenue} onChange={v=>setForm({...form,revenue:+v})} type="number"/><Inp sm label="Meta (R$)" value={form.target} onChange={v=>setForm({...form,target:+v})} type="number"/><div style={{display:"flex",gap:8}}><Btn sm onClick={()=>save(p.id)} loading={saving} icon="check" fw>Salvar</Btn><Btn sm v="ghost" onClick={()=>setEditId(null)} fw>Cancelar</Btn></div></div>):(
        <div style={{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"}}><div style={{textAlign:"right"}}><div style={{fontSize:16,fontWeight:800,color:"#10b981",fontFamily:"'Space Mono',monospace"}}>R$ {(p.monetization?.revenue||0).toLocaleString("pt-BR")}</div><div style={{fontSize:11,color:"#475569"}}>/ R$ {(p.monetization?.target||0).toLocaleString("pt-BR")}</div></div><div style={{width:80}}><PBar value={p.monetization?.target>0?Math.min(100,(p.monetization.revenue/p.monetization.target)*100):0} color="#10b981" h={5}/></div>{(user.role==="admin"||user.role==="manager")&&<Btn sm v="ghost" icon="edit" onClick={()=>{setEditId(p.id);setForm({revenue:p.monetization?.revenue||0,target:p.monetization?.target||0,model:p.monetization?.model||""});}}>Editar</Btn>}</div>
      )}
    </div></Card>))}</div>
  </div>);
}

// ── ADMIN PANEL ────────────────────────────────────────────────────────────────
function AdminPanel({users,projects,reloadUsers,reloadProjects,cats,setCats,cu,toast}){
  const m=useMobile();const [tab,setTab]=useState("users");
  const [uModal,setUModal]=useState(false);const [uEdit,setUEdit]=useState(null);const [uForm,setUForm]=useState({name:"",email:"",password:"",role:"member",active:true,phone:""});const [saving,setSaving]=useState(false);
  const [cModal,setCModal]=useState(false);const [cEdit,setCEdit]=useState(null);const [cForm,setCForm]=useState("");
  const [lModal,setLModal]=useState(false);const [lUser,setLUser]=useState(null);

  const saveUser=async()=>{
    if(!uForm.name||!uForm.email)return;
    setSaving(true);
    try{
      const av=avt(uForm.name);
      if(uEdit){
        // Update Firestore user doc
        await db_set("users",uEdit,Domain.workspace.withRecord({...uForm,avatar:av,updatedAt:now(),...(!uForm.password?{password:undefined}:{})}));
        await db_logActivity({workspaceId:Domain.workspace.defaultId,action:"user_updated",entityType:"user",entityId:uEdit,actorId:cu.id,actorName:cu.name,summary:`Usuário atualizado: ${uForm.name}`,metadata:{role:uForm.role,active:uForm.active}});
        // Update password in Firebase Auth if provided
        if(uForm.password){
          // Note: updating another user's password requires Admin SDK; we store it for reference
          toast("Usuário atualizado! Senha só pode ser alterada pelo próprio usuário em Configurações.","warn");
        }else{ toast("Usuário atualizado!","success"); }
      }else{
        // Create Firebase Auth user
        const { auth, createUserWithEmailAndPassword } = FB();
        const cred = await createUserWithEmailAndPassword(auth, uForm.email, uForm.password||"senha123");
        await db_set("users", cred.user.uid, Domain.workspace.withRecord({name:uForm.name,email:uForm.email,role:uForm.role,active:uForm.active,phone:uForm.phone||"",avatar:av,createdAt:now()}));
        await db_logActivity({workspaceId:Domain.workspace.defaultId,action:"user_created",entityType:"user",entityId:cred.user.uid,actorId:cu.id,actorName:cu.name,summary:`Usuário criado: ${uForm.name}`,metadata:{role:uForm.role,active:uForm.active}});
        toast(`Usuário criado! Senha provisória: ${uForm.password||"senha123"}`,"success");
      }
      await reloadUsers();setUModal(false);
    }catch(e){ toast("Erro: "+e.message,"error"); }
    setSaving(false);
  };

  const toggleActive=async id=>{if(id===cu.id)return;const u=users.find(x=>x.id===id);await db_set("users",id,Domain.workspace.withRecord({...u,active:!u.active}));await db_logActivity({workspaceId:Domain.workspace.idOf(u),action:u.active?"user_deactivated":"user_activated",entityType:"user",entityId:id,actorId:cu.id,actorName:cu.name,summary:u.active?`Usuário desativado: ${u.name}`:`Usuário ativado: ${u.name}`});await reloadUsers();toast(u.active?"Usuário desativado.":"Usuário ativado.","info");};
  const delUser=async id=>{if(id===cu.id||!confirm("Excluir usuário?"))return;await db_del("users",id);await reloadUsers();toast("Usuário excluído.","info");};

  const saveCat=()=>{
    if(!cForm.trim())return;
    let upd;
    if(cEdit!==null)upd=cats.map((c,i)=>i===cEdit?cForm.trim():c);
    else{if(cats.includes(cForm.trim())){toast("Categoria já existe.","warn");return;}upd=[...cats,cForm.trim()];}
    db_set("config","categories",Domain.workspace.withRecord({list:upd,schemaVersion:Domain.schema.version}));setCats(upd);setCModal(false);setCForm("");setCEdit(null);toast("Categoria salva!","success");
  };
  const delCat=i=>{const cat=cats[i];if(!confirm(`Excluir categoria "${cat}"?`))return;const upd=cats.filter((_,j)=>j!==i);db_set("config","categories",Domain.workspace.withRecord({list:upd,schemaVersion:Domain.schema.version}));setCats(upd);toast("Categoria removida.","info");};

  const getLinked=uid=>projects.filter(p=>(p.team||[]).includes(uid));
  const toggleLink=async(userId,projectId)=>{
    const p=projects.find(x=>x.id===projectId);const has=(p.team||[]).includes(userId);
    const updated=Domain.workspace.withRecord({...p,team:has?(p.team||[]).filter(id=>id!==userId):[...(p.team||[]),userId]});
    await db_set("projects",projectId,updated);
    await db_saveProjectMember(updated,userId,cu.id,!has);
    await db_logActivity({workspaceId:Domain.workspace.idOf(updated),action:has?"membership_removed":"membership_added",entityType:"projectMember",entityId:Domain.membership.id(projectId,userId),projectId,actorId:cu.id,actorName:cu.name,summary:has?`Vínculo removido: ${updated.name}`:`Vínculo adicionado: ${updated.name}`,metadata:{userId}});
    await reloadProjects();
  };

  const ATABS=[{id:"users",label:"👥 Usuários"},{id:"roles",label:"🛡️ Perfis"},{id:"projects",label:"🔗 Vínculos"},{id:"cats",label:"🏷️ Categorias"},{id:"overview",label:"📊 Visão Geral"}];

  return(<div style={{padding:m?"16px":"28px",maxWidth:1200,paddingBottom:m?80:28}}>
    <SH title="Painel Administrativo" sub="Usuários, perfis, categorias e vínculos"/>
    <div style={{display:"flex",gap:0,borderBottom:"1px solid #1e293b",marginBottom:24,overflowX:"auto"}}>{ATABS.map(t=><button key={t.id} onClick={()=>setTab(t.id)} style={{padding:"10px 16px",border:"none",background:"none",color:tab===t.id?"#f59e0b":"#64748b",borderBottom:`2px solid ${tab===t.id?"#f59e0b":"transparent"}`,cursor:"pointer",fontSize:m?12:13,fontWeight:600,whiteSpace:"nowrap"}}>{t.label}</button>)}</div>

    {tab==="users"&&(<div>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}><span style={{color:"#64748b",fontSize:14}}>{users.length} usuário(s)</span><Btn icon="plus" sm onClick={()=>{setUForm({name:"",email:"",password:"",role:"member",active:true,phone:""});setUEdit(null);setUModal(true);}}>Novo Usuário</Btn></div>
      <div style={{display:"flex",flexDirection:"column",gap:10}}>{users.map(u=>(<Card key={u.id}>
        <div style={{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap"}}>
          <div style={{width:46,height:46,borderRadius:"50%",background:u.active?"#1e293b":"#0a0a14",border:`2px solid ${u.active?"#334155":"#1e293b"}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:15,fontWeight:700,color:u.active?"#94a3b8":"#334155",flexShrink:0}}>{u.avatar||"?"}</div>
          <div style={{flex:1,minWidth:140}}><div style={{fontSize:14,fontWeight:700,color:u.active?"#f1f5f9":"#475569"}}>{u.name}{u.id===cu.id&&<span style={{fontSize:11,color:"#f59e0b",marginLeft:6}}>(você)</span>}</div><div style={{fontSize:12,color:"#64748b"}}>{u.email}</div>{u.phone&&<div style={{fontSize:12,color:"#475569",marginTop:1}}>{u.phone}</div>}</div>
          <div style={{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"}}><Bdg label={roI(u.role).label} color="#6366f1" sm/><Bdg label={u.active?"Ativo":"Inativo"} color={u.active?"#10b981":"#64748b"} sm/></div>
          <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
            <Btn sm v="ghost" icon="edit" onClick={()=>{setUForm({name:u.name,email:u.email,password:"",role:u.role,active:u.active,phone:u.phone||""});setUEdit(u.id);setUModal(true);}}>Editar</Btn>
            <Btn sm v="outline" icon="link" onClick={()=>{setLUser(u);setLModal(true);}}>Projetos</Btn>
            {u.id!==cu.id&&<Btn sm v="ghost" onClick={()=>toggleActive(u.id)}>{u.active?"Desativar":"Ativar"}</Btn>}
            {u.id!==cu.id&&<Btn sm danger icon="trash" onClick={()=>delUser(u.id)}>Del</Btn>}
          </div>
        </div>
        {getLinked(u.id).length>0&&<div style={{marginTop:10,paddingTop:10,borderTop:"1px solid #1e293b",display:"flex",gap:6,flexWrap:"wrap"}}><span style={{fontSize:11,color:"#475569",alignSelf:"center"}}>Projetos:</span>{getLinked(u.id).map(p=><span key={p.id} style={{fontSize:11,background:p.color+"22",color:p.color,border:`1px solid ${p.color}44`,borderRadius:99,padding:"2px 8px"}}>{p.icon} {p.name}</span>)}</div>}
      </Card>))}</div>
      {uModal&&<Modal title={uEdit?"Editar Usuário":"Novo Usuário"} onClose={()=>setUModal(false)}>
        <div style={{display:"flex",flexDirection:"column",gap:14}}>
          <Inp label="Nome completo" value={uForm.name} onChange={v=>setUForm({...uForm,name:v})} required/>
          <Inp label="E-mail" value={uForm.email} onChange={v=>setUForm({...uForm,email:v})} type="email" required/>
          <Inp label={uEdit?"Nova senha (deixe vazio para não alterar)":"Senha inicial"} value={uForm.password} onChange={v=>setUForm({...uForm,password:v})} type="password" placeholder={uEdit?"••••••••":"mínimo 6 caracteres"} helper={!uEdit?"O usuário poderá trocar depois em Configurações":""}/>
          <Inp label="Telefone / WhatsApp" value={uForm.phone} onChange={v=>setUForm({...uForm,phone:v})} placeholder="(11) 99999-9999"/>
          <Inp label="Perfil de Acesso" value={uForm.role} onChange={v=>setUForm({...uForm,role:v})} options={ROLES.map(r=>({value:r.value,label:r.label}))}/>
          <div style={{background:"#0a0a14",borderRadius:8,padding:"10px 12px"}}><div style={{fontSize:12,color:"#64748b",marginBottom:4}}>Permissões:</div><div style={{fontSize:13,color:"#94a3b8"}}>{roI(uForm.role).desc}</div></div>
          <div style={{display:"flex",gap:10,marginTop:8}}><Btn v="ghost" onClick={()=>setUModal(false)} fw>Cancelar</Btn><Btn onClick={saveUser} loading={saving} icon="check" fw>{uEdit?"Salvar":"Criar Usuário"}</Btn></div>
        </div>
      </Modal>}
      {lModal&&lUser&&<Modal title={`Projetos de ${lUser.name}`} onClose={()=>setLModal(false)} wide>
        <div style={{marginBottom:12,fontSize:13,color:"#64748b"}}>Clique para vincular/desvincular projetos:</div>
        <div style={{display:"flex",flexDirection:"column",gap:8}}>{projects.map(p=>{const linked=(p.team||[]).includes(lUser.id);return(<div key={p.id} onClick={()=>toggleLink(lUser.id,p.id)} style={{display:"flex",gap:12,alignItems:"center",padding:"12px 14px",borderRadius:10,border:`1px solid ${linked?"#f59e0b44":"#1e293b"}`,background:linked?"#f59e0b08":"#0a0a14",cursor:"pointer",transition:"all .15s"}}>
          <div style={{width:22,height:22,borderRadius:6,border:`2px solid ${linked?"#f59e0b":"#334155"}`,background:linked?"#f59e0b":"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{linked&&<Ic n="check" s={12} c="#0f0f17"/>}</div>
          <span style={{fontSize:20,flexShrink:0}}>{p.icon}</span>
          <div style={{flex:1}}><div style={{fontSize:14,fontWeight:600,color:"#e2e8f0"}}>{p.name}</div><div style={{fontSize:12,color:"#475569"}}>{p.category} · {stI(p.status).label}</div></div>
          <Bdg label={linked?"Vinculado":"Sem acesso"} color={linked?"#10b981":"#64748b"} sm/>
        </div>);})}
        </div>
        <div style={{marginTop:16}}><Btn v="primary" onClick={()=>setLModal(false)} fw icon="check">Fechar</Btn></div>
      </Modal>}
    </div>)}

    {tab==="roles"&&(<div style={{display:"flex",flexDirection:"column",gap:14}}>
      <div style={{background:"#0a0a14",borderRadius:10,padding:"12px 16px",fontSize:13,color:"#64748b",marginBottom:4}}>Perfis definem o nível de acesso de cada usuário.</div>
      {ROLES.map(r=>{const cnt=users.filter(u=>u.role===r.value).length;const RC={admin:"#ef4444",manager:"#f59e0b",member:"#10b981",viewer:"#6366f1"};return(<Card key={r.value}><div style={{display:"flex",gap:14,alignItems:"flex-start"}}><div style={{width:44,height:44,borderRadius:10,background:RC[r.value]+"22",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}><Ic n="shield" s={20} c={RC[r.value]}/></div><div style={{flex:1}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4}}><div style={{fontSize:15,fontWeight:700,color:"#f1f5f9"}}>{r.label}</div><Bdg label={`${cnt} usuário(s)`} color={RC[r.value]} sm/></div><div style={{fontSize:13,color:"#64748b",marginBottom:10}}>{r.desc}</div>{cnt>0&&<div style={{display:"flex",gap:6,flexWrap:"wrap",marginTop:8,paddingTop:8,borderTop:"1px solid #1e293b"}}>{users.filter(u=>u.role===r.value).map(u=><span key={u.id} style={{fontSize:11,background:"#1e293b",color:"#94a3b8",borderRadius:99,padding:"2px 8px"}}>{u.name}</span>)}</div>}</div></div></Card>);})}
    </div>)}

    {tab==="projects"&&(<div>
      <div style={{background:"#0a0a14",borderRadius:10,padding:"12px 16px",marginBottom:16,fontSize:13,color:"#64748b"}}>Clique em um usuário para gerenciar seus acessos.</div>
      <div style={{display:"flex",flexDirection:"column",gap:10}}>{users.map(u=>{const linked=getLinked(u.id);return(<Card key={u.id} onClick={()=>{setLUser(u);setLModal(true);}} style={{cursor:"pointer"}}>
        <div style={{display:"flex",gap:12,alignItems:"center"}}><div style={{width:40,height:40,borderRadius:"50%",background:"#1e293b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:700,color:"#94a3b8",flexShrink:0}}>{u.avatar}</div><div style={{flex:1}}><div style={{fontSize:14,fontWeight:700,color:"#f1f5f9"}}>{u.name}</div><div style={{fontSize:12,color:"#64748b"}}>{roI(u.role).label}</div></div><div style={{textAlign:"right"}}><div style={{fontSize:20,fontWeight:800,color:"#f59e0b",fontFamily:"'Space Mono',monospace"}}>{linked.length}</div><div style={{fontSize:11,color:"#475569"}}>projeto(s)</div></div></div>
        {linked.length>0&&<div style={{marginTop:10,paddingTop:10,borderTop:"1px solid #1e293b",display:"flex",gap:6,flexWrap:"wrap"}}>{linked.map(p=><span key={p.id} style={{fontSize:11,background:p.color+"22",color:p.color,border:`1px solid ${p.color}44`,borderRadius:99,padding:"2px 8px"}}>{p.icon} {p.name}</span>)}</div>}
      </Card>);})}</div>
      {lModal&&lUser&&<Modal title={`Projetos de ${lUser.name}`} onClose={()=>setLModal(false)} wide>
        <div style={{display:"flex",flexDirection:"column",gap:8}}>{projects.map(p=>{const linked=(p.team||[]).includes(lUser.id);return(<div key={p.id} onClick={()=>toggleLink(lUser.id,p.id)} style={{display:"flex",gap:12,alignItems:"center",padding:"12px 14px",borderRadius:10,border:`1px solid ${linked?"#f59e0b44":"#1e293b"}`,background:linked?"#f59e0b08":"#0a0a14",cursor:"pointer",transition:"all .15s"}}><div style={{width:22,height:22,borderRadius:6,border:`2px solid ${linked?"#f59e0b":"#334155"}`,background:linked?"#f59e0b":"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{linked&&<Ic n="check" s={12} c="#0f0f17"/>}</div><span style={{fontSize:20,flexShrink:0}}>{p.icon}</span><div style={{flex:1}}><div style={{fontSize:14,fontWeight:600,color:"#e2e8f0"}}>{p.name}</div><div style={{fontSize:12,color:"#475569"}}>{p.category}</div></div><Bdg label={linked?"Vinculado":"Sem acesso"} color={linked?"#10b981":"#64748b"} sm/></div>);})}
        </div><div style={{marginTop:16}}><Btn fw onClick={()=>setLModal(false)} icon="check">Fechar</Btn></div>
      </Modal>}
    </div>)}

    {tab==="cats"&&(<div>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}><span style={{color:"#64748b",fontSize:14}}>{cats.length} categoria(s)</span><Btn icon="plus" sm onClick={()=>{setCForm("");setCEdit(null);setCModal(true);}}>Nova Categoria</Btn></div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))",gap:10}}>{cats.map((cat,i)=>{const cnt=projects.filter(p=>p.category===cat).length;const CC=["#6366f1","#10b981","#f59e0b","#ef4444","#3b82f6","#a78bfa","#22c55e","#f97316"];const color=CC[i%CC.length];return(<Card key={i} style={{display:"flex",flexDirection:"column",gap:10}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start"}}><div style={{width:36,height:36,borderRadius:8,background:color+"22",display:"flex",alignItems:"center",justifyContent:"center"}}><Ic n="tag" s={16} c={color}/></div><div style={{display:"flex",gap:4}}><button onClick={()=>{setCForm(cat);setCEdit(i);setCModal(true);}} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",padding:4}}><Ic n="edit" s={14} c="#64748b"/></button><button onClick={()=>delCat(i)} style={{background:"none",border:"none",cursor:"pointer",color:"#ef444466",padding:4}}><Ic n="trash" s={14} c="#ef4444"/></button></div></div>
        <div><div style={{fontSize:14,fontWeight:700,color:"#f1f5f9"}}>{cat}</div><div style={{fontSize:12,color:"#64748b",marginTop:2}}>{cnt} projeto(s)</div></div>
        <PBar value={projects.length?(cnt/projects.length)*100:0} color={color} h={4}/>
      </Card>);})}</div>
      {cModal&&<Modal title={cEdit!==null?"Editar Categoria":"Nova Categoria"} onClose={()=>setCModal(false)}><div style={{display:"flex",flexDirection:"column",gap:14}}><Inp label="Nome da Categoria" value={cForm} onChange={v=>setCForm(v)} required placeholder="Ex: Blog, SaaS, E-commerce..."/><div style={{display:"flex",gap:10}}><Btn v="ghost" onClick={()=>setCModal(false)} fw>Cancelar</Btn><Btn onClick={saveCat} icon="check" fw>{cEdit!==null?"Salvar":"Criar"}</Btn></div></div></Modal>}
    </div>)}

    {tab==="overview"&&(<div style={{display:"flex",flexDirection:"column",gap:16}}>
      <div style={{display:"grid",gridTemplateColumns:m?"1fr 1fr":"repeat(4,1fr)",gap:12}}>{[{label:"Usuários",v:users.length,c:"#6366f1",icon:"users"},{label:"Projetos",v:projects.length,c:"#10b981",icon:"folder"},{label:"Categorias",v:cats.length,c:"#f59e0b",icon:"tag"},{label:"Tarefas",v:projects.reduce((a,p)=>a+(p.tasks||[]).length,0),c:"#3b82f6",icon:"task"}].map(s=>(<Card key={s.label} style={{textAlign:"center"}}><div style={{background:s.c+"22",width:40,height:40,borderRadius:10,display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 8px"}}><Ic n={s.icon} s={18} c={s.c}/></div><div style={{fontSize:24,fontWeight:800,color:s.c,fontFamily:"'Space Mono',monospace"}}>{s.v}</div><div style={{fontSize:12,color:"#64748b",marginTop:2}}>{s.label}</div></Card>))}</div>
      <Card><h4 style={{color:"#e2e8f0",fontSize:14,fontWeight:700,margin:"0 0 14px"}}>Projetos por Usuário</h4>{users.map(u=>{const l=getLinked(u.id);return(<div key={u.id} style={{marginBottom:12}}><div style={{display:"flex",justifyContent:"space-between",marginBottom:4}}><span style={{fontSize:13,color:"#94a3b8"}}>{u.name}</span><span style={{fontSize:13,color:"#f59e0b",fontWeight:700}}>{l.length} projetos</span></div><PBar value={projects.length?(l.length/projects.length)*100:0} color="#f59e0b" h={5}/></div>);})}</Card>
    </div>)}
  </div>);
}

// ── HELP ───────────────────────────────────────────────────────────────────────
function Help({user}){
  const m=useMobile();
  const [open,setOpen]=useState(null);
  const toggle=i=>setOpen(open===i?null:i);
  const RC={admin:"#ef4444",manager:"#f59e0b",member:"#10b981",viewer:"#6366f1"};
  const sections={
    all:[
      {icon:"📖",title:"O que é o ProjectOS?",content:"O ProjectOS é um sistema de gestão de projetos para organizar, acompanhar e monetizar múltiplos projetos ao mesmo tempo.\n\n✅ Acesse pelo celular ou computador\n✅ Dados salvos automaticamente na nuvem\n✅ Vários usuários podem colaborar em tempo real\n✅ Sincronização instantânea via Firebase"},
      {icon:"🖥️",title:"Como navegar pelo sistema?",content:"💻 No computador:\n• Menu lateral esquerdo com todos os módulos\n• Clique em ◀ para recolher o menu\n• Indicador LIVE confirma conexão ativa\n\n📱 No celular:\n• Barra de navegação na parte inferior\n• Toque nos ícones para navegar\n• Ícone 🛡️ no topo abre o Painel Admin (admins)\n• Avatar no canto superior abre Configurações"},
      {icon:"📊",title:"Dashboard — Visão geral",content:"A tela inicial mostra um resumo completo:\n\n📈 Cards de estatísticas no topo: Total de projetos, Em Andamento, Planejamento, Concluídos e Receita total.\n\n📊 Status dos Projetos: gráfico de barras por status.\n\n🚀 Progresso dos Projetos Ativos: barra de progresso de cada projeto ativo.\n\n📁 Lista Completa: todos os projetos com status e progresso. Clique em qualquer um para ver os detalhes."},
      {icon:"📁",title:"Projetos — Como gerenciar?",content:"🔍 Filtros disponíveis:\n• Busca por nome ou descrição\n• Filtro por Status\n• Filtro por Categoria\n\n📋 Dentro de cada projeto:\n• Resumo: descrição, datas, monetização e marcos recentes\n• Tarefas: quadro Kanban — A Fazer / Em Andamento / Concluído\n• Marcos: etapas importantes com datas\n• Notas: observações e decisões importantes\n• Equipe: membros vinculados\n\n✏️ Para editar o progresso:\nAbra o projeto → clique no ✏️ ao lado da % → arraste o slider → clique OK"},
      {icon:"📅",title:"Timeline — Linha do tempo",content:"Exibe todos os eventos em ordem cronológica.\n\n🔍 Como filtrar:\n• Botões coloridos = projetos específicos (seleção múltipla)\n• Filtro por tipo: Inícios 🚀 / Metas 🎯 / Marcos 🔹\n\n💡 Para aparecer na Timeline, o projeto precisa ter:\n• Data de Início\n• Data Alvo\n• Marcos com datas definidas"},
      {icon:"✅",title:"Tarefas — Fluxo único",content:"As tarefas agora usam um fluxo único:\n\nTarefas:\n• Criadas pelo botão 'Nova Tarefa'\n• Podem ficar sem projeto, em um projeto, em vários projetos ou em todos\n• Quando aparecem em mais de um projeto, são tratadas como compartilhadas\n\n📌 Tarefas antigas:\n• Continuam aparecendo normalmente na mesma lista\n• Podem ser editadas sem perder os dados já salvos\n\n🔍 Filtros: por status e por projeto\n\n➡️ Para mover no Kanban: clique nas setas ‹ › nos cards"},
      {icon:"💰",title:"Financeiro — Receita e metas",content:"Acompanha a monetização de cada projeto.\n\n📊 Resumo no topo:\n• Receita Total acumulada\n• Meta Total definida\n• % da Meta geral atingida\n\n✏️ Para atualizar receita de um projeto:\nClique em Editar → altere modelo, receita e meta → Salvar\n\n💡 Modelos comuns:\n• AdSense (anúncios)\n• Licença (venda de acesso)\n• Assinatura (mensalidade)\n• Afiliados (comissão)"},
    ],
    admin:[
      {icon:"🛡️",title:"Painel Admin — O que posso fazer?",content:"O Painel Admin é exclusivo para Administradores.\n\n👥 Usuários — criar, editar, ativar/desativar\n🛡️ Perfis — visualizar permissões de cada nível\n🔗 Vincular Projetos — controlar quem acessa o quê\n🏷️ Categorias — criar e gerenciar categorias\n📊 Visão Geral — relatório consolidado do sistema"},
      {icon:"👥",title:"Como criar um novo usuário?",content:"1. Painel Admin → aba Usuários\n2. Clique em 'Novo Usuário'\n3. Preencha: nome, e-mail, senha inicial, telefone e perfil\n4. Clique em 'Criar Usuário'\n\n⚠️ O usuário usará esse e-mail e senha para entrar. Comunique as credenciais a ele.\n\n🔑 Perfis disponíveis:\n• Administrador: acesso total\n• Gerente: cria e edita projetos\n• Membro: acessa projetos vinculados\n• Visualizador: somente leitura"},
      {icon:"🔗",title:"Como vincular usuários a projetos?",content:"Pela aba 'Vincular Projetos' do Painel Admin:\n1. Clique no card do usuário\n2. Marque ✅ ou desmarque os projetos\n3. Clique em 'Salvar vínculos'\n\nOu pela aba 'Usuários':\n1. No card do usuário, clique em 'Projetos'\n2. Marque/desmarque e confirme\n\n💡 Administradores veem todos os projetos automaticamente."},
      {icon:"🏷️",title:"Como gerenciar categorias?",content:"Painel Admin → aba Categorias\n\n➕ Nova categoria: clique em 'Nova Categoria'\n✏️ Editar: ícone de lápis ao lado do nome\n🗑️ Excluir: ícone de lixeira\n\n💡 As categorias organizam os projetos por tipo (Site, Aplicativo, Marketing, etc.)"},
    ],
    manager:[
      {icon:"📝",title:"O que um Gerente pode fazer?",content:"✅ Pode:\n• Criar novos projetos\n• Editar projetos existentes\n• Adicionar tarefas, marcos e notas\n• Atualizar o progresso\n• Ver e editar dados financeiros\n\n❌ Não pode:\n• Acessar o Painel Admin\n• Criar ou gerenciar usuários\n• Alterar categorias do sistema"},
    ],
    member:[
      {icon:"👤",title:"O que um Membro pode fazer?",content:"✅ Pode:\n• Ver o Dashboard com seus projetos\n• Visualizar projetos vinculados a você\n• Adicionar tarefas, notas e marcos\n• Mover tarefas no Kanban\n• Marcar marcos como concluídos\n\n❌ Não pode:\n• Ver projetos não vinculados a você\n• Criar novos projetos\n• Acessar o Painel Admin\n• Editar dados financeiros"},
    ],
    viewer:[
      {icon:"👁️",title:"O que um Visualizador pode fazer?",content:"✅ Pode:\n• Ver o Dashboard\n• Visualizar projetos vinculados\n• Acompanhar tarefas e marcos\n• Ver a Timeline e relatórios financeiros\n\n❌ Não pode:\n• Criar ou editar qualquer informação\n• Adicionar tarefas ou notas\n• Marcar marcos como concluídos\n\n💡 Ideal para clientes ou parceiros que precisam acompanhar sem editar."},
    ],
  };
  const mySections=[...sections.all,...(sections[user.role]||[])];
  return(<div style={{padding:m?"16px":"32px",maxWidth:900,paddingBottom:m?80:32}}>
    <SH title="Ajuda & Guia" sub={`Personalizado para: ${roI(user.role).label}`}/>
    <div style={{background:RC[user.role]+"11",border:`1px solid ${RC[user.role]}33`,borderRadius:12,padding:"14px 18px",marginBottom:24,display:"flex",gap:12,alignItems:"center"}}>
      <div style={{width:44,height:44,borderRadius:10,background:RC[user.role]+"22",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}><Ic n="shield" s={22} c={RC[user.role]}/></div>
      <div><div style={{fontSize:14,fontWeight:700,color:"#f1f5f9"}}>Perfil: {roI(user.role).label}</div><div style={{fontSize:13,color:"#64748b",marginTop:2}}>{roI(user.role).desc} · {mySections.length} tópicos disponíveis</div></div>
    </div>
    <div style={{display:"flex",flexDirection:"column",gap:10}}>
      {mySections.map((s,i)=>(
        <div key={i} style={{background:"#0f172a",border:`1px solid ${open===i?"#f59e0b44":"#1e293b"}`,borderRadius:12,overflow:"hidden",transition:"border-color .2s"}}>
          <button onClick={()=>toggle(i)} style={{width:"100%",background:"none",border:"none",padding:"16px 18px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:"pointer",gap:12}}>
            <div style={{display:"flex",gap:12,alignItems:"center"}}><span style={{fontSize:20,flexShrink:0}}>{s.icon}</span><span style={{fontSize:14,fontWeight:700,color:"#f1f5f9",textAlign:"left"}}>{s.title}</span></div>
            <span style={{color:"#64748b",fontSize:16,flexShrink:0,display:"inline-block",transform:open===i?"rotate(180deg)":"none",transition:"transform .2s"}}>▾</span>
          </button>
          {open===i&&<div style={{padding:"0 18px 18px",borderTop:"1px solid #1e293b"}}>
            <div style={{marginTop:14,display:"flex",flexDirection:"column",gap:6}}>
              {s.content.split("\n").map((line,j)=>{
                if(!line.trim())return<div key={j} style={{height:6}}/>;
                const special=["✅","❌","💡","⚠️","🔑","📌","🌐","➕","✏️","🗑️","➡️","💻","📱"].some(e=>line.startsWith(e));
                const isNum=/^\d\./.test(line.trim());
                const isH=line.endsWith(":")&&line.length<40;
                return<div key={j} style={{fontSize:13,color:isH?"#f59e0b":special||isNum?"#94a3b8":"#64748b",fontWeight:isH?700:400,paddingLeft:special||isNum?8:isH?0:0,lineHeight:1.7,borderLeft:isH?"3px solid #f59e0b44":"none",paddingLeft:isH?12:special||isNum?8:0}}>{line}</div>;
              })}
            </div>
          </div>}
        </div>
      ))}
    </div>
    <Card style={{marginTop:20,background:"#0a0a14"}}>
      <div style={{display:"flex",gap:12,alignItems:"center"}}><div style={{fontSize:28}}>💬</div><div><div style={{fontSize:14,fontWeight:700,color:"#f1f5f9",marginBottom:4}}>Ainda com dúvidas?</div><div style={{fontSize:13,color:"#64748b",lineHeight:1.5}}>Entre em contato com o administrador do sistema para suporte ou para solicitar novas funcionalidades.</div></div></div>
    </Card>
  </div>);
}

// ── SETTINGS ───────────────────────────────────────────────────────────────────
function Settings({user,users,reloadUsers,toast,projects,reloadProjects,cats,setCats}){
  const m=useMobile();const [tab,setTab]=useState("profile");
  const [form,setForm]=useState({name:user.name,email:user.email,password:"",phone:user.phone||""});const [saving,setSaving]=useState(false);
  const [importing,setImporting]=useState(false);
  const importRef=React.useRef();
  const savePro=async()=>{
    setSaving(true);
    try{
      const av=avt(form.name);
      await db_set("users",user.id,Domain.workspace.withRecord({...user,name:form.name,phone:form.phone,avatar:av,updatedAt:now()}));
      if(form.password&&form.password.length>=6){
        try{
          const{auth,updatePassword}=FB();
          if(auth.currentUser)await updatePassword(auth.currentUser,form.password);
          setForm(prev=>({...prev,password:""}));
          toast("Perfil e senha atualizados!","success");
        }catch(e){
          if(e.code==="auth/requires-recent-login")toast("Perfil salvo. Para trocar a senha, saia e entre novamente antes de salvar a nova senha.","info");
          else throw e;
        }
      }
      else{toast("Perfil atualizado!","success");}
      await reloadUsers();
    }catch(e){toast("Erro: "+(e.code==="auth/requires-recent-login"?"faça login novamente para trocar a senha.":e.message),"error");}
    setSaving(false);
  };
  const exportData=async()=>{
    const [globalTasks,projectMembers,tasks,milestones,notes,financeEntries,activityLogs]=await Promise.all([
      db_getAll("globalTasks").catch(()=>[]),
      db_getAll("projectMembers").catch(()=>[]),
      db_getAll("tasks").catch(()=>[]),
      db_getAll("milestones").catch(()=>[]),
      db_getAll("notes").catch(()=>[]),
      db_getAll("financeEntries").catch(()=>[]),
      db_getAll("activityLogs").catch(()=>[]),
    ]);
    const data={schemaVersion:Domain.schema.version,projects,users,globalTasks:Domain.workspace.withList(globalTasks),projectMembers:Domain.workspace.withList(projectMembers),tasks:Domain.workspace.withList(tasks),milestones:Domain.workspace.withList(milestones),notes:Domain.workspace.withList(notes),financeEntries:Domain.workspace.withList(financeEntries),activityLogs:Domain.workspace.withList(activityLogs),cats,exportedAt:new Date().toISOString(),version:"1.0"};
    const b=new Blob([JSON.stringify(data,null,2)],{type:"application/json"});
    const url=URL.createObjectURL(b);const a=document.createElement("a");a.href=url;a.download=`projectos_backup_${now()}.json`;a.click();URL.revokeObjectURL(url);
    toast("Backup exportado!","success");
  };
  const importData=async(e)=>{
    const file=e.target.files[0];if(!file)return;
    setImporting(true);
    try{
      const text=await file.text();const data=JSON.parse(text);
      if(!data.projects){toast("Arquivo inválido. Use um backup do ProjectOS.","error");setImporting(false);return;}
      if(!confirm(`Importar ${(data.projects||[]).length} projetos?`)){setImporting(false);return;}
      for(const p of(data.projects||[])){const project=Domain.workspace.withRecord(p);await db_set("projects",p.id,project);await db_syncProjectChildren(project,user.id);}
      for(const t of(data.globalTasks||[])){const task=Domain.workspace.withRecord(t);await db_set("globalTasks",t.id,task);await db_saveTaskDocument(task,{projectIds:task.projects||task.projectIds||[],createdBy:task.createdBy||user.id,sourceType:"global"});}
      for(const task of(data.tasks||[])){try{await db_set("tasks",task.id,Domain.workspace.withRecord(task));}catch(e){console.warn("Task import skipped:",e);}}
      for(const milestone of(data.milestones||[])){try{await db_set("milestones",milestone.id,Domain.workspace.withRecord(milestone));}catch(e){console.warn("Milestone import skipped:",e);}}
      for(const note of(data.notes||[])){try{await db_set("notes",note.id,Domain.workspace.withRecord(note));}catch(e){console.warn("Note import skipped:",e);}}
      for(const entry of(data.financeEntries||[])){try{await db_set("financeEntries",entry.id,Domain.workspace.withRecord(entry));}catch(e){console.warn("Finance import skipped:",e);}}
      for(const log of(data.activityLogs||[])){try{await db_set("activityLogs",log.id,Domain.workspace.withRecord(log));}catch(e){console.warn("Activity log import skipped:",e);}}
      for(const member of(data.projectMembers||[])){try{await db_set("projectMembers",member.id,Domain.workspace.withRecord(member));}catch(e){console.warn("Project membership import skipped:",e);}}
      if(data.cats){await db_set("config","categories",Domain.workspace.withRecord({list:data.cats,schemaVersion:Domain.schema.version}));setCats(data.cats);}
      await reloadProjects();
      toast(`${(data.projects||[]).length} projetos importados!`,"success");
    }catch(err){toast("Erro ao importar: "+err.message,"error");}
    setImporting(false);e.target.value="";
  };
  const loadDemo=async()=>{
    if(!confirm(`Importar ${INIT_PROJECTS.length} projetos de demonstração?`))return;
    setImporting(true);
    for(const p of INIT_PROJECTS){const project=Domain.workspace.withRecord(p);await db_set("projects",p.id,project);await db_syncProjectChildren(project,user.id);}
    const dc=["Site","Aplicativo","Marketing","Financeiro","Outro"];
    await db_set("config","categories",Domain.workspace.withRecord({list:dc,schemaVersion:Domain.schema.version}));setCats(dc);
    await reloadProjects();
    toast(`${INIT_PROJECTS.length} projetos demo importados!`,"success");
    setImporting(false);
  };
  return(<div style={{padding:m?"16px":"32px",maxWidth:700,paddingBottom:m?80:32}}>
    <SH title="Configurações"/>
    <div style={{display:"flex",gap:0,borderBottom:"1px solid #1e293b",marginBottom:20,overflowX:"auto"}}>
      {["profile","data","install"].map(t=><button key={t} onClick={()=>setTab(t)} style={{padding:"10px 16px",border:"none",background:"none",color:tab===t?"#f59e0b":"#64748b",borderBottom:`2px solid ${tab===t?"#f59e0b":"transparent"}`,cursor:"pointer",fontSize:13,fontWeight:600,whiteSpace:"nowrap"}}>{t==="profile"?"Meu Perfil":t==="data"?"Importar / Exportar":"Instalar App"}</button>)}
    </div>
    {tab==="profile"&&<Card>
      <div style={{display:"flex",gap:14,alignItems:"center",marginBottom:20}}><div style={{width:52,height:52,borderRadius:"50%",background:"#1e293b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,fontWeight:700,color:"#f59e0b"}}>{user.avatar}</div><div><div style={{fontSize:16,fontWeight:700,color:"#f1f5f9"}}>{user.name}</div><div style={{fontSize:13,color:"#64748b"}}>{roI(user.role).label}</div></div></div>
      <div style={{display:"flex",flexDirection:"column",gap:14}}>
        <Inp label="Nome" value={form.name} onChange={v=>setForm({...form,name:v})}/>
        <Inp label="E-mail" value={form.email} onChange={v=>setForm({...form,email:v})} type="email" helper="Para alterar o e-mail contacte o administrador"/>
        <Inp label="Telefone" value={form.phone} onChange={v=>setForm({...form,phone:v})} placeholder="(11) 99999-9999"/>
        <Inp label="Nova senha (mín. 6 caracteres)" value={form.password} onChange={v=>setForm({...form,password:v})} type="password" placeholder="Vazio = manter atual"/>
        <Btn onClick={savePro} loading={saving} icon="check" fw>Salvar alterações</Btn>
      </div>
    </Card>}
    {tab==="data"&&<div style={{display:"flex",flexDirection:"column",gap:14}}>
      <Card>
        <h4 style={{color:"#10b981",fontSize:13,margin:"0 0 10px",textTransform:"uppercase",letterSpacing:.8}}>⬇️ Exportar Backup</h4>
        <p style={{fontSize:13,color:"#64748b",margin:"0 0 14px",lineHeight:1.6}}>Baixa um arquivo JSON com todos os projetos e categorias. Use como backup de segurança.</p>
        <Btn v="ghost" icon="install" onClick={exportData}>Exportar backup (.json)</Btn>
      </Card>
      <Card>
        <h4 style={{color:"#6366f1",fontSize:13,margin:"0 0 10px",textTransform:"uppercase",letterSpacing:.8}}>⬆️ Importar Backup</h4>
        <p style={{fontSize:13,color:"#64748b",margin:"0 0 14px",lineHeight:1.6}}>Restaura projetos de um arquivo de backup exportado anteriormente.</p>
        <input ref={importRef} type="file" accept=".json" onChange={importData} style={{display:"none"}}/>
        <Btn v="outline" icon="upload" onClick={()=>importRef.current.click()} loading={importing}>Selecionar arquivo .json</Btn>
      </Card>
      <Card>
        <h4 style={{color:"#f59e0b",fontSize:13,margin:"0 0 10px",textTransform:"uppercase",letterSpacing:.8}}>⭐ Projetos de Demonstração</h4>
        <p style={{fontSize:13,color:"#64748b",margin:"0 0 10px",lineHeight:1.6}}>Importa os {INIT_PROJECTS.length} projetos de exemplo pré-configurados com dados reais:</p>
        <div style={{display:"flex",flexWrap:"wrap",gap:6,marginBottom:14}}>{INIT_PROJECTS.map(p=><span key={p.id} style={{fontSize:11,background:p.color+"22",color:p.color,border:`1px solid ${p.color}44`,borderRadius:99,padding:"2px 8px"}}>{p.icon} {p.name}</span>)}</div>
        <Btn v="outline" icon="folder" onClick={loadDemo} loading={importing}>Importar projetos demo</Btn>
      </Card>
      <Card>
        <h4 style={{color:"#94a3b8",fontSize:13,margin:"0 0 12px",textTransform:"uppercase",letterSpacing:.8}}>ℹ️ Informações do Sistema</h4>
        {[["Versão","1.0.0"],["Projetos",projects.length],["Usuários",users.length],["Categorias",cats.length],["Banco de dados","Firebase Firestore"],["Hospedagem","Netlify"]].map(([k,v])=><div key={k} style={{display:"flex",justifyContent:"space-between",padding:"8px 0",borderBottom:"1px solid #1e293b"}}><span style={{fontSize:13,color:"#64748b"}}>{k}</span><span style={{fontSize:13,color:"#e2e8f0",fontWeight:600}}>{v}</span></div>)}
      </Card>
    </div>}
    {tab==="install"&&<div style={{display:"flex",flexDirection:"column",gap:14}}>
      <Card><div style={{textAlign:"center",padding:"20px 0"}}><div style={{fontSize:64,marginBottom:12}}>📖</div><h3 style={{color:"#f1f5f9",fontSize:18,fontWeight:700,margin:"0 0 8px"}}>Instalar ProjectOS</h3><p style={{color:"#64748b",fontSize:14,lineHeight:1.6,margin:0}}>Adicione à tela inicial como um app nativo!</p></div></Card>
      <Card><h4 style={{color:"#94a3b8",fontSize:13,margin:"0 0 14px",textTransform:"uppercase",letterSpacing:.8}}>📱 Android (Chrome)</h4>{["1. Abra no Google Chrome","2. Menu ⋮ → 'Adicionar à tela inicial'","3. Confirme e toque em 'Adicionar'","✅ Ícone 📖 na tela inicial!"].map((s,i)=><div key={i} style={{fontSize:13,color:s.startsWith("✅")?"#10b981":"#94a3b8",padding:"6px 0",borderBottom:i<3?"1px solid #1e293b11":"none"}}>{s}</div>)}</Card>
      <Card><h4 style={{color:"#94a3b8",fontSize:13,margin:"0 0 14px",textTransform:"uppercase",letterSpacing:.8}}>🍎 iPhone / iPad (Safari)</h4>{["1. Abra no Safari","2. Toque em Compartilhar □↑","3. 'Adicionar à Tela de Início'","✅ Ícone 📖 na tela inicial!"].map((s,i)=><div key={i} style={{fontSize:13,color:s.startsWith("✅")?"#10b981":"#94a3b8",padding:"6px 0",borderBottom:i<3?"1px solid #1e293b11":"none"}}>{s}</div>)}</Card>
    </div>}
  </div>);
}

// ── APP ROOT ───────────────────────────────────────────────────────────────────
function App(){
  const m=useMobile();
  const [fbReady,setFbReady]=useState(!!window.__FB_READY);
  const [configured,setConfigured]=useState(true);
  const [cu,setCu]=useState(null);
  const [users,setUsers]=useState([]);
  const [projects,setProjects]=useState([]);
  const [globalTasks,setGlobalTasks]=useState([]);
  const [cats,setCats]=useState(INIT_CATS);
  const [view,setView]=useState("dashboard");
  const [sel,setSel]=useState(null);
  const [sCol,setSCol]=useState(false);
  const [loading,setLoading]=useState(true);
  const [toast,setToast]=useState(null);
  const [theme,toggleTheme]=useTheme();

  const showToast=(msg,type="info")=>{setToast({msg,type});setTimeout(()=>setToast(null),3000);};
  const ensureWorkspace=async(owner={})=>{
    try{
      const id=Domain.workspace.defaultId;
      const existing=await db_get("workspaces",id);
      if(!existing)await db_set("workspaces",id,Domain.workspace.createDefault(owner));
    }catch(e){console.warn("Workspace setup skipped:",e);}
  };

  useEffect(()=>{
    if(fbReady)return;
    const h=()=>setFbReady(true);
    window.addEventListener("fb_ready",h);
    return()=>window.removeEventListener("fb_ready",h);
  },[]);

  useEffect(()=>{
    if(!fbReady)return;
    // Check if Firebase is configured
    const cfg = window.__FB?.auth?.app?.options;
    if(!cfg||cfg.apiKey==="COLE_SEU_API_KEY_AQUI"){setConfigured(false);setLoading(false);return;}

    const { auth, onAuthStateChanged } = FB();
    const unsub = onAuthStateChanged(auth, async firebaseUser=>{
      if(firebaseUser){
        try{
          let userData = await db_get("users", firebaseUser.uid);
          // Auto-cria o perfil no primeiro acesso
          if(!userData){
            const isFirst = (await db_getAll("users")).length === 0;
            userData = {
              name: firebaseUser.email.split("@")[0].replace(/[^a-zA-Z]/g," ").trim() || "Administrador",
              email: firebaseUser.email,
              role: isFirst ? "admin" : "member",
              active: true,
              avatar: "AD",
              phone: "",
              createdAt: now(),
              workspaceId: Domain.workspace.defaultId,
            };
            await db_set("users", firebaseUser.uid, userData);
          }
          if(userData.active){
            const currentUser={...userData,id:firebaseUser.uid,workspaceId:userData.workspaceId||Domain.workspace.defaultId};
            await ensureWorkspace(currentUser);
            setCu(currentUser);
            await loadAll(currentUser);
          }else{
            await FB().signOut(auth);
          }
        }catch(e){ console.error(e); }
      }else{ setCu(null); }
      setLoading(false);
    });
    return()=>unsub();
  },[fbReady]);

  const safeRead=async(label,reader,fallback)=>{
    try{return await reader();}
    catch(e){console.warn(`Falha ao carregar ${label}:`,e);showToast(`Não foi possível carregar ${label}.`,"error");return fallback;}
  };
  const loadUsersFor=async current=>{
    if(current?.role==="admin")return Domain.workspace.withList(await db_getAll("users"));
    const own=await db_get("users",current.id);
    return own?[Domain.workspace.withRecord({...own,id:current.id})]:[current];
  };
  const loadAll=async(current=cu)=>{
    const [ps,us,catDoc,gts]=await Promise.all([
      safeRead("projetos",()=>db_getAll("projects"),[]),
      safeRead("usuários",()=>loadUsersFor(current),current?[current]:[]),
      safeRead("categorias",()=>db_get("config","categories"),null),
      safeRead("tarefas",()=>db_getAll("globalTasks"),[])
    ]);
    setProjects(Domain.workspace.withList(ps));setUsers(us);setGlobalTasks(Domain.workspace.withList(gts));
    if(catDoc?.list)setCats(catDoc.list);
    else{ if((current?.role==="admin"||current?.role==="manager")&&ps.length===0){for(const p of INIT_PROJECTS){const project=Domain.workspace.withRecord(p);await db_set("projects",p.id,project);await db_syncProjectChildren(project,current?.id||"");}} }
  };
  const reloadProjects=async()=>{const ps=await safeRead("projetos",()=>db_getAll("projects"),[]);setProjects(Domain.workspace.withList(ps));};
  const reloadGlobalTasks=async()=>{const gts=await safeRead("tarefas",()=>db_getAll("globalTasks"),[]);setGlobalTasks(Domain.workspace.withList(gts));};
  const reloadUsers=async()=>{const us=await safeRead("usuários",()=>loadUsersFor(cu),cu?[cu]:[]);setUsers(us);const me=us.find(x=>x.id===cu?.id);if(me)setCu(prev=>({...prev,...me}));};

  const login=async u=>{const scopedUser=Domain.workspace.withRecord(u);await ensureWorkspace(scopedUser);setCu(scopedUser);await loadAll(scopedUser);setView("dashboard");};
  const logout=async()=>{const {auth,signOut}=FB();await signOut(auth);setCu(null);};
  const go=v=>{setView(v);window.scrollTo(0,0);};

  const VN={dashboard:"Dashboard",projects:"Projetos",project_detail:"Projeto",timeline:"Timeline",tasks:"Tarefas",finances:"Financeiro",admin:"Painel Admin",settings:"Configurações",help:"Ajuda"};

  if(!fbReady||loading)return(<div style={{minHeight:"100vh",background:"#070711",display:"flex",alignItems:"center",justifyContent:"center"}}>
    <div style={{textAlign:"center"}}>
      <div style={{fontSize:56,display:"inline-block",animation:"spin 1.2s linear infinite"}}>📖</div>
      <div style={{color:"#475569",fontSize:14,marginTop:12}}>Buscando projetos...</div>
    </div>
  </div>);

  if(!configured)return <SetupScreen/>;
  if(!cu)return <Login onLogin={login} toast={showToast}/>;

  return(<div data-app-theme={theme} style={{display:"flex",minHeight:"100vh",background:theme==="day"?"#f6f8fb":"#070711"}}>
    {!m&&<Sidebar view={view} go={go} user={cu} onLogout={logout} col={sCol} setCol={setSCol}/>}
    <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"}}>
      <header style={{background:"#0a0a14",borderBottom:"1px solid #1e293b",padding:m?"12px 16px":"12px 24px",display:"flex",alignItems:"center",justifyContent:"space-between",position:"sticky",top:0,zIndex:50,flexShrink:0}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          {m&&view==="project_detail"&&<button onClick={()=>go("projects")} style={{background:"none",border:"none",cursor:"pointer",color:"#64748b",padding:"0 8px 0 0"}}><Ic n="back" s={20} c="#64748b"/></button>}
          {m&&<span style={{fontSize:20}}>📖</span>}
          <span style={{color:"#e2e8f0",fontWeight:700,fontSize:m?15:14}}>{VN[view]||view}</span>
        </div>
        <div style={{display:"flex",gap:8,alignItems:"center"}}>
          <ThemeToggle theme={theme} onToggle={toggleTheme}/>
          {/* Sync indicator */}
          <div style={{display:"flex",alignItems:"center",gap:4,background:"#10b98111",border:"1px solid #10b98133",borderRadius:20,padding:"3px 8px"}}>
            <div style={{width:6,height:6,borderRadius:"50%",background:"#10b981",animation:"pulse 2s infinite"}}/>
            {!m&&<span style={{fontSize:10,color:"#10b981",fontWeight:600}}>LIVE</span>}
          </div>
          {m&&cu.role==="admin"&&<button onClick={()=>go("admin")} style={{background:"none",border:"none",cursor:"pointer",color:view==="admin"?"#f59e0b":"#64748b",padding:4}}><Ic n="shield" s={20} c={view==="admin"?"#f59e0b":"#64748b"}/></button>}
          <div onClick={()=>go("settings")} style={{width:34,height:34,borderRadius:"50%",background:"#1e293b",display:"flex",alignItems:"center",justifyContent:"center",fontSize:13,fontWeight:700,color:"#f59e0b",cursor:"pointer"}}>{cu.avatar||"?"}</div>
          {m&&<button onClick={logout} style={{background:"none",border:"none",cursor:"pointer",color:"#ef4444",padding:4}}><Ic n="logout" s={18} c="#ef4444"/></button>}
        </div>
      </header>
      <main style={{flex:1,overflowY:"auto",overflowX:"hidden"}}>
        {view==="dashboard"      &&<Dashboard projects={projects} user={cu} go={go} setSel={setSel}/>}
        {view==="projects"       &&<Projects projects={projects} users={users} user={cu} reloadProjects={reloadProjects} go={go} setSel={setSel} cats={cats} toast={showToast}/>}
        {view==="project_detail" &&<Detail pid={sel} projects={projects} users={users} user={cu} reloadProjects={reloadProjects} go={go} toast={showToast} globalTasks={globalTasks} reloadGlobalTasks={reloadGlobalTasks}/>}
        {view==="timeline"       &&<Timeline projects={projects} user={cu}/>}
        {view==="tasks"          &&<Tasks projects={projects} user={cu} users={users} globalTasks={globalTasks} reloadProjects={reloadProjects} reloadGlobalTasks={reloadGlobalTasks} toast={showToast}/>}
        {view==="finances"       &&<Finances projects={projects} user={cu} reloadProjects={reloadProjects} toast={showToast}/>}
        {view==="admin"          &&cu.role==="admin"&&<AdminPanel users={users} projects={projects} reloadUsers={reloadUsers} reloadProjects={reloadProjects} cats={cats} setCats={setCats} cu={cu} toast={showToast}/>}
        {view==="help"           &&<Help user={cu}/>}
        {view==="settings"       &&<Settings user={cu} users={users} reloadUsers={reloadUsers} toast={showToast} projects={projects} reloadProjects={reloadProjects} cats={cats} setCats={setCats}/>}
      </main>
    </div>
    {m&&<BotNav view={view} go={go} user={cu}/>}
    {toast&&<Toast msg={toast.msg} type={toast.type}/>}
  </div>);
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
