// ===== App shell: sidebar + topbar =====

const NAV = [
  { id: "dashboard", label: "Inicio", icon: "home" },
  { id: "orders",    label: "Órdenes de trabajo", icon: "orders" },
  { id: "equipos",   label: "Equipos (Historial)", icon: "device" },
  { id: "clientes",  label: "Clientes", icon: "clients" },
];
const NAV_GESTION = [
  { id: "pos",        label: "Punto de venta", icon: "wallet" },
  { id: "inventario", label: "Inventario", icon: "box" },
  { id: "finanzas",   label: "Finanzas", icon: "money" },
  { id: "asistencia", label: "Reloj / Asistencia", icon: "clock" },
  { id: "notif",      label: "Notificaciones", icon: "bell" },
  { id: "stats",      label: "Estadísticas", icon: "chart" },
];
const NAV_BOTTOM = [
  { id: "config", label: "Configuración del taller", icon: "settings" },
];

function Sidebar({ route, onNav, orders, user }){
  const open = orders.filter(o => STATUSES[o.status].stage !== "salida").length;
  const entrada = orders.filter(o => STATUSES[o.status].stage === "entrada").length;
  const perms = ROLES[user?.roleId]?.perms || [];
  const NAV_PERM = { dashboard:null, orders:"orders_view", equipos:"orders_view", clientes:"clients", pos:"orders_create", inventario:"orders_create", finanzas:"stats", asistencia:"orders_view", notif:"clients", stats:"stats", config:"config" };
  const allow = (id) => { const p = NAV_PERM[id]; return !p || perms.includes(p); };
  function NavItem({ item }){
    const active = route === item.id;
    const [hover, setHover] = React.useState(false);
    const badge = item.id === "orders" ? open : null;
    return (
      <button onClick={()=>onNav(item.id)}
        onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
        style={{
          display:"flex", alignItems:"center", gap:11, width:"100%", padding:"10px 12px",
          borderRadius:10, border:"none", textAlign:"left", position:"relative",
          background: active ? "var(--accent-soft)" : hover ? "var(--surface-2)" : "transparent",
          color: active ? "var(--accent-ink)" : "var(--ink-2)",
          fontSize:14, fontWeight: active ? 700 : 500, transition:"background .14s, color .14s",
        }}>
        {active && <span style={{ position:"absolute", left:0, top:"50%", transform:"translateY(-50%)", width:3, height:18, borderRadius:99, background:"var(--accent)" }} />}
        <Icon name={item.icon} size={19} strokeWidth={active?1.9:1.7} />
        <span style={{ flex:1 }}>{item.label}</span>
        {badge != null && badge > 0 && (
          <span style={{ minWidth:20, height:20, padding:"0 6px", borderRadius:99, fontSize:11.5, fontWeight:700,
            display:"flex", alignItems:"center", justifyContent:"center",
            background: active ? "var(--accent)" : "var(--line)", color: active ? "#fff" : "var(--muted)" }}>{badge}</span>
        )}
      </button>
    );
  }
  return (
    <aside style={{
      width:"var(--sidebar-w)", flexShrink:0, height:"100%", background:"var(--surface)",
      borderRight:"1px solid var(--line)", display:"flex", flexDirection:"column", padding:"18px 14px", overflow:"hidden",
    }}>
      <div style={{ padding:"4px 8px 18px", flexShrink:0 }}><Logo /></div>

      <Btn icon="plus" size="md" style={{ width:"100%", marginBottom:18, flexShrink:0 }} onClick={()=>onNav("new")}>Nueva orden de ingreso</Btn>

      <div style={{ flex:1, minHeight:0, overflowY:"auto", overflowX:"hidden", margin:"0 -6px", padding:"0 6px" }}>
        <nav style={{ display:"flex", flexDirection:"column", gap:3 }}>
          <div style={{ fontSize:11, fontWeight:700, color:"var(--faint)", textTransform:"uppercase", letterSpacing:"0.08em", padding:"6px 12px 8px" }}>Centro de servicios</div>
          {NAV.filter(i=>allow(i.id)).map(item => <NavItem key={item.id} item={item} />)}
        </nav>

        {NAV_GESTION.some(i=>allow(i.id)) && (
          <nav style={{ display:"flex", flexDirection:"column", gap:3, marginTop:14 }}>
            <div style={{ fontSize:11, fontWeight:700, color:"var(--faint)", textTransform:"uppercase", letterSpacing:"0.08em", padding:"6px 12px 8px" }}>Gestión</div>
            {NAV_GESTION.filter(i=>allow(i.id)).map(item => <NavItem key={item.id} item={item} />)}
          </nav>
        )}
      </div>

      <div style={{ flexShrink:0, paddingTop:12, display:"flex", flexDirection:"column", gap:3 }}>
        {/* mini status card — hidden on short viewports to keep nav usable */}
        <div className="cp-status-card" style={{ margin:"0 4px 14px", padding:"13px 14px", borderRadius:12, background:"linear-gradient(135deg, var(--st-listo-soft), var(--surface-2))", border:"1px solid var(--line)" }}>
          <div style={{ display:"flex", alignItems:"center", gap:7, fontSize:13, fontWeight:700, color:"var(--st-listo)", whiteSpace:"nowrap" }}>
            <Icon name="check" size={16} /> Taller al día
          </div>
          <div style={{ fontSize:12.5, color:"var(--muted)", marginTop:5, lineHeight:1.35 }}>{entrada} equipos esperando diagnóstico</div>
        </div>
        {NAV_BOTTOM.filter(i=>allow(i.id)).map(item => <NavItem key={item.id} item={item} />)}
      </div>
    </aside>
  );
}

