// Admin screens: dashboard, projects, clients, hours
const { useState: useStateA, useMemo: useMemoA } = React;

// =============================================================== DASHBOARD
function AdminDashboard({ onNav, onOpenProject }) {
  const D = useStore();
  const totalHours = D.totalHours();
  const income = D.totalIncome();
  const openBugs = D.openBugs();
  const activeProjects = D.projects.filter(p => p.stage !== 'Finalizado').length;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Buenos días, Ebed.</h1>
          <p className="page-sub">Resumen del periodo en curso · 06 al 20 de mayo de 2026</p>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={() => {
            const rows = D.hours.map(h => {
              const p = D.projectById(h.project);
              return `${h.date},${p?.name || ''},${h.task?.replace(/,/g,' ') || ''},${h.hrs},${D.RATE},${h.hrs * D.RATE}`;
            }).join('\n');
            const csv = `Fecha,Proyecto,Descripcion,Horas,Tarifa,Costo\n${rows}`;
            const blob = new Blob([csv], {type:'text/csv'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url; a.download = `bugzero_horas_${new Date().toISOString().slice(0,10)}.csv`; a.click();
            URL.revokeObjectURL(url);
          }}><Icon.Download width="14" height="14"/> Exportar reporte</button>
          <button className="btn btn-primary" onClick={() => onNav('hours')}><Icon.Plus width="14" height="14"/> Registrar horas</button>
        </div>
      </div>

      <div className="grid-4" style={{marginBottom: 16}}>
        <StatCard label="Horas trabajadas" value={`${totalHours.toFixed(1)}h`} delta="↑ 14% vs quincena previa" deltaTone="up" hint=""/>
        <StatCard label="Ingreso estimado" value={D.fmtMxnShort(income)} delta="MXN" hint="· cierre 20 may" />
        <StatCard label="Proyectos activos" value={activeProjects} hint={`de ${D.projects.length} totales`}/>
        <StatCard label="Bugs abiertos" value={openBugs} delta="3 críticos" deltaTone="down" hint=""/>
      </div>

      <div className="grid-2" style={{marginBottom: 16}}>
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">Horas por día · quincena actual</div>
              <div className="card-sub">Total {totalHours.toFixed(1)}h en 15 días</div>
            </div>
            <span className="badge accent"><span className="dot"/>En curso</span>
          </div>
          <div className="card-pad">
            <SparkBar
              data={D.heatmap}
              max={8}
              labels={['06','07','08','09','10','11','12','13','14','15','16','17','18','19','20']}
            />
            <div style={{display:'flex', justifyContent:'space-between', marginTop:16, paddingTop:14, borderTop:'1px solid var(--border)'}}>
              <div>
                <div style={{fontSize:11.5, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.06em'}}>Promedio diario</div>
                <div style={{fontSize:18, fontWeight:600, marginTop:4, fontVariantNumeric:'tabular-nums'}}>{(totalHours/15).toFixed(1)}h</div>
              </div>
              <div>
                <div style={{fontSize:11.5, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.06em'}}>Día más productivo</div>
                <div style={{fontSize:18, fontWeight:600, marginTop:4, fontVariantNumeric:'tabular-nums'}}>17 may · 6.0h</div>
              </div>
              <div>
                <div style={{fontSize:11.5, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.06em'}}>Costo estimado</div>
                <div style={{fontSize:18, fontWeight:600, marginTop:4, fontVariantNumeric:'tabular-nums'}}>{D.fmtMxnShort(income)} MXN</div>
              </div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">Estado de incidencias</div>
              <div className="card-sub">{D.bugs.length} bugs · últimos 30 días</div>
            </div>
            <button className="btn btn-sm" onClick={() => onNav('bugs')}>Ver todas <Icon.Arrow width="12" height="12"/></button>
          </div>
          <div className="card-pad" style={{display:'flex', gap:24, alignItems:'center'}}>
            <Donut value={openBugs} max={D.bugs.length} label="abiertos" color="oklch(0.55 0.18 25)"/>
            <div style={{flex:1, display:'flex', flexDirection:'column', gap:9}}>
              {[
                ['Abierta', D.bugs.filter(b=>b.status==='Abierta').length, 'danger'],
                ['En corrección', D.bugs.filter(b=>b.status==='En corrección').length, 'warning'],
                ['Re-test', D.bugs.filter(b=>b.status==='Re-test').length, 'accent'],
                ['Corregida', D.bugs.filter(b=>b.status==='Corregida').length, 'success'],
                ['Cerrada', D.bugs.filter(b=>b.status==='Cerrada').length, 'neutral'],
              ].map(([k,v,t]) => (
                <div key={k} className="row" style={{justifyContent:'space-between'}}>
                  <Badge tone={t} dot>{k}</Badge>
                  <span className="mono" style={{fontSize:13, fontWeight:500}}>{v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="card-header">
            <div className="card-title">Proyectos activos</div>
            <button className="btn btn-sm" onClick={() => onNav('projects')}>Ver todos <Icon.Arrow width="12" height="12"/></button>
          </div>
          <table className="table">
            <thead><tr><th>Proyecto</th><th>Cliente</th><th>Estado</th><th style={{textAlign:'right'}}>Horas</th><th></th></tr></thead>
            <tbody>
              {D.projects.filter(p=>p.stage!=='Finalizado').slice(0,5).map(p => {
                const c = D.clientById(p.client_id);
                return (
                  <tr key={p.id} style={{cursor:'pointer'}} onClick={() => onOpenProject(p.id)}>
                    <td><div className="cell-strong">{p.name}</div><div className="cell-muted" style={{fontSize:11.5, marginTop:2}}>último: {p.lastActivity}</div></td>
                    <td><div className="row" style={{gap:8}}><div className="client-avatar" style={{width:24, height:24, fontSize:10, borderRadius:6}}>{c?.name?.split(" ").map(w=>w[0]).join("").slice(0,2).toUpperCase()}</div>{c?.name || '—'}</div></td>
                    <td><Badge tone={D.stageBadge(p.stage)} dot>{p.stage}</Badge></td>
                    <td style={{textAlign:'right'}} className="num">{(p.hours??0).toFixed(1)} / {p.allocated ?? 0}</td>
                    <td><button className="icon-btn"><Icon.Arrow width="14" height="14"/></button></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="card">
          <div className="card-header">
            <div className="card-title">Actividad reciente</div>
            <button className="btn btn-sm btn-ghost">Ver bitácora</button>
          </div>
          <div className="card-pad">
            <div className="timeline">
              <div className="timeline-item now">
                <div className="timeline-time">Hoy · 14:32</div>
                <div className="timeline-title">Registraste 3.5h en Portal Distribuidores</div>
                <div className="timeline-desc">Re-test módulo de catálogo y validación de filtros en mobile</div>
              </div>
              <div className="timeline-item">
                <div className="timeline-time">Hoy · 11:08</div>
                <div className="timeline-title">Bug BUG-0035 abierto en Dashboard Analítico</div>
                <div className="timeline-desc">Tooltip KPI se corta por encima de viewport · severidad Baja</div>
              </div>
              <div className="timeline-item">
                <div className="timeline-time">Ayer · 18:40</div>
                <div className="timeline-title">Subiste reporte quincenal · Checkout v3.2</div>
                <div className="timeline-desc">Reporte_Quincenal_Checkout_v3.2_Sem19-20.pdf · 2.4 MB</div>
              </div>
              <div className="timeline-item">
                <div className="timeline-time">Ayer · 15:12</div>
                <div className="timeline-title">Cobalto Retail accedió al portal</div>
                <div className="timeline-desc">Karina Solís revisó 2 proyectos y descargó 1 reporte</div>
              </div>
              <div className="timeline-item">
                <div className="timeline-time">17 may · 09:30</div>
                <div className="timeline-title">BUG-0038 marcado como crítico</div>
                <div className="timeline-desc">Doble tap en CTA crea dos cuentas · Onboarding Móvil</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// =============================================================== CLIENTS
function AdminClients({ onOpenClient }) {
  const D = useStore();
  const [open, setOpen] = useStateA(false);
  const [editId, setEditId] = useStateA(null);
  const [saving, setSaving] = useStateA(false);
  const [form, setForm] = useStateA({ name:'', contact_name:'', position:'', contact_email:'', contact_phone:'', status:'Activo', notes:'' });
  const [error, setError] = useStateA(null);
  const [search, setSearch] = useStateA('');
  const [statusFilter, setStatusFilter] = useStateA('Todos');
  const [confirmDelete, setConfirmDelete] = useStateA(null);
  const [deleting, setDeleting] = useStateA(false);

  const filtered = D.clients.filter(c => {
    const q = search.toLowerCase();
    const matchesSearch = !q || c.name?.toLowerCase().includes(q) || c.contact_name?.toLowerCase().includes(q) || c.contact_email?.toLowerCase().includes(q);
    const matchesStatus = statusFilter === 'Todos' || c.status === statusFilter;
    return matchesSearch && matchesStatus;
  });
  const { page, setPage, totalPages, slice } = usePagination(filtered, 10);

  function openCreate() {
    setEditId(null);
    setForm({ name:'', contact_name:'', position:'', contact_email:'', contact_phone:'', status:'Activo', notes:'' });
    setError(null);
    setOpen(true);
  }
  function openEdit(c) {
    setEditId(c.id);
    setForm({ name:c.name||'', contact_name:c.contact_name||'', position:c.position||'', contact_email:c.contact_email||'', contact_phone:c.contact_phone||'', status:c.status||'Activo', notes:c.notes||'' });
    setError(null);
    setOpen(true);
  }

  async function handleSave() {
    setSaving(true); setError(null);
    try {
      if (editId) {
        await BugzeroAPI.clients.update(editId, form);
      } else {
        await BugzeroAPI.clients.create(form);
      }
      await refreshData();
      setOpen(false);
      setForm({ name:'', contact_name:'', position:'', contact_email:'', contact_phone:'', status:'Activo', notes:'' });
      setEditId(null);
    } catch (e) {
      setError(e.message || 'Error al guardar cliente');
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!confirmDelete) return;
    setDeleting(true);
    try {
      await BugzeroAPI.clients.remove(confirmDelete);
      await refreshData();
      setConfirmDelete(null);
    } catch (e) {
      alert(e.message || 'Error al eliminar');
    } finally {
      setDeleting(false);
    }
  }

  const update = (k,v) => setForm(f => ({...f, [k]:v}));

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Clientes</h1>
          <p className="page-sub">{D.clients.length} clientes registrados · {D.clients.filter(c=>c.status==='Activo').length} activos</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={openCreate}><Icon.Plus width="14" height="14"/> Nuevo cliente</button>
        </div>
      </div>

      <div className="filter-bar">
        <Icon.Search width="14" height="14" style={{color:'var(--text-3)'}}/>
        <input className="input" placeholder="Buscar cliente o contacto…" style={{border:'none', padding:0, flex:1}} value={search} onChange={e=>{setSearch(e.target.value); setPage(1);}}/>
        <div style={{width:1, height:18, background:'var(--border)'}}/>
        {['Todos','Activo','Pausa'].map(s => (
          <button key={s} className={`filter-pill ${statusFilter===s?'active':''}`} onClick={()=>{setStatusFilter(s); setPage(1);}}>
            {s==='Todos' ? `Todos · ${D.clients.length}` : `${s} · ${D.clients.filter(c=>c.status===s).length}`}
          </button>
        ))}
      </div>

      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>Cliente</th><th>Contacto</th><th>Correo</th>
              <th style={{textAlign:'right'}}>Proyectos</th>
              <th style={{textAlign:'right'}}>Horas periodo</th>
              <th>Estado</th><th></th>
            </tr>
          </thead>
          <tbody>
            {slice.map(c => {
              const projs = D.projectsOfClient(c.id);
              const hrs = projs.reduce((s,p) => s + D.hoursOfProject(p.id).reduce((a,h)=>a+h.hrs,0), 0);
              return (
                <tr key={c.id}>
                  <td style={{cursor:'pointer'}} onClick={()=>onOpenClient && onOpenClient(c.id)}>
                    <div className="row" style={{gap:12}}>
                      <div className="client-avatar">{c.name?.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()}</div>
                      <div>
                        <div className="cell-strong">{c.name}</div>
                        <div className="cell-muted" style={{fontSize:11.5}}>{c.id?.slice(-6).toUpperCase()}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{cursor:'pointer'}} onClick={()=>onOpenClient && onOpenClient(c.id)}>{c.contact_name}</td>
                  <td className="cell-muted" style={{cursor:'pointer'}} onClick={()=>onOpenClient && onOpenClient(c.id)}>{c.contact_email}</td>
                  <td style={{textAlign:'right'}} className="num" onClick={()=>onOpenClient && onOpenClient(c.id)}>{projs.length}</td>
                  <td style={{textAlign:'right'}} className="num" onClick={()=>onOpenClient && onOpenClient(c.id)}>{hrs.toFixed(1)}h</td>
                  <td onClick={()=>onOpenClient && onOpenClient(c.id)}><Badge tone={c.status==='Activo'?'success':'neutral'} dot>{c.status}</Badge></td>
                  <td><ActionMenu onEdit={()=>openEdit(c)} onDelete={()=>setConfirmDelete(c.id)}/></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <Paginator page={page} totalPages={totalPages} onChange={setPage}/>

      <ConfirmDialog open={!!confirmDelete} title="Eliminar cliente" message="Se eliminarán todos sus proyectos, horas, bugs y reportes asociados. ¿Continuar?" onConfirm={handleDelete} onCancel={()=>setConfirmDelete(null)} loading={deleting}/>

      <Drawer
        open={open}
        onClose={()=>setOpen(false)}
        title={editId ? 'Editar cliente' : 'Nuevo cliente'}
        footer={<>
          <button className="btn" onClick={()=>setOpen(false)} disabled={saving}>Cancelar</button>
          <button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving?(editId?'Guardando…':'Creando…'):(editId?'Guardar cambios':'Crear cliente')}</button>
        </>}
      >
        <div className="col" style={{gap:14}}>
          {error && <div style={{padding:'10px 12px', borderRadius:8, background:'rgba(220,50,50,0.12)', color:'#ff8a8a', fontSize:13}}>{error}</div>}
          <div className="field"><label className="label">Empresa / Razón social</label><input className="input" value={form.name} onChange={e=>update('name',e.target.value)} placeholder="Ej. Mariposa Studio"/></div>
          <div className="grid-2">
            <div className="field"><label className="label">Persona de contacto</label><input className="input" value={form.contact_name} onChange={e=>update('contact_name',e.target.value)} placeholder="Nombre completo"/></div>
            <div className="field"><label className="label">Puesto</label><input className="input" value={form.position} onChange={e=>update('position',e.target.value)} placeholder="Product Manager"/></div>
          </div>
          <div className="grid-2">
            <div className="field"><label className="label">Correo</label><input className="input" type="email" value={form.contact_email} onChange={e=>update('contact_email',e.target.value)} placeholder="contacto@empresa.com"/></div>
            <div className="field"><label className="label">Teléfono</label><input className="input" value={form.contact_phone} onChange={e=>update('contact_phone',e.target.value)} placeholder="+52"/></div>
          </div>
          <div className="field">
            <label className="label">Estado</label>
            <select className="select" value={form.status} onChange={e=>update('status',e.target.value)}><option>Activo</option><option>Pausa</option></select>
          </div>
          <div className="field"><label className="label">Notas internas</label><textarea className="textarea" rows="3" value={form.notes} onChange={e=>update('notes',e.target.value)} placeholder="Contexto del cliente, expectativas, etc."/></div>
          <div className="row" style={{padding:'12px 14px', background:'var(--surface-2)', borderRadius:8, fontSize:12.5, color:'var(--text-3)'}}>
            <Icon.Check width="14" height="14" style={{color:'var(--success)'}}/>
            Al crear el cliente se generará automáticamente su acceso al portal.
          </div>
        </div>
      </Drawer>
    </div>
  );
}

// =============================================================== PROJECTS
function AdminProjects({ onOpenProject }) {
  const D = useStore();
  const [stageFilter, setStageFilter] = useStateA('Todos');
  const [search, setSearch] = useStateA('');
  const filtered = D.projects.filter(p => {
    const matchesStage = stageFilter==='Todos' || p.stage===stageFilter;
    const q = search.toLowerCase();
    const matchesSearch = !q || p.name?.toLowerCase().includes(q) || D.clientById(p.client_id)?.name?.toLowerCase().includes(q);
    return matchesStage && matchesSearch;
  });
  const { page, setPage, totalPages, slice } = usePagination(filtered, 10);
  const [drawer, setDrawer] = useStateA(false);
  const [editId, setEditId] = useStateA(null);
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA(null);
  const [confirmDelete, setConfirmDelete] = useStateA(null);
  const [deleting, setDeleting] = useStateA(false);
  const [form, setForm] = useStateA({ name:'', client_id:'', description:'', stage:'En revisión', allocated_hours:40, started_on:'', client_can_view_hours:true, client_can_view_bugs:true, client_can_view_reports:true });
  const update = (k,v) => setForm(f => ({...f, [k]:v}));

  function openCreate() {
    setEditId(null);
    setForm({ name:'', client_id:'', description:'', stage:'En revisión', allocated_hours:40, started_on:'', client_can_view_hours:true, client_can_view_bugs:true, client_can_view_reports:true });
    setError(null);
    setDrawer(true);
  }
  function openEdit(p) {
    setEditId(p.id);
    setForm({ name:p.name||'', client_id:p.client_id||'', description:p.description||'', stage:p.stage||'En revisión', allocated_hours:p.allocated||40, started_on:p.started_on||p.start||'', client_can_view_hours:p.client_can_view_hours!==false, client_can_view_bugs:p.client_can_view_bugs!==false, client_can_view_reports:p.client_can_view_reports!==false });
    setError(null);
    setDrawer(true);
  }

  async function handleSave() {
    setSaving(true); setError(null);
    try {
      if (editId) {
        await BugzeroAPI.projects.update(editId, form);
      } else {
        await BugzeroAPI.projects.create(form);
      }
      await refreshData();
      setDrawer(false);
      setForm({ name:'', client_id:'', description:'', stage:'En revisión', allocated_hours:40, started_on:'', client_can_view_hours:true, client_can_view_bugs:true, client_can_view_reports:true });
      setEditId(null);
    } catch (e) {
      setError(e.message || 'Error al guardar proyecto');
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!confirmDelete) return;
    setDeleting(true);
    try {
      await BugzeroAPI.projects.remove(confirmDelete);
      await refreshData();
      setConfirmDelete(null);
    } catch (e) {
      alert(e.message || 'Error al eliminar');
    } finally {
      setDeleting(false);
    }
  }

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Proyectos</h1>
          <p className="page-sub">{D.projects.length} proyectos · {D.projects.filter(p=>p.stage!=='Finalizado').length} en curso</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={openCreate}><Icon.Plus width="14" height="14"/> Nuevo proyecto</button>
        </div>
      </div>

      <div className="filter-bar">
        <Icon.Search width="14" height="14" style={{color:'var(--text-3)'}}/>
        <input className="input" placeholder="Buscar proyecto…" style={{border:'none', padding:0, flex:1}} value={search} onChange={e=>{setSearch(e.target.value); setPage(1);}}/>
        <div style={{width:1, height:18, background:'var(--border)'}}/>
        {['Todos', ...D.stages].map(s => (
          <button key={s} className={`filter-pill ${stageFilter===s?'active':''}`} onClick={()=>{setStageFilter(s); setPage(1);}}>{s}</button>
        ))}
      </div>

      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th>Proyecto</th><th>Cliente</th><th>Estado</th>
              <th style={{textAlign:'right'}}>Avance</th>
              <th style={{textAlign:'right'}}>Horas</th>
              <th style={{textAlign:'right'}}>Bugs</th>
              <th>Última actividad</th><th></th>
            </tr>
          </thead>
          <tbody>
            {slice.map(p => {
              const c = D.clientById(p.client_id);
              const pct = p.allocated ? Math.min(100, (p.hours/p.allocated)*100) : 0;
              return (
                <tr key={p.id}>
                  <td style={{cursor:'pointer'}} onClick={()=>onOpenProject(p.id)}>
                    <div className="cell-strong">{p.name}</div>
                    <div className="cell-muted" style={{fontSize:11.5, marginTop:2}}>Inició {p.started_on?.slice(0,10)}</div>
                  </td>
                  <td style={{cursor:'pointer'}} onClick={()=>onOpenProject(p.id)}><div className="row" style={{gap:8}}><div className="client-avatar" style={{width:24, height:24, fontSize:10, borderRadius:6}}>{c?.name?.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()}</div>{c?.name}</div></td>
                  <td style={{cursor:'pointer'}} onClick={()=>onOpenProject(p.id)}><Badge tone={D.stageBadge(p.stage)} dot>{p.stage}</Badge></td>
                  <td style={{width:160, cursor:'pointer'}} onClick={()=>onOpenProject(p.id)}>
                    <div className="row" style={{gap:8}}>
                      <div className="bar" style={{flex:1}}><span style={{width:pct+'%'}}/></div>
                      <span className="mono" style={{fontSize:11.5, color:'var(--text-3)', minWidth:32, textAlign:'right'}}>{Math.round(pct)}%</span>
                    </div>
                  </td>
                  <td style={{textAlign:'right', cursor:'pointer'}} className="num" onClick={()=>onOpenProject(p.id)}>{p.hours?.toFixed(1)} / {p.allocated}</td>
                  <td style={{textAlign:'right', cursor:'pointer'}} className="num" onClick={()=>onOpenProject(p.id)}>
                    {p.bugs_open > 0 ? <span style={{color:'var(--danger)', fontWeight:500}}>{p.bugs_open} abiertos</span> : <span className="cell-muted">0</span>}
                    <div className="cell-muted" style={{fontSize:11}}>de {p.bugs_total} totales</div>
                  </td>
                  <td className="cell-muted" style={{cursor:'pointer'}} onClick={()=>onOpenProject(p.id)}>{p.last_activity?.slice(0,10)}</td>
                  <td><ActionMenu onEdit={()=>openEdit(p)} onDelete={()=>setConfirmDelete(p.id)}/></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <Paginator page={page} totalPages={totalPages} onChange={setPage}/>

      <ConfirmDialog open={!!confirmDelete} title="Eliminar proyecto" message="Se eliminarán todas las horas, bugs, reportes y evidencia asociados. ¿Continuar?" onConfirm={handleDelete} onCancel={()=>setConfirmDelete(null)} loading={deleting}/>

      <Drawer
        open={drawer}
        onClose={()=>setDrawer(false)}
        title={editId ? 'Editar proyecto' : 'Nuevo proyecto'}
        footer={<>
          <button className="btn" onClick={()=>setDrawer(false)} disabled={saving}>Cancelar</button>
          <button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving?(editId?'Guardando…':'Creando…'):(editId?'Guardar cambios':'Crear proyecto')}</button>
        </>}
      >
        <div className="col" style={{gap:14}}>
          {error && <div style={{padding:'10px 12px', borderRadius:8, background:'rgba(220,50,50,0.12)', color:'#ff8a8a', fontSize:13}}>{error}</div>}
          <div className="field"><label className="label">Nombre del proyecto</label><input className="input" value={form.name} onChange={e=>update('name',e.target.value)} placeholder="Ej. Checkout v3.2"/></div>
          <div className="field">
            <label className="label">Cliente asignado</label>
            <select className="select" value={form.client_id} onChange={e=>update('client_id',e.target.value)}>
              <option value="">Seleccionar…</option>
              {D.clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div className="grid-2">
            <div className="field"><label className="label">Fecha de inicio</label><input className="input" type="date" value={form.started_on} onChange={e=>update('started_on',e.target.value)}/></div>
            <div className="field"><label className="label">Horas estimadas</label><input className="input" type="number" value={form.allocated_hours} onChange={e=>update('allocated_hours',e.target.value)} placeholder="40"/></div>
          </div>
          <div className="field">
            <label className="label">Estado inicial</label>
            <select className="select" value={form.stage} onChange={e=>update('stage',e.target.value)}>{D.stages.map(s => <option key={s}>{s}</option>)}</select>
          </div>
          <div className="field"><label className="label">Descripción / alcance</label><textarea className="textarea" rows="4" value={form.description} onChange={e=>update('description',e.target.value)} placeholder="Qué se va a probar, ambientes, accesos…"/></div>
          <div className="field">
            <label className="label">Visible para el cliente</label>
            <div className="row" style={{gap:14, padding:'10px 0'}}>
              <label className="row" style={{gap:8, fontSize:13}}><input type="checkbox" checked={form.client_can_view_hours} onChange={e=>update('client_can_view_hours',e.target.checked)}/> Ver horas trabajadas</label>
              <label className="row" style={{gap:8, fontSize:13}}><input type="checkbox" checked={form.client_can_view_bugs} onChange={e=>update('client_can_view_bugs',e.target.checked)}/> Ver bugs e incidencias</label>
              <label className="row" style={{gap:8, fontSize:13}}><input type="checkbox" checked={form.client_can_view_reports} onChange={e=>update('client_can_view_reports',e.target.checked)}/> Descargar reportes</label>
            </div>
          </div>
        </div>
      </Drawer>
    </div>
  );
}

// =============================================================== HOURS LOG
function AdminHours() {
  const D = useStore();
  const [open, setOpen] = useStateA(false);
  const [editId, setEditId] = useStateA(null);
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA(null);
  const [confirmDelete, setConfirmDelete] = useStateA(null);
  const [deleting, setDeleting] = useStateA(false);
  const [form, setForm] = useStateA({ worked_on:'', hours:'2.5', project_id:'', description:'' });
  const update = (k,v) => setForm(f => ({...f, [k]:v}));

  function openCreate() {
    setEditId(null);
    setForm({ worked_on:'', hours:'2.5', project_id:'', description:'' });
    setError(null);
    setOpen(true);
  }
  function openEdit(h) {
    setEditId(h.id);
    setForm({ worked_on:h.date||'', hours:String(h.hrs||''), project_id:h.project||'', description:h.task||'' });
    setError(null);
    setOpen(true);
  }

  async function handleSave() {
    setSaving(true); setError(null);
    try {
      if (editId) {
        await BugzeroAPI.hours.update(editId, form);
      } else {
        await BugzeroAPI.hours.create(form);
      }
      await refreshData();
      setOpen(false);
      setForm({ worked_on:'', hours:'2.5', project_id:'', description:'' });
      setEditId(null);
    } catch (e) {
      setError(e.message || 'Error al guardar horas');
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!confirmDelete) return;
    setDeleting(true);
    try {
      await BugzeroAPI.hours.remove(confirmDelete);
      await refreshData();
      setConfirmDelete(null);
    } catch (e) {
      alert(e.message || 'Error al eliminar');
    } finally {
      setDeleting(false);
    }
  }

  const groupedByDate = useMemoA(() => {
    const map = {};
    D.hours.forEach(h => { (map[h.date] = map[h.date] || []).push(h); });
    return Object.entries(map).sort((a,b) => b[0].localeCompare(a[0]));
  }, [D.hours]);
  const totalHrs = D.totalHours();
  const totalCost = D.totalIncome();
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Registro de horas</h1>
          <p className="page-sub">Quincena del 06 al 20 de mayo · {D.hours.length} entradas registradas</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary" onClick={openCreate}><Icon.Plus width="14" height="14"/> Registrar hora</button>
        </div>
      </div>

      <div className="grid-3" style={{marginBottom:16}}>
        <StatCard label="Horas registradas" value={`${totalHrs.toFixed(1)}h`} hint="quincena en curso"/>
        <StatCard label="Tarifa aplicada" value={`$${D.RATE}`} hint="MXN / hora"/>
        <StatCard label="Costo acumulado" value={D.fmtMxnShort(totalCost)} hint="MXN — cierre 20 may"/>
      </div>

      <div className="card">
        <div className="card-header">
          <div className="card-title">Bitácora detallada</div>
          <div className="row" style={{gap:8}}>
            <select className="select" style={{padding:'5px 26px 5px 10px', fontSize:12}}>
              <option>Quincena actual</option>
              <option>Quincena anterior</option>
              <option>Mes en curso</option>
              <option>Personalizado…</option>
            </select>
            <select className="select" style={{padding:'5px 26px 5px 10px', fontSize:12}}>
              <option>Todos los proyectos</option>
              {D.projects.map(p => <option key={p.id}>{p.name}</option>)}
            </select>
          </div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Fecha</th><th>Proyecto</th><th>Descripción</th>
              <th style={{textAlign:'right'}}>Horas</th>
              <th style={{textAlign:'right'}}>Costo</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {groupedByDate.map(([date, items]) => (
              <FragmentA key={date}>
                <tr>
                  <td colSpan="6" style={{background:'var(--surface-2)', padding:'8px 16px', fontSize:11.5, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-3)', fontWeight:500}}>
                    <div className="row" style={{justifyContent:'space-between'}}>
                      <span>{date}</span>
                      <span className="mono">{items.reduce((s,h)=>s+h.hrs,0).toFixed(1)}h · {D.fmtMxn(items.reduce((s,h)=>s+h.hrs*D.RATE,0))}</span>
                    </div>
                  </td>
                </tr>
                {items.map(h => {
                  const p = D.projectById(h.project);
                  const c = D.clientById(p.client_id);
                  return (
                    <tr key={h.id}>
                      <td className="mono cell-muted">{h.date.slice(-5)}</td>
                      <td>
                        <div className="cell-strong">{p.name}</div>
                        <div className="cell-muted" style={{fontSize:11.5}}>{c.name}</div>
                      </td>
                      <td style={{maxWidth:420}}>{h.task}</td>
                      <td style={{textAlign:'right'}} className="num">{h.hrs.toFixed(1)}</td>
                      <td style={{textAlign:'right'}} className="num">{D.fmtMxn(h.hrs * D.RATE)}</td>
                      <td><ActionMenu onEdit={()=>openEdit(h)} onDelete={()=>setConfirmDelete(h.id)}/></td>
                    </tr>
                  );
                })}
              </FragmentA>
            ))}
          </tbody>
          <tfoot>
            <tr>
              <td colSpan="3" style={{padding:'14px 16px', fontWeight:600, fontSize:13.5}}>Total quincena</td>
              <td style={{textAlign:'right', padding:'14px 16px', fontWeight:600}} className="num">{totalHrs.toFixed(1)}h</td>
              <td style={{textAlign:'right', padding:'14px 16px', fontWeight:600}} className="num">{D.fmtMxn(totalCost)}</td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>

      <ConfirmDialog open={!!confirmDelete} title="Eliminar registro de horas" message="¿Eliminar esta entrada del registro? Se actualizará el total de la quincena." onConfirm={handleDelete} onCancel={()=>setConfirmDelete(null)} loading={deleting}/>

      <Drawer
        open={open}
        onClose={()=>setOpen(false)}
        title={editId ? 'Editar horas' : 'Registrar horas'}
        footer={<>
          <button className="btn" onClick={()=>setOpen(false)} disabled={saving}>Cancelar</button>
          <button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving?(editId?'Guardando…':'Guardando…'):(editId?'Guardar cambios':'Guardar entrada')}</button>
        </>}
      >
        <div className="col" style={{gap:14}}>
          {error && <div style={{padding:'10px 12px', borderRadius:8, background:'rgba(220,50,50,0.12)', color:'#ff8a8a', fontSize:13}}>{error}</div>}
          <div className="grid-2">
            <div className="field"><label className="label">Fecha</label><input className="input" type="date" value={form.worked_on} onChange={e=>update('worked_on',e.target.value)}/></div>
            <div className="field"><label className="label">Horas trabajadas</label><input className="input" type="number" step="0.25" value={form.hours} onChange={e=>update('hours',e.target.value)}/></div>
          </div>
          <div className="field">
            <label className="label">Proyecto</label>
            <select className="select" value={form.project_id} onChange={e=>update('project_id',e.target.value)}>
              <option value="">Seleccionar…</option>
              {D.projects.map(p => <option key={p.id} value={p.id}>{p.name} — {D.clientById(p.client_id)?.name}</option>)}
            </select>
          </div>
          <div className="field"><label className="label">Descripción del trabajo</label><textarea className="textarea" rows="4" value={form.description} onChange={e=>update('description',e.target.value)} placeholder="Qué se probó, en qué módulo, qué hallazgos…"/></div>
          <div className="card-pad" style={{background:'var(--surface-2)', borderRadius:8, border:'1px solid var(--border)'}}>
            <div className="row" style={{justifyContent:'space-between'}}>
              <div>
                <div style={{fontSize:11.5, color:'var(--text-3)', textTransform:'uppercase', letterSpacing:'0.06em'}}>Costo estimado</div>
                <div style={{fontSize:22, fontWeight:600, marginTop:4, fontVariantNumeric:'tabular-nums'}}>{D.fmtMxn((parseFloat(form.hours)||0)*D.RATE)} <span style={{fontSize:13, color:'var(--text-3)'}}>MXN</span></div>
              </div>
              <div style={{fontSize:12, color:'var(--text-3)', textAlign:'right'}}>
                {(parseFloat(form.hours)||0).toFixed(2)}h × ${D.RATE}/h<br/>
                Se incluirá en quincena actual
              </div>
            </div>
          </div>
        </div>
      </Drawer>
    </div>
  );
}

Object.assign(window, { AdminDashboard, AdminClients, AdminProjects, AdminHours });