function Topbar({ route, user, onLogout, onNav, query, setQuery, myShift, onPunch, onProfile }){
  const titles = {
    dashboard:"Inicio", orders:"Órdenes de trabajo", equipos:"Equipos (Historial)",
    clientes:"Clientes", stats:"Estadísticas", config:"Configuración",
    inventario:"Inventario", finanzas:"Finanzas", asistencia:"Reloj / Asistencia", notif:"Notificaciones", pos:"Punto de venta",
    new:"Nueva orden de ingreso", detail:"Detalle de la orden",
  };
  const crumbs = { dashboard:["Principal"], orders:["Principal","Taller","Órdenes"], new:["Principal","Taller","Nueva orden"], detail:["Principal","Taller","Órdenes","Detalle"] };
  const [menu, setMenu] = React.useState(false);
  const tech = getTech(user.techId);
  const today = new Date().toLocaleDateString("es-ES", { day:"2-digit", month:"long", year:"numeric" });

  return (
    <header style={{
      height:64, flexShrink:0, background:"var(--surface)", borderBottom:"1px solid var(--line)",
      display:"flex", alignItems:"center", gap:16, padding:"0 22px",
    }}>
      <div style={{ minWidth:0 }}>
        <div style={{ display:"flex", alignItems:"center", gap:7, fontSize:12.5, color:"var(--faint)", marginBottom:1 }}>
          {(crumbs[route]||["Principal"]).map((c,i,a)=>(
            <React.Fragment key={i}>
              <span style={{ fontWeight: i===a.length-1?600:500, color: i===a.length-1?"var(--muted)":"var(--faint)" }}>{c}</span>
              {i<a.length-1 && <Icon name="chevronRight" size={13} />}
            </React.Fragment>
          ))}
        </div>
        <h1 style={{ fontSize:18, fontWeight:800, margin:0, letterSpacing:"-0.01em" }}>{titles[route]||"Casepoint"}</h1>
      </div>

      {/* search */}
      <div style={{ position:"relative", flex:1, maxWidth:420, marginLeft:18 }}>
        <span style={{ position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)" }}><Icon name="search" size={17} /></span>
        <input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Buscar orden, cliente o equipo…"
          onFocus={()=>route!=="orders"&&onNav("orders")}
          style={{ width:"100%", padding:"9px 12px 9px 37px", fontSize:13.5, borderRadius:10, border:"1px solid var(--line)", background:"var(--surface-2)", outline:"none", color:"var(--ink)" }} />
      </div>

      <div style={{ display:"flex", alignItems:"center", gap:4, marginLeft:"auto" }}>
        <button onClick={onPunch} title={myShift?"Marcar salida":"Marcar entrada"}
          style={{ display:"flex", alignItems:"center", gap:7, padding:"7px 12px", borderRadius:10, marginRight:6, cursor:"pointer", fontSize:13, fontWeight:600,
            border:`1px solid ${myShift?"oklch(0.85 0.07 155)":"var(--line)"}`, background: myShift?"var(--st-listo-soft)":"var(--surface-2)", color: myShift?"var(--st-listo)":"var(--ink-2)" }}>
          <Icon name="clock" size={16} /> {myShift ? `En turno · ${fmtHours(attHours(myShift))}` : "Fichar entrada"}
        </button>
        <IconBtn icon="bell" title="Notificaciones" badge={3} onClick={()=>onNav("notif")} />
        <div style={{ width:1, height:26, background:"var(--line)", margin:"0 6px" }} />
        <div style={{ position:"relative" }}>
          <button onClick={()=>setMenu(m=>!m)} style={{ display:"flex", alignItems:"center", gap:9, padding:"5px 8px 5px 5px", borderRadius:99, border:"1px solid var(--line)", background:"var(--surface)" }}>
            <Avatar name={user.name} initials={user.initials || tech?.initials} hue={user.hue || tech?.hue || 256} size={30} />
            <div style={{ textAlign:"left", lineHeight:1.15 }}>
              <div style={{ fontSize:13, fontWeight:700 }}>{user.name}</div>
              <div style={{ fontSize:11.5, color:"var(--muted)" }}>{user.role}</div>
            </div>
            <Icon name="chevronDown" size={15} style={{ color:"var(--faint)", marginLeft:2 }} />
          </button>
          {menu && (
            <>
              <div onClick={()=>setMenu(false)} style={{ position:"fixed", inset:0, zIndex:40 }} />
              <div style={{ position:"absolute", right:0, top:"calc(100% + 8px)", width:200, background:"var(--surface)", border:"1px solid var(--line)", borderRadius:12, boxShadow:"var(--shadow-lg)", padding:6, zIndex:41, animation:"popIn .14s ease" }}>
                <MenuItem icon="user" label="Mi perfil" onClick={()=>{setMenu(false);onProfile&&onProfile();}} />
                <MenuItem icon="settings" label="Preferencias" onClick={()=>{setMenu(false);onNav("config");}} />
                <div style={{ height:1, background:"var(--line)", margin:"5px 0" }} />
                <MenuItem icon="logout" label="Cerrar sesión" danger onClick={onLogout} />
              </div>
            </>
          )}
        </div>
      </div>
    </header>
  );
}

function MenuItem({ icon, label, onClick, danger }){
  const [h, setH] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
      style={{ display:"flex", alignItems:"center", gap:10, width:"100%", padding:"9px 10px", borderRadius:8, border:"none",
        background: h ? (danger?"var(--danger-soft)":"var(--surface-2)") : "transparent",
        color: danger ? "var(--danger)" : "var(--ink-2)", fontSize:13.5, fontWeight:600, textAlign:"left" }}>
      <Icon name={icon} size={17} /> {label}
    </button>
  );
}

Object.assign(window, { Sidebar, Topbar, NAV });
